[Python-Dev] Unbound methods (was: Sorting)

Oleg Broytman phd at phdru.name
Thu Apr 6 06:08:00 EDT 2017


On Thu, Apr 06, 2017 at 12:24:47PM +1000, Steven D'Aprano <steve at pearwood.info> wrote:
> On Thu, Apr 06, 2017 at 02:30:06AM +0200, Oleg Broytman wrote:
> > I spent few days hunting
> > for a subtle bug caused by absent of unbound methods.
> >    Painful. :-(
> I'm curious about this. What do you mean? Python 3 has unbound methods, 
> they're just the original, unwrapped function:
> py> class K:
> ...     def method(self, arg):
> ...             pass
> ...
> py> K.method
> <function K.method at 0xb7cbd6a4>

   I know.

> The only(?) functional difference between unbound methods in Python 2 
> versus 3 is that in Python 2 they automatically do a type-check that 
> `self` is an instance of the class.

   The check was involved, yes. The bug I was hunting manifested itself
in PY3 with exceptions hinting that instead of `self` I've passed
`self.__class__`. In PY2 everything worked fine.
   I found the problem in dynamically created methods. Someone
implemented them this way:

if PY2:
    def createMethod(func, cls):
        return types.MethodType(func, None, cls)
    def createMethod(func, cls):
        return types.MethodType(func, None)

   Hard to spot at the first glance what was the problem. Finally I grok
the problem and fixed the implementation for PY3 to

    def createMethod(func, cls):
        return func

> -- 
> Steve

     Oleg Broytman            http://phdru.name/            phd at phdru.name
           Programmers don't die, they just GOSUB without RETURN.

More information about the Python-Dev mailing list