Question on metaclasses
Diez B. Roggisch
deetsNOSPAM at web.de
Sun Apr 24 10:20:16 EDT 2005
Steffen Glückselig wrote:
> Hello,
>
> I've been experimenting with metaclasses a bit (even though I am quite
> a newbie to python) and stumpled over the following problem in my code:
>
> class Meta(type):
> def __init__(cls, name, bases, dct):
> for attr, value in dct.items():
> if callable(value):
> dct[attr] = wrapper(value)
>
> wrapper adds debugging-information to methods of the class (at least
> that is my plan).
>
> Using dct[attr] = wrapper(value) does not result in wrapped methods,
> though. Using setattr(cls, attr, wrapper(value)) creates the desired
> effect, though.
>
> Why are the changes to dct not visible in the instantiated class? Is
> dct not the namespace of the class currently instantiated?
You don't use metaclasses correctly I believe. Usage should look like this:
class Foo(type):
def __new__(cls, name, bases, dict):
for k,v in [(k, v) for k,v in dict.items() if callable(v)]:
cls.wrap(k,v,cls.get_directives(v), dict)
return super(Foo, self).__new__(self, name, bases, dict)
Notice the __new__ instead of __init__, and the call to (actually, through
super) type.__new__
--
Regards,
Diez B. Roggisch
More information about the Python-list
mailing list