Metaclasses vs. standard Python reflection?

Jack Diederich jack at performancedrivers.com
Fri May 2 04:43:36 EDT 2003


On Fri, May 02, 2003 at 07:02:09AM +0000, Alex Martelli wrote:
> Jeremy Fincher wrote:
> 
> > I've been looking for examples of metaclasses I can use for a talk I'm
> > going to be giving next week, but I've been having trouble finding
> > examples that solve problems that wouldn't just as easily be via
> > Python's uber-reflective __getattr__/__setattr__ and inheritance.
> > Does anyone have a good example of a problem that's solved more
> > "beautifully" with metaclasses than with Python's standard reflection
> > facilities?
> 
> If you want to affect the behavior of the class object itself (rather
> than the behavior of its instances) you _have_ to do it with a custom
> metaclass -- __getattr__/__setattr__ are just not an option here.
> 
> There have been many significant custom-metaclasses posted in this
> group (and google advanced groups search lets you search for them
> quite easily).  Metaclasses offer more control (require less
> cooperation from the user of the framework and let errors be
> diagnosed more easily), better performance (you pay the price
> at class-creation time rather than on each and every operation),
> AND more functionality (control operations on the class itself).

Alex said it well.  The original question could have been:

What can you do with while or for loops that you can't do with if and goto?

metaclasses are like that while or for loop, you can work around their absence
but it is nice not to have to.  metaclasses make some hard things easier and 
less error prone.  There are a number of ways to get the same effect, but none
as tidy.  Other languages solve the same problem with code generation tools[1]
.  metaclasses just make python a little cleaner and clearer if you need to
do something unusual.

And definitely do the groups.google search, metaclasses are newish and not
widely used (and definitely not widely documented) so most of the info you'll
find is in old c.l.py postings[2].

-jackdied

[1] lex & yacc are a good example of C's way to generate code.
    Compare with the inspection based approach in PLY (Python Lex Yacc)
      (savannah.nongnu.org/projects/ply/)
    Compare a PLY refactored to use metaclasses 
      (jackdied.com/cgi-bin/viewcvs.cgi/pymud/parse/)

[2] I posted a couple examples of metaclasses patterns a day or two ago,
    I put a copy at jackdied.com/python/





More information about the Python-list mailing list