[Python-3000] Metaclass syntax?

Bill Birch birchb at tpg.com.au
Tue May 2 14:55:00 CEST 2006


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. ;-)

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?

The syntax should flag to the reader "this class is
potentially weird and does not follow the usual rules".
Putting the metaclass in a special place in the statement
makes it really obvious to the reader:

   class[StructMeta] Person:

or even use the UML stereotype syntax:

   class<<StructMeta>> Person:

How could you miss the meta-class, it's obvious!

With this syntax you could eliminate the odd-looking:

    class Address:
    """ nice big multi-line comment 
        nice big multi-line comment
        nice big multi-line comment """
        __metaclass__ = StructMeta           # see, I'm hiding!
        ...

(see : http://orangecow.org/pythonet/sketches/larch.htm)

er, that's it.
-- 
http://billbirch.wordpress.com/


More information about the Python-3000 mailing list