Slots

A new, and poorly explained, feature of Python classes.

Around version 2.2, Python rejigged its classes with some useful extensions. Unfortunately these enhancements have been explained so poorly that they appear in little published code.

One such enhancement is __slots__. An attribute of this name in a class restricts what attributes can be created in objects of that class. For example:

>>> class myclass (object):
      __slots__ = ['default']

>>> a = myclass ()
>>> a.default = 1 # allowed
>>> a.key = 3 # not allowed
exceptions.AttributeError
Traceback (most recent call last)
AttributeError: 'myclass' object has no attribute 'key'

The __slots__ class attribute earmarks places for the member variables of the given names. It otherwise prevents the implicit creation of object attributes. In plain language: if you mispell a variable name in an assignment, you don't accicdentally create and assign to a new variable. And this is very handy.

There is a caveat. The class in question must be derived from the primordial Python object (or some descendant of it) for this to work. Otherwise __slots__ has no effect. So these would work:

class myclass (list):

class myclass (dict):

while this won't:

class myclass: