method decorators and more on decorators

Themistoklis Bourdenas tbourden at doc.ic.ac.uk
Sun Jul 27 14:26:39 EDT 2008


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.

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.

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.

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:

def class_decorate(cls):
  print 'class_decorate'
  return cls

def decorate(func):
  print 'decorate'
  return func

@class_decorate
class myclass:

  @decorate
  def foo(self):
    pass

what will be the correct output?

class_decorate
decorate

or

decorate
class_decorate

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 :)

Cheers,
Themis
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080727/4f4c207b/attachment.html>


More information about the Python-list mailing list