method decorators and more on decorators

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Jul 28 06:12:38 EDT 2008


En Sun, 27 Jul 2008 15:26:39 -0300, Themistoklis Bourdenas <tbourden at doc.ic.ac.uk> escribió:

> Hi, is there any possible way to get the class or class name inside a method
> decorator? For example in the code sample below:
>
> def decorate(func):
>   print type(func)
>   return func
>
> class myclass:
>
>   @decorate
>   def foo(self):
>     pass
>
> The output of this program will be the type of the supplied func in
> decorate, i.e. method foo. However, the type is function foo, a free
> function, not an instance method myclass.foo.

Because the decorator is applied when the function is defined - and as you already noted, foo is a plain function (stored into myclass's namespace). Only when, later, the name foo is searched in the class, the descriptor protocol comes into play and a method object is built from the function and the myclass instance.

> On a related note, as the actual instance method of myclass is not foo but
> decorate(foo), why are they called method decorators? This does not decorate
> methods, they decorate functions and eventually the decorated functions
> become methods. The name method decorator sounds a bit misleading to me.

Where have you found it? I've always seen the expression "function decorator" or just "decorator", not "method decorator". 

> So returning to my original question is there any way I can get the class
> inside decorate()? I guess there is not, but just asking to make sure.

"the class inside decorate"? What do you mean? The type of the x instance in an x.foo() call? That should be determined inside the wrapped function -when it is actually called-. 

> Speaking of decorators I'd also like to ask on the pending class decorators
> that should be coming in a following version of the language. Are they going
> to be in 2.6 or just 3.0? In the following example:

Both versions come with class decorators.

> In essence what is the order of application of class decorators compared to
> the function decorators of their methods? I couldn't find any mention of
> that issue in any of the PEPs. I guess it would be the latter, following the
> behavior of metaclasses, but better be certain than speculate :)

I don't have a 2.6/3.0 Python at hand to check, but the (decorated) functions must be built before the class is created (because they are contained in the class's namespace). So the function decorators should be aplied before the class decorator... 

-- 
Gabriel Genellina




More information about the Python-list mailing list