Specifying __slots__ in a dynamically generated type

Ron Garret rNOSPAMon at flownet.com
Mon Mar 28 03:59:14 CEST 2005

In article <K-idnZPlpO4ZttrfRVn-2g at comcast.com>,
 Steven Bethard <steven.bethard at gmail.com> wrote:

> 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?
> Why don't you just write a function to create class objects?
> def f(*params):
>      class C(...):
>          ... # based on params
>      return C

I suppose I could.  When I originally started writing this code I wanted 
each of the generated classes to have its own name, and I didn't realize 
that you could accomplish this by assigning to cls.__name__ after you 
created it.  So I started down the road of using the type constructor.  
But there's not really a good reason for it now.  Maybe I'll go back and 
change my code.


More information about the Python-list mailing list