Determining if a function is a method of a class within a decorator

Piet van Oostrum piet at cs.uu.nl
Sun Jul 5 13:28:35 EDT 2009


>>>>> David Hirschfield <davidh at ilm.com> (DH) wrote:

>DH> Yeah, it definitely seems like having two separate decorators is the
>DH> solution. But the strange thing is that I found this snippet after some
>DH> deep googling, that seems to do something *like* what I want, though I
>DH> don't understand the descriptor stuff nearly well enough to get what's
>DH> happening:

>DH> http://stackoverflow.com/questions/306130/python-decorator-makes-function-forget-that-it-belongs-to-a-class

>DH> answer number 3, by ianb. It seems to indicate there's a way to introspect
>DH> and determine the class that the function is going to be bound to...but I
>DH> don't get it, and I'm not sure it's applicable to my case.

>DH> I'd love an explanation of what is going on in that setup, and if it isn't
>DH> usable for my situation, why not?

What that example does is not getting the name of the class in the
decorator, but in the bound method that is the result of the decorator
when that method is called. This is just done by asking for the class of
the self parameter. Actually they even don't do that in that example but
it could have been done. Note also that there is an error in the code:
keyargs should be kw.

There is also something special in that code: it uses the descriptor
protocol. This is necessary for a method. The descriptor protocol for
methods defines a __get__ method that transforms the unbound method into
a bound method. That code uses this to decorate the generated bound method
object instead of decorating the unbound method.

A side effect of doing the class detection at call time is that you get
the name of the subclass if you use the method on an instance of the
subclass, not the name of the class that the method was defined in:

class D(C):
     pass

D().f(1, 2) will talk about class D, not class C.

So if you would like to do something special for bound methods the
__get__ might be the proper place to do it.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list