Sub topic 2
Declaring __slots__ to Fix an Instance's Attributes
This chapter assumes you can define classes with __init__, know the difference between instance and class attributes, and are comfortable with dictionaries. By default, every instance stores its attributes in a per-instance __dict__. Declaring __slots__ tells Python to reserve a fixed set of attribute names instead.
The starting point: a dict per instance
A regular instance keeps its attributes in a dictionary. You can see it directly:
class PlainPoint:
def __init__(self, x, y):
self.x = x
self.y = y
p = PlainPoint(1, 2)
print(p.__dict__)
p.z = 3
print(p.__dict__)The first print shows {'x': 1, 'y': 2}. After p.z = 3, the dict also contains 'z'. Nothing in the class limits which names an instance may gain. Each instance pays for its own dict, and that dict can grow at any time.
Declaring __slots__
To fix the attribute names, assign a sequence of strings to __slots__ in the class body:
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(p.x, p.y)
print(hasattr(p, "__dict__"))
try:
p.z = 3
except AttributeError as exc:
print("AttributeError:", exc)This prints 1 2, then False, then an AttributeError message for the name z. The class body is nearly the same as before. The only new line is __slots__, and it changes two things:
- Instances no longer have a
__dict__. - Only the names listed in
__slots__can be assigned on an instance.
Python allocates space for the listed attributes inside the instance itself. It does not create a dict to hold them.
What you can put in __slots__
__slots__ can be a tuple, a list, or any iterable of strings. A tuple is the usual choice because it signals that the names are fixed. A single string such as __slots__ = "x" is treated as one slot named x, not as the characters of the string. Even so, a tuple with a trailing comma is clearer: ("x",).
Python reads __slots__ once, when the class is created. Changing it later has no effect on the class.
Slots do not need to be filled
A slot is a reserved place for an attribute. It does not need a value. If you never assign a listed name, reading it raises AttributeError, as if the attribute did not exist:
class Point:
__slots__ = ("x", "y")
p = Point()
try:
print(p.x)
except AttributeError:
print("x is not set yet")
p.x = 10
print(p.x)The class has no __init__, so the instance starts empty. Reading p.x fails until you assign it. After that, p.x returns 10. The next chapters explain how Python implements this behavior. For now, treat each slot as a name that is allowed but not guaranteed to be set.
Dict storage compared with slot storage
The diagram contrasts the two storage models.
The table summarizes the visible differences.
| Behavior | Regular class | Class with `__slots__` |
|---|---|---|
| `instance.__dict__` exists | Yes | No |
| Assign a new attribute name | Allowed | `AttributeError` |
| Attributes allowed | Any name | Only the listed names |
| Unassigned attribute | Never created | Reading raises `AttributeError` |
Common mistakes
- Listing a name but forgetting to assign it. Reading it later raises
AttributeError. Assign every slot in__init__unless you want it optional. - Misspelling an attribute in
__init__. With a regular class,self.colour = 1silently creates a new attribute. With slots, it raisesAttributeError, so the typo surfaces right away. This is a side effect of slots, not their purpose. - Expecting
vars(p)to work.vars()needs a__dict__, so it raisesTypeErroron a slotted instance.
Exercises
Exercise
Given class Pair: __slots__ = ("a", "b") and p = Pair(), what happens when you run p.a = 1, then p.c = 2, then print(p.b)?
Show answer
p.a = 1 succeeds because a is a listed slot. p.c = 2 raises AttributeError because c is not in __slots__ and the instance has no __dict__. Execution stops there. If the second line were removed, print(p.b) would also raise AttributeError, because b was never assigned.
Exercise
Why does hasattr(Point(1, 2), "__dict__") return False for a class that declares __slots__ = ("x", "y")?
Show answer
Declaring __slots__ tells Python to store the listed attributes in fixed storage within the instance, so it does not create the per-instance dict. With no dict, there is nowhere to add unlisted names.