So what are __slots__ and when should I use them?

Alex Martelli aleax at mail.comcast.net
Tue Nov 15 23:29:38 EST 2005


<dan.j.weber at gmail.com> wrote:

> I see some programs declaring the names of class variables in
> "__slots__". I've looked this up and the docs say something about old
> and new style classes, whatever that means. Can someone give me a
> simple, brief explanation of what __slots__ are and when I should use
> them? Thanks.

Normally, for flexibility and simplicity, every class instance carries
around a dictionary -- which is great, and very fast, _but_ does take up
a little memory per-instance.  __slots__ lets you make a class whose
instances does NOT carry a dictionary, saving tens of bytes, at a price
in simplicity and flexibility.  So, it's useful for classes whose
instances are little more than holders for a few small pieces of data,
ideally don't use inheritance (__slots__ and inheritance can mix, but
not trivially so), AND as long as you plan to have HUGE numbers of
instances of such classes "alive" at the same time, so that it matters a
lot to you to save those few bytes per instance.  The classes must be
new-type (inherit from object or some other built-in type).

Many people try to use one of __slots__'s unfortunate side effects (the
fact that it removes flexibility from the instances of classes that
define it) for other purposes (presumably because they're coming from
languages where class instances don't HAVE that flexibility, and they're
trying to use Python as if it was a different language, rather than
using Python as Python).  However, I heartily recommend that you
consider defining __slots__ only as an optimization (memory saving),
should you ever find yourself in a situation meeting all of the
requirements in the previous paragraph (if ever).


Alex



More information about the Python-list mailing list