Choosing a Metaclass?
Jeff McNeil
jeff at jmcneil.net
Thu Feb 21 13:11:36 EST 2008
Hi list,
Hopefully a quick metaclass question. In the following example, MyMeta is a
metaclass that does not inherit directly from type:
#!/usr/bin/python
class MyMeta(object):
def __new__(cls, name, bases, vars):
print "MyMeta.__new__ called for %s" % name
return type(name, bases, vars)
class MetaWrapper(object):
__metaclass__ = MyMeta
class M(MetaWrapper):
pass
[jeff at marvin ~]$ python t.py
MyMeta.__new__ called for MetaWrapper
[jeff at marvin ~]$
When I run that script, it's apparent that although M inherits from
MetaWrapper, it does not use MyMeta as it's metaclass. However, if I change
MyMeta to be a subclass of builtin type, it works as I would expect:
[jeff at marvin ~]$ cat t.py
#!/usr/bin/python
class MyMeta(type):
def __new__(cls, name, bases, vars):
print "MyMeta.__new__ called for %s" % name
return super(MyMeta, cls).__new__(cls, name, bases, vars)
class MetaWrapper(object):
__metaclass__ = MyMeta
class M(MetaWrapper):
pass
[jeff at marvin ~]$ python t.py
MyMeta.__new__ called for MetaWrapper
MyMeta.__new__ called for M
[jeff at marvin ~]$
How exactly does Python choose which MC it will use when building a class?
It doesn't seem to me that the parent class of MyMeta should matter in this
case?
Thanks!
Jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080221/399e6386/attachment.html>
More information about the Python-list
mailing list