Specifying __slots__ in a dynamically generated type

Ron Garret rNOSPAMon at flownet.com
Sun Mar 27 20:46:46 EST 2005


In article <rpH1e.366$MJ1.59152 at newshog.newsread.com>,
 Leif K-Brooks <eurleif at ecritters.biz> 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?
> 
> Using __slots__ with type() works for me:
> 
> Python 2.3.5 (#2, Feb  9 2005, 00:38:15)
> [GCC 3.3.5 (Debian 1:3.3.5-8)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> FooClass = type('foo', (object, ), {'__slots__': 'foo'})
>  >>> foo = FooClass()
>  >>> foo.bar = 1
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
> AttributeError: 'foo' object has no attribute 'bar'
>  >>> foo.foo = 2

Well, whaddya know.  I don't know how I got the idea that this didn't 
work.  Maybe I left out an underscore when I tried it.

Thanks!

rg



More information about the Python-list mailing list