Use of __slots__

Alex Martelli aleaxit at yahoo.com
Mon Feb 27 10:30:11 EST 2006


Don Taylor <nospamformeSVP at gmail.com> wrote:
   ...
> Does Python have the notion of static class attributes?

No.

> Just what was going on when I redefined my __slots__ attribute?

Nothing.

> It looks as if __slots__ is something really special, or I am managing

Yep: it acts at *class-creation time*, only -- when the class statement
executes (specifically: the class body executes, building a dict; that
dict together with the classname and tuple of bases is passed to the
metaclass, normally 'type' -- 'type' builds a slotted class iff it sees
'__slots__' as a key in the dict, otherwise a normal class).

Most other class attributes matter during the class's lifetime (e.g.,
__metaclass__ matters at class creation time, since it defines which
metaclass is called to do the class creation, but it also matters later,
since the current value of metaclass defines what specialmethods operate
on the classobject), but __slots__ doesn't.  A reasonable design choice:
all existing instances couldn't be retroactively modified to change
their slots, and having two instances of the "same class" that are
incompatible with each other would be weird.

Ideally, 'type' could transform a class's __slots__ into a readonly
property (specifically a tuple of strings, to make it immutable), to
catch any confusion about __slots__ ASAP. However, since __slots__ was
meant for extremely RARE use, and only by very advanced programmers who
fully know what they're doing, so nobody at the time took the trouble of
building such strong fences around it (it wouldn't save us many of the
huge stream of questions and misunderstandings we're getting all the
time about it, anyway).


Alex



More information about the Python-list mailing list