The language D has a feature called Uniform Function Call Syntax, which allows instance methods to be resolved using function calls.
In Python terms, the call:
x.len()
would first check if 'x' has a method 'len', and would then look for a function 'len', passing 'x' as the first argument.
The big wins are:
- the ability to override functions with more optimal class-specific implementations. (Of course, len() is a bad example, since we already have a way to override it, but there are other functions that do not have a special method).
- the readability of a.b().c().d() vs c(a.b()).d()
Here's a few links discussing the feature in D:
- First, a fairly gentle "this is cool" post:
http://www.kr41.net/2013/08/27/uniform_function_call_syntax_in_d.html
- Second, an article from the Walter Bright, the creator of D:
http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394
Has this been discussed or proposed before? I found PEP's 443 and 3124, which provide a form of function overloading, but not reordering.
It's a nice feature in a statically typed language, but I'm not sure
how well it would work in a language as dynamic as Python. There are
some questions that would need to be addressed.
1) Where should the function (or perhaps callable) be looked for? The
most obvious place is the global scope. I think it would be a bit too
far-reaching and inconsistent with other language features to reach
directly inside imported modules (not to mention that it could easily
get to be far too slow in a module with lots of imports). As a result
it would have to be imported using the "from module import function"
syntax, rather than the somewhat cleaner "import module" syntax.
While there's nothing wrong with such imports, I'm not sure I like the
thought of the language encouraging them any more than necessary.
Probably local (and by extension nonlocal) scoping is fine also. This
makes perfect sense to me:
def some_function(x):
def my_local_extension_method(self): return 42
print(x.my_local_extension_method())
2) What about getattr and hasattr? If I call hasattr(x,
"some_method"), and x has no such attribute, but there is a function
in the global scope named "some_method", should it return True? I
think the answer is no, because that could mess with duck typing. Say
I have a function that checks the methods of some object that was
passed in, and it then passes that object on to some other function:
def gatekeeper_for_f(x):
# f behaves badly if passed an x without a key_func,
# so verify that it has one.
if not hasattr(x, 'key_func'):
raise TypeError("x has no key_func")
else:
return f(x)
Okay, so suppose we pass in to gatekeeper_for_f a non-conformant
object, but there happens to be a key_func in our global scope, so
hasattr returns True. Great! gatekeeper_for_f can call x.key_func().
But that doesn't mean that *f* can call x.key_func(), if it happened
to be defined in a different global scope.
If we instead have hasattr return False though, and have getattr raise
an exception, then we have this very magical and confusing
circumstance where getattr(x, 'method') raises an exception but
x.method does not. So I don't think that's really a good scenario
either.
Also the idea makes me nervous in the thought that an incorrect
attribute access could accidentally and somewhat randomly pick up some
object from the environment. In statically typed languages this isn't
a huge concern, because the extension method has to take an
appropriately typed object as its first argument (and in C# it even
has to be explicitly marked as an extension method), so if you resolve
an extension method by accident, at least it will be something that
makes sense as a method. Without the static typing you could
mistakenly pick up arbitrary functions that have nothing at all to do
with your object.
But if you want to experiment with the idea, here's a (lightly tested)
mixin that implements the behavior:
import inspect
import types
class ExtensionMethodMixin:
def __getattr__(self, attr):
parent_frame = inspect.currentframe().f_back
if parent_frame:
try:
func = parent_frame.f_locals[attr]
except KeyError:
func = parent_frame.f_globals.get(attr)
if callable(func):
try:
__get__ = func.__get__
except AttributeError:
return types.MethodType(func, self)
else:
return __get__(self, type(self))
return super().__getattr__(attr)