[Python-3000] Metaclass syntax?

Guido van Rossum guido at python.org
Tue May 2 16:55:35 CEST 2006


On 5/2/06, Bill Birch <birchb at tpg.com.au> wrote:
> On Tue, 2 May 2006 12:36 am, Guido van Rossum wrote:
> > This has usually been solved by creating a non-meta class whose only
> > purpose is to introduce the new metaclass. You'd write
> >
> > class TheLarch(KindsOfTrees, deciduous): ...
> >
> > and the metaclass would be called KindsOfTreesMeta.
> >
> > (Of course you could come up with a different naming convention.)
> >
> Sorry, but the reader has nothing to indicate that TheLarch is a different
> _kind_ of class. It's no fair! Too much magic. It's hard to "recognize
> different types of class from quite a long way away" with this. ;-)

Too bad (you're new to Python right?). The metaclass is inherited
anyway, so this is not a new issure, and in practice it's not a
problem -- you can usually tell from what the base class is, or from
naming conventions, etc.

> KindsOfTrees is a bad example of a meta-class. A better
> example is a metaclass which behaves very differently from
> normal classes. Consider a metaclass which does not allow methods:
>
> ----------------------struct.py--------------------------
>    class StructMeta
>       ...
>    class Struct:
>       __metaclass__ = StructMeta
>       ...
>  -------------------------snip-----------------------------
>    from struct import *
>    class Person(Struct):
>
> To someone reading the second file this reads "Person inherits from struct".
> Which of course it does not, because Struct is a devious hook to pull
> in a different metaclass. What if StructMeta does not allow
> inheritance?

Then it'll be a run-time error at class definition time.

This is how metaclasses work; better get used to it. I can't imagine
how painful it would be if the metaclass *weren't* inherited -- lots
of boilerplate all over.

Please research the history of metaclasses in Python (and in general)
before making your next post.

--
--Guido van Rossum (home page: http://www.python.org/~guido/)


More information about the Python-3000 mailing list