[Python-Dev] Let's get rid of unbound methods
Phillip J. Eby
pje at telecommunity.com
Tue Jan 4 21:31:57 CET 2005
At 11:40 AM 1/4/05 -0800, Guido van Rossum wrote:
>[Jim]
> > We'll still need unbound builtin methods, so the concept won't
> > go away. In fact, the change would mean that the behavior between
> > builtin methods and python methods would become more inconsistent.
>
>Actually, unbound builtin methods are a different type than bound
>builtin methods:
>
> >>> type(list.append)
><type 'method_descriptor'>
> >>> type([].append)
><type 'builtin_function_or_method'>
> >>>
>
>Compare this to the same thing for a method on a user-defined class:
>
> >>> type(C.foo)
><type 'instancemethod'>
> >>> type(C().foo)
><type 'instancemethod'>
>
>(The 'instancemethod' type knows whether it is a bound or unbound
>method by checking whether im_self is set.)
>
>[Phillip]
> > Code that currently does 'aClass.aMethod.im_func' in order to access the
> > function object would break, as would code that inspects 'im_self' to
> > determine whether a method is a class or instance method. (Although code
> > of the latter sort would already break with static methods, I suppose.)
>
>Right. (But I think you're using the terminology in a cunfused way --
>im_self distinguishes between bould and unbound methods. Class methods
>are a different beast.)
IIUC, when you do 'SomeClass.aMethod', if 'aMethod' is a classmethod, then
you will receive a bound method with an im_self of 'SomeClass'. So, if you
are introspecting items listed in 'dir(SomeClass)', this will be your only
clue that 'aMethod' is a class method. Similarly, the fact that you get an
unbound method object if 'aMethod' is an instance method, allows you to
distinguish it from a static method (if the object is a function).
That is, I'm saying that code that looks at the type and attributes of
'aMethod' as retrieved from 'SomeClass' will now not be able to distinguish
between a static method and an instance method, because both will return a
function instance.
However, the 'inspect' module uses __dict__ rather than getattr to get at
least some attributes, so it doesn't rely on this property.
>I guess for backwards compatibility, function objects could implement
>dummy im_func and im_self attributes (im_func returning itself and
>im_self returning None), while issuing a warning that this is a
>deprecated feature.
+1 on this part if the proposal goes through.
On the proposal as a whole, I'm -0, as I'm not quite clear on what this is
going to simplify enough to justify the various semantic impacts such as
upcalls, pickling, etc. Method objects will still have to exist, so ISTM
that this is only going to streamline the "__get__(None,type)" branch of
functions' descriptor code, and the check for "im_self is None" in the
__call__ of method objects. (And maybe some eval loop shortcuts for
calling methods?)
More information about the Python-Dev
mailing list