[Python-Dev] metaclass insanity

Walter Dörwald walter@livinglogic.de
Tue, 05 Nov 2002 13:35:52 +0100


Guido van Rossum wrote:

 > [...]
 > This won't work for classes defined inside functions though -- those
 > are never picklable.  But making them module-global would be a simple
 > enough fix (also more efficient, since the class definition code is
 > executed on every function call).
 >
 > Can someone provide a reason why you'd want to use nested classes?
 > I've never felt this need myself.  What are the motivations?


XIST (http://www.livinglogic.de/Python/xist/) uses nested classes
to map XML element types and their attributes to Python classes.
For example the HTML element type img looks like this in XIST:

class img(Element):
    class Attrs(Element.Attrs):
       class src(URLAttr): required = True
       class alt(TextAttr): required = True
       class align(TextAttr): values = ("top", "middle", ...)

Having XML elements as classes makes it possible to add methods for
transforming these elements. Defining the attributes via classes is
just an extension to that, although there are moments when I'm not
so sure, whether this is the best method, but the title of this
thread is "metaclass insanity"! ;)

Bye,
    Walter Dörwald