Sub topic 2
Declaring __slots__ to fix an instance's attributes
This chapter shows how to declare __slots__ and what the declaration does to a class. It assumes you can write classes with __init__, know the difference between instance and class attributes, and know how __dict__ stores attributes by default. The previous chapter covered that default storage. Here you write the declaration and learn its rules.
What `__slots__` declares
__slots__ is a class attribute that lists the names of the instance attributes the class allows. When Python builds the class and finds this attribute in the class body, it changes how instances are laid out. Instances get reserved storage for exactly those names, and they do not get a per-instance __dict__.
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__"))The code prints 1 2 and then False. The __init__ method is ordinary Python. It assigns self.x and self.y as usual. The difference is where those values go. They are stored in fixed positions inside the instance, not in a dictionary.
The declaration is a contract. The class author lists the attribute names in advance, and Python holds every instance to that list.
The accepted forms
__slots__ can be any iterable of strings, and a single string is also accepted. In practice you will see these forms.
| Form | Example | Result |
|---|---|---|
| Tuple | `__slots__ = ("x", "y")` | Two slots, `x` and `y`. This is the usual style. |
| List | `__slots__ = ["x", "y"]` | Same two slots. |
| Single string | `__slots__ = "x"` | One slot named `x`. |
| Empty tuple | `__slots__ = ()` | No slots. Instances can hold no attributes of their own. |
| Dict | `__slots__ = {"x": "the x coordinate"}` | Slot `x`. The values are used as docstrings for the slots. |
A tuple is the convention because it signals that the list is not meant to change. The code below compares the first three forms.
class A:
__slots__ = ("x", "y")
class B:
__slots__ = ["x", "y"]
class C:
__slots__ = "x"
a, b, c = A(), B(), C()
a.x = b.x = c.x = 1
print(A.__slots__, B.__slots__, C.__slots__)The single-string form catches people out. The string is one slot name. It is not split on spaces or commas the way some other APIs treat names.
try:
class Bad:
__slots__ = "x y"
except TypeError as exc:
print("TypeError:", exc)Python rejects the class with a TypeError. The name "x y" is not a valid identifier, and every slot name must be one. Write ("x", "y") when you want two slots.
Slots are checked when the class is created
Python reads __slots__ once, while it builds the class. This has two consequences.
First, a mistake in the declaration shows up as soon as the module is imported, before any instance exists. An invalid name such as "x y" fails at class creation.
Second, adding __slots__ to a finished class has no effect on its instances. The layout was already decided.
class Late:
pass
Late.__slots__ = ("x",)
obj = Late()
obj.y = 1
print(obj.y)
print(hasattr(obj, "__dict__"))The code prints 1 and True. The class was created without a declaration, so its instances still get a __dict__ and accept any name. The declaration must be in the class body.
Assigning slots
A declared slot is a place for a value. It is not a value. Declaring x does not give x a default, and the attribute does not exist on an instance until you assign it.
class Box:
__slots__ = ("width", "height")
b = Box()
b.width = 4
print(b.width)
try:
print(b.height)
except AttributeError:
print("height is declared but not set")Reading b.height raises AttributeError, the same error Python raises for a name that was never declared. A __dict__ instance behaves like this too, so existing code that handles missing attributes keeps working. The chapter on descriptors explains the mechanism behind this behavior. For now, treat an unassigned slot as a missing attribute.
Because of this, set every slot in __init__ unless you want some slots to be optional. Skipping a slot is legal. It just means a later read of that slot fails until someone assigns it.
You can also delete a slot value with del. The slot becomes empty again, and the next read raises AttributeError.
class Counter:
__slots__ = ("count",)
c = Counter()
c.count = 3
del c.count
print(hasattr(c, "count"))The code prints False. The slot still exists, but it holds no value.
Unlisted names are rejected
The main visible effect of the declaration is that assigning an unlisted name fails. A regular class accepts any name, and a slotted class accepts only its own.
class Account:
__slots__ = ("owner", "balance")
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
acct = Account("Ana", 100)
try:
acct.balence = 50
except AttributeError as exc:
print("AttributeError:", exc)The typo balence raises AttributeError. In a regular class, that line would silently create a new attribute, and balance would keep its old value. The error text differs between Python versions, so do not match on the message. Catch the exception type if you need to handle it.
Some people use this behavior as a guard against typos. That is a side effect and a useful one. The chapter on when to use slots weighs it against the costs.
Private names and name mangling
Slot names follow the same name-mangling rule as other class-private names. A name that starts with two underscores and does not end with two underscores is rewritten to include the class name.
class Secret:
__slots__ = ("__token",)
def __init__(self, token):
self.__token = token
s = Secret("abc")
print(s._Secret__token)Python stores the slot as _Secret__token, and self.__token inside the class body is mangled to the same name. The code prints abc. If you write the private name without mangling from outside the class, the lookup fails. This is the same behavior as in a regular class.
Rules to remember
__slots__must be in the class body to affect the class.- Every name must be a valid identifier, and names must not repeat.
- A single string is one slot, not a list of slots.
- A declared slot starts empty. Reading it before assignment raises
AttributeError. - Assigning a name that is not declared raises
AttributeError, unless some class in the inheritance chain provides a__dict__. The inheritance chapter covers that case. - Slots hold per-instance values only. They do not define class-level defaults. The chapter on defaults explains why a class attribute with the same name as a slot raises an error.
A worked example
Suppose you are building a record type for sensor readings, and a program creates a large number of them. The class has a fixed set of fields, so it is a reasonable fit for slots.
class Reading:
__slots__ = ("sensor_id", "timestamp", "value")
def __init__(self, sensor_id, timestamp, value):
self.sensor_id = sensor_id
self.timestamp = timestamp
self.value = value
def __repr__(self):
return (
f"Reading(sensor_id={self.sensor_id!r}, "
f"timestamp={self.timestamp!r}, value={self.value!r})"
)
r = Reading("t-1", 1700000000, 21.5)
print(r)
for name in Reading.__slots__:
print(name, "=", getattr(r, name))
try:
r.unit = "C"
except AttributeError:
print("cannot add 'unit'")The class lists each field once, in the tuple. __repr__ and the loop work as usual, because reading a slot is an ordinary attribute read. Iterating over Reading.__slots__ is a convenient way to reach every field, with one caveat. It lists only the slots declared in that class and not slots from parent classes, so it is incomplete under inheritance. The inheritance chapter returns to this.
The last lines show the restriction. Adding unit fails, so the class cannot grow fields by accident. If a field is missing from the design, add it to the tuple. You cannot add it from outside the class.
Common mistakes
- Forgetting to declare an attribute that
__init__assigns. The failure happens the first time you create an instance, not at class creation. Python cannot check the body of__init__when it builds the class. - Writing a single string with several names.
"x y"raisesTypeError. Use a tuple. - Adding
__slots__after the class exists. The assignment succeeds and does nothing useful. - Assuming an undeclared attribute fails everywhere. A subclass with no
__slots__of its own gets a__dict__and accepts new names again. - Assuming a declared slot holds a default. It holds nothing until you assign it.
Exercises
Exercise
A class is defined as follows. What happens when you run the last line, and why? class Temperature: _slots = ("celsius",) def init_(self, celsius): self.celsius = celsius t = Temperature(20) t.fahrenheit = 68
Show answer
The last line raises AttributeError. The class declares only "celsius", and instances have no _dict where a new name could be stored. To allow the attribute, add "fahrenheit" to slots_ (or compute it with a property instead of storing it).
Exercise
Why does this class definition fail, and how do you fix it so the class has the two slots "first" and "last"? class Name: _slots_ = "first last"
Show answer
A single string is treated as one slot name, and "first last" is not a valid identifier, so Python raises TypeError when the class is created. Use a tuple or list with separate strings: _slots_ = ("first", "last").
Exercise
You run Late._slots = ("x",) on a class that was created without slots_. Instances of Late still accept obj.y = 1. Explain why.
Show answer
Python reads _slots only while it builds the class. By the time the assignment runs, the class layout is fixed and its instances already have a dict_. Setting the attribute afterward has no effect on instances. The declaration has to be in the class body.