Choosing a Metaclass?

Jeff McNeil jeff at jmcneil.net
Thu Feb 21 20:43:17 CET 2008


Never mind, I've figured it out.  The build_class function looks at the
'__class__' attribute of the first base class if there's no explicit
__metaclass__ attribute. By calling type directly, the __class__ attribute
as returned by MyMeta is, in fact, type.

Should have just looked at the source to begin with.

On 2/21/08, Jeff McNeil <jeff at jmcneil.net> wrote:
>
> 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/9ed4ede3/attachment.html>


More information about the Python-list mailing list