Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

So what are __slots__ and when should I use them?

2 views
Skip to first unread message

dan.j...@gmail.com

unread,
Nov 15, 2005, 10:05:37 PM11/15/05
to
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.

Alex Martelli

unread,
Nov 15, 2005, 11:29:38 PM11/15/05
to
<dan.j...@gmail.com> wrote:

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

MrJean1

unread,
Nov 16, 2005, 1:53:49 AM11/16/05
to
Here is an example of the difference between a class with __slots__ and
__dict__

<http://mail.python.org/pipermail/python-list/2004-May/220513.html>

/Jean Brouwers

0 new messages