[Python-3000] The case for unbound methods?
artomegus at gmail.com
Sun Mar 9 00:33:40 CET 2008
On Sat, Mar 8, 2008 at 3:28 PM, Steven Bethard <steven.bethard at gmail.com> wrote:
> Why is it so crucial that "self" is the first argument? If I use a
> decorator that adds a new element to the beginning of the argument
> list, I wouldn't be surprised that I now have to write my methods as::
> def method(new_arg, self, ...):
That would work with class binding in Python 3.0 (i.e. "unbound"
methods). In Python 2.5, doing that with an unbound method would
throw an error.
However, bound methods still force the first argument to be self. If
I want to change this behavior, then I need to grab the __func__
attribute of the method and send the parameters directly. That means
re-implementing the behavior of bound methods; i.e. inserting __self__
into the argument list.
Unfortunately, that destroys the "magic" of the bound method,
bypassing it altogether, and it could only be done once. Thus, if
another decorator wrapped this one, then the inner one would have to
present itself as a plain function (no __self__ or __func__
attributes) to the outer one. Any information about the original
method type would be lost; and I'm not sure that is a good thing.
Anyway, this isn't just about inserting arguments. It is also about
being able to inspect callables to determine their origin (static
method, bound method, unbound method), to facilitate designing
decorators that play well with one another. In my opinion, the ideal
situation is to allow information about the original method to pass
all the way up the chain of decorators.
Of course, there may be cases one would want to mask the underlying
signature (which is essentially what staticmethod does). In most
cases, however, preserving the attribute signature would be indicative
of well-behaved decorators.
More information about the Python-3000