Using metaclasses to play with decorators.

Michele Simionato michele.simionato at
Thu Jun 17 06:46:31 CEST 2004

David MacQuigg <dmq at> wrote in message news:<qea0d09mp5o68lsiu7rhmnao8689h4p8e2 at>...
> I decided to include a brief discussion of metaclasses in my chapter
> introducing Python OOP for engineering students, but if there is a
> simpler way to do what I need, I could eliminate this section and not
> be tempting students to use (and possibly abuse) metaclasses. (See
> example on p.13 in PythonOOP.doc at
> )
> I haven't given this much thought, but it occurred to me that making
> the __new__ function work in an ordinary class ( not just a metaclass
> ) would avoid the need for metaclasses in simple cases like my
> example.  If the __new__ function is present in a class, then run it
> when any new class is constructed with the current class as an
> ancestor.  In my example, all I am doing is adding a class variable
> '_count' to each new class.
> By providing this simple functionality *without* metaclasses, we can
> keep a clear line between what mere mortals need to learn, and what
> the Python developers need.
> -- Dave

You seem to think that __new__ is something related to metaclasses only
(at least I got this impression). It is not. __new__ is the generic
instance allocator; can be used inside classes to create regular instances
and inside metaclasses to create classes (and inside meta-metaclasses to
create metaclasses, etc.). In your example I would just use __init__
in the metaclass, not __new__: something like

def __init__(cls, name, bases, dic):
   cls._count = 0

But you ask if it makes sense to use a metaclass for this task or not.

Not really, you could use a function acting as a factory of classes,
or a classmethod doing the same job. Or even a function setting the 
counter to zero after the class creation in all the classes of your
hierarchy (using Animal.__subclasses__()). You would lose a bit of elegance
but you would get the same functionality. Plus, you would avoid cluttering
too much the minds of your students. Plus, you would avoid embarassing 
questions from the smartest between them (such why I get a meta-type conflict 
if I do this and that?)

There is no point in teaching everything, let them a bit of fun if they
want to :)

   Michele Simionato

More information about the Python-list mailing list