Specifying __slots__ in a dynamically generated type

Diez B. Roggisch deetsNOSPAM at web.de
Sun Mar 27 23:51:15 CEST 2005

Ron Garret wrote:

> I need to dynamically generate new types at run time.  I can do this in
> two ways.  I can use the "type" constructor, or I can generate a "class"
> statement as a string and feed that to the exec function.  The former
> technique is much cleaner all else being equal, but I want to be able to
> specify the __slots__ class variable for these new types, and it seems
> that to do that I need to use the latter method.  Is that true?  Is it
> really impossible to specify __slots__ using the "type" constructor?

This simple testscript

class Meta(type):
    def __init__(*args):
        print args
        return type(*args[1:])

class Foo(object):
    __metaclass__ = Meta
    __slots__ = "foo", "bar"


shows that __slots__ is just a part of the type's dict. So you can simply
specify it.


Diez B. Roggisch

More information about the Python-list mailing list