[Tutor] What is the metaclass for?

Gonçalo Rodrigues op73418@mail.telepac.pt
Thu Mar 6 12:14:01 2003


----- Original Message -----
From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu>
To: "Jeff Shannon" <jeff@ccvcorp.com>
Cc: <tutor@python.org>
Sent: Thursday, March 06, 2003 3:22 PM
Subject: Re: [Tutor] What is the metaclass for?


>
> > > Can someone describe under what a metaclass is for and under
> > > circumstances do we need to consider using them?
> >
> >
> > My short answer would be that metaclasses are a mechanism for black
> > magic -- or at least, very dark grey magic. ;) Odds are good that if
> > what you read about metaclasses makes no sense, then you're not likely
> > to need metaclasses for anything that you're doing -- it's a very
> > advanced subject for advanced programmers. (Read this as -- I don't know
> > just what to do with them either, so I'm sticking to what I can
> > understand! ;) They're a fairly new addition to Python and I never felt
> > limited by their absence. But they seem to make some people happy...)
>
>
> Does anyone have the Python Cookbook (dead trees version) handy?  I'm
> actually still in Santa Fe, and forgot to bring mine with me, but I
> remember seeing a really awesome example of metaclasses in one of the
> later chapters in the Python Cookbook.  I'll be back home tomorrow, so
> I'll try to correctly quote the example when I return.
>
> Concrete examples often make abstract concepts less difficult to perceive.
> Someone had once asked if the idea of an "interface" could be handled in
> Python.  Metaclasses allow us to extend Python's idea of a class to
> include interfaces:
>
>     http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/164901
>
>

<shameless-plug>

Let me add another example, also of my doing:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/149148

<\shameless-plug>

The recipes builds a metaclass whose instances are the Z_n rings of finite
arithmetic. They are infinite in number so you have to use some kind of
factory. Add to that the fact that I wanted each Z_n to be a class and the
metaclass solution becomes obvious.

All the best,
G. Rodrigues