PEP 318: Is chaining decorators even possible?

Michele Simionato mis6 at pitt.edu
Thu Jun 12 13:54:59 EDT 2003


Kevin Smith <Kevin.Smith at sas.com> wrote in message news:<20030612080349419-0400 at braeburn.themorgue.org>...
> It has been brought up a couple of times in other threads that simply 
> chaining descriptors won't work (i.e. classmethod(synchronized(foo))).  
> Another possibility was to use subclassing (i.e. type('newtype',(
> classmethod,synchronized,{})(foo)).  When I wrote PEP 318, I wasn't sure 
> myself if it was possible to chain them, but I figured someone would 
> point it out if it wasn't.  So my question is, is it even possible to 
> chain decorators in a general way? 

Here is a bare bone implementation (i.e. written in 5 minutes and probably
buggy) to show how it would work the multiple inheritance way:


class chatty(object):
    "custom decorator, printing a message when the attribute is accessed"
    def __get__(self,obj,cls):
        print "Accessing %s" % self
        return super(chatty,self).__get__(obj,cls)

class chattyclassmethod(chatty,classmethod): pass

class C(object):
    # would be def ccm(cls)[chatty,classmethod]:		
    def ccm(cls):
        return 'This is a chattyclassmethod of %s' % cls
    ccm=chattyclassmethod(ccm)
    
c=C()
print C.ccm()
print c.ccm()

with output:

Accessing <__main__.chattyclassmethod object at 0x403143ec>
This is a chattyclassmethod of <class '__main__.C'>
Accessing <__main__.chattyclassmethod object at 0x403143ec>
This is a chattyclassmethod of <class '__main__.C'>

Notice that currently classmethod is not cooperative, therefore it
would not work in the other order:

class classmethodchatty(classmethod,chatty): pass

class C(object):
    def cmc(cls):
        return 'This is a classmethodchatty of %s' % cls
    cmc=classmethodchatty(cmc)

c=C()
print C.cmc()
print c.cmc()
This is a chattyclassmethod of <class '__main__.C'>
This is a chattyclassmethod of <class '__main__.C'>

This is why I said classmethod and staticmethods should be reimplemented
(even more so if you want to use Steven's solution).

HTH,

                                     Michele




More information about the Python-list mailing list