[Python-3000] The case for unbound methods?

Anthony Tolle artomegus at gmail.com
Fri Mar 7 14:06:44 CET 2008


Greg Ewing wrote:

>  Not very well, IMO.
>
>  Without seeing a concrete use case, it's hard to be
>  sure, but my feeling is that there's almost certainly
>  a better way of thinking about the problem you're
>  trying to solve -- one that doesn't require introspecting
>  on a callable object to find out whether its implementation
>  involves a 'self' argument. That's *not* duck typing,
>  it's look-inside-before-you-leap.

>From the Python Tutorial glossary:

----------
duck-typing
    Pythonic programming style that determines an object's type by
inspection of its method or attribute signature rather than by
explicit relationship to some type object ("If it looks like a duck
and quacks like a duck, it must be a duck.") By emphasizing interfaces
rather than specific types, well-designed code improves its
flexibility by allowing polymorphic substitution. Duck-typing avoids
tests using type() or isinstance(). Instead, it typically employs
hasattr() tests or EAFP programming.
----------

That's what the code is doing. By wrapping the attribute access in a
try statement, it is essentially performing a hasattr() test.  That is
all hasattr does anyway; it tries getattr and checks if an exception
occurs.

So the question becomes, what is the 'duck test' for objects returned
by descriptors?  The test used in the example code works with Python
2.5, but fails in only one case in Python 3.0, because unbound methods
were removed.  When writing a wrapper that might wrap static methods
or instance methods (with class binding), the distinction between them
disappears when the attribute signature is the same for the the
respective callable objects.

As for a more concrete example, imagine the wrapper using the inspect
module to gather some information about the stack frame and passing it
along to selected methods.

I just like flexibility, and that's what unbound methods permitted in
2.5.  With them, the attribute signature of callable objects is
distinct for three separate cases: static methods, instance methods
with instance binding, and instance methods with class binding (class
methods are just a subset of instance methods with instance binding).

I'm not saying that unbound methods are 100% essential--I can learn to
live without them--I just think they provided some additional
flexibility, and that's a good thing in my opinion.


More information about the Python-3000 mailing list