[Python-Dev] metaclass insanity

Guido van Rossum guido@python.org
Tue, 05 Nov 2002 10:38:41 -0500


> > Can someone provide a reason why you'd want to use nested classes?
> > I've never felt this need myself.  What are the motivations?
> 
> Yes. In Reality (a Twisted Matrix Labs project), a text-based virtual
> world simulation framework, we have a system that can automatically
> generate Interface definitions from classes (with a metaclass that
> builds them at class-def time).

(Beware of using a custom metaclass per class though -- it can prevent
multiple inheritance, as I explained before in this thread.)

> Twisted has an Interface/adapter/
> componentized system similar to Zope's in twisted.python.components,
> and we use components/adapters to their fullest in Reality.
> 
> The problem is, our virtual worlds are persistent, so most of our
> objects get pickled (or serialized with some similar mechanism), and
> our objects hold references to these automatically-generated
> Interfaces. We would *like* to have these automatically-generated
> Interfaces as attributes of the classes they were generated for,
> but we have to use a hack that does something like::
> 
>     setattr(subclass.__module__, interfaceName, NewInterface)
> 
> This is really horrible, IMO.

Why didn't you choose to avoid nesting classes and use a naming
convention instead, since the nesting causes problems?

> Anyway, regardless that this may be a somewhat obscure use-case
> (although one we rely heavily on), It _is_ wrong that str(klass) is
> lying about its location, and I seriously doubt fixing it would cause
> any problems.

Agreed.  I'll respond to MvL's proposal.

--Guido van Rossum (home page: http://www.python.org/~guido/)