Understanding and working with __metaclass__
michele.simionato at poste.it
Tue Dec 9 20:19:22 CET 2003
dw-google.com at botanicus.net (David M. Wilson) wrote in message news:<99dce321.0312081149.2a32575d at posting.google.com>...
> Hi there,
> I've been sitting on the __metaclass__ feature for about 2 weeks now,
> and haven't really got that far with it. It looks like a very powerful
> tool, and I think I have even already identified places in my code
> where I could use it quite effectively, but I can't quite tell what it
> is /meant/ to be used for, or indeed what it is popularly used for.
> Is there a page, posting, or other place I can turn to to get a
> developer's run-down on the practical uses of __metaclass__? The
> Python documentation states very clearly what it does, but I fear that
> journeying off on my own with it will lead to some terrible habit
> formation, and I already have enough of those to deal with. :) (:set
> ts=3 ;)
> Thanks for your time,
Uhm ... this question has been asked here many times and I am beginning
to think it should be in the FAQ. Any volunteer for a tentative FAQ entry?
I must say that I don't have a precise opinion on the subject yet, since
in most cases you can avoid metaclasses without loosing any essential
functionality. Metaclasses are somewhat elegant, but you pay the elegance
with impliciteness and we all know that "esplicit is better than implicit".
A typical use case for metaclasses is when you have a hierarchy
written to do X, and you want it to do Y. Instead of rewriting all
the classes, a quick and dirty metaclass can give you the desired
functionality with a little effort.
Also, you can use metaclasses to debug classes.
Metaclasses allow to implement Aspect Oriented Programming for Python,
and there are already modules doing that.
With metaclasses you can modify the semantics of the language.
For instance, you could design a declarative language on top of Python.
Nevertheless, IMO these tricks don't fit well with the spirit of the
language, so even if you can do that, I am not convinced you should do
A reasonable application of metaclasses is in the writing of plugins:
you may import at runtime the same module but with different metaclasses,
changing its behaviour according to the external conditions.
See for instance
for more on this idea.
Google for "Guido metaclasses a.k.a. the killer joke" for additional
motivations. The standard distributions contains various examples
My advice: use a lot of metaclasses for experimental purposes and
playing, very little (better zero) for production code.
The fact that you can correct your design mistakes with metaclasses does
not mean that you should not correct them by rewriting you classes
from scratch ;)
More information about the Python-list