[Python-Dev] Let's get rid of unbound methods

Guido van Rossum gvanrossum at gmail.com
Tue Jan 4 20:40:30 CET 2005


[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.)

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.

[Tim]
> Really?  Unbound methods are used most often (IME) to call a
> base-class method from a subclass, like my_base.the_method(self, ...).
>  It's especially easy to forget to write `self, ` there, and the
> exception msg then is quite focused because of that extra bit of type
> checking.  Otherwise I expect we'd see a more-mysterious
> AttributeError or TypeError when the base method got around to trying
> to do something with the bogus `self` passed to it.

Hm, I hadn't thought ot this.

> I could live with that, though.

Most cases would be complaints about argument counts (it gets harier
when there are default args so the arg count is variable). Ironically,
I get those all the time these days due to the reverse error: using
super() but forgetting *not* to pass self!

> Across the Python, Zope2 and Zope3 code bases, types.UnboundMethodType
> is defined once and used once (believe it or not, in unittest.py).

But that might be because BoundMethodType is the same type object...

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-Dev mailing list