Don't use __slots__ (was Re: performance of dictionary lookup vs. object attributes)

Patrick Maupin pmaupin at gmail.com
Mon Aug 28 20:30:16 EDT 2006


Dieter Maurer wrote:
> "Patrick Maupin" <pmaupin at gmail.com> writes on 26 Aug 2006 12:51:44 -0700:
> > ...
> > The only
> > problem I personally know of is that the __slots__ aren't inherited,
>
> "__slots__" *ARE* inherited, although the rules may be a bit
> complex.

Yes, I didn't write that correctly.  What's not inherited is the lack
of a dictionary :)

>>> class foo(object):
...   __slots__ = 'a b c'.split()
...
>>> class bar(foo):
...     pass
...
>>> set(dir(foo())) - set(dir(bar()))
set([])
>>> set(dir(bar())) - set(dir(foo()))
set(['__dict__', '__weakref__'])

And you are correct that the rules are a bit complicated, but for my
purposes (memory usage reduction on non-subclassed classes) __slots__
seem to work fine.

Thanks,
Pat




More information about the Python-list mailing list