metaclasses, how you might actually use 'em

Michele Simionato mis6 at pitt.edu
Mon Apr 28 09:14:37 EDT 2003


Jack Diederich <jack at performancedrivers.com> wrote in message news:<mailman.1051458882.30400.python-list at python.org>...

> <snip evangelism to metaclasses>

All your usages of metaclasses seems to me quite typical and "good"
(to see a "bad" usage, google for my "black magic trick" ;)

> If this is known stuff or there is a better standard way just mark 
> this thread as ignored and enjoy your Sunday. 

Do you know that the standard 'type'
metaclass (and therefore all metaclasses derived from it, which means
ALL metaclasses) contains a __subclasses__ method ?

>>> dir(type)
['__base__', '__bases__', '__basicsize__', '__call__', '__class__', 
 '__cmp__', '__delattr__', '__dict__', '__dictoffset__', '__doc__', 
 '__flags__', '__getattribute__', '__hash__', '__init__', '__itemsize__', 
 '__module__', '__mro__', '__name__', '__new__', '__reduce__', '__repr__', 
 '__setattr__', '__str__', '__subclasses__', '__weakrefoffset__', 'mro']

It works this way:

>>> class C(object): pass
...
>>> class D(C): pass
...
>>> C.__subclasses__() # means type(C).__subclasses__(C)
[<class '__main__.D'>]

I think it is quite similar in spirit to your Register, isn't it ?

> Corrections encouraged, pedantry especially.

your sentence

> metaclasses just allow you to tweak a class definition on the fly.  Mainly 
> adding or removing attributes just before the class becomes 'real'. 

is correct when you redefine the __new__ method of the metaclass. However,
in your examples, you redefine the __init__ method. This means that the
class has been *already* created, i.e. it is 'real', and it is modified
*after* creation. This is just nitpicking, but since you asked for pedantry...

Have fun,

                                   Michele




More information about the Python-list mailing list