[Python-Dev] Backport PEP 3129: Class Decorators
Christian Heimes
lists at cheimes.de
Tue Jan 8 17:49:09 CET 2008
Eli Courtwright wrote:
> I can tell that instancemethods can't have attributes added to them outside
> of their class definition. Is this part of the Python language spec, or
> just an implementation detail of CPython?
You can't modify the attributes of an instance method. You have to
modify the attribute of the function object.
> I bring this up here because it makes writing certain class decorators much
> more annoying. For example, if I want to write a class decorator that will
> set "exposed=True" for every method of a class, I must resort to
> shenanigans.
No, you don't. You have to retrieve the function object from the
instance method object. The example should shed some light on the problem:
>>> class Root(object):
... def index(self):
... return "Hello World!"
... print type(index)
... index.exposed = True
...
<type 'function'>
>>> type(Root.index)
<type 'instancemethod'>
>>> Root.index.exposed
True
>>> Root.index.exposed = False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'instancemethod' object has no attribute 'exposed'
>>> Root.index.im_func
<function index at 0x8354e64>
>>> Root.index.im_func.exposed = False
>>> Root.index.exposed
False
Christian
More information about the Python-Dev
mailing list