Sub topic 3
What changes: no __dict__ and no new attributes
This chapter assumes you know how to define classes and __init__, that you can tell instance attributes from class attributes, and that you have seen __slots__ declared on a class. Here you will see what code can no longer do once a class declares __slots__.
The instance loses its __dict__
A regular instance stores its attributes in a per-instance dictionary. A class with __slots__ does not create that dictionary. The listed names are the only attributes an instance can hold.
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__"))This prints 1 2 and then False. The values still live on the instance, but not in a dictionary you can reach.
New attribute names are rejected
Assigning a name that is not in __slots__ fails, because there is no dictionary to put it in.
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
try:
p.z = 3
except AttributeError as exc:
print("AttributeError:", exc)The error is an AttributeError. The exact message text differs between Python versions, so do not match on it in tests.
A regular class accepts the same assignment silently. That is why a typo such as p.xx = 5 creates a new attribute on a plain class and raises an error on a slotted one.
Reading an unset slot
A declared slot starts out empty. Reading it before you assign it raises AttributeError, just as a missing name would. Deleting a slot value puts it back in that state.
class Point:
__slots__ = ("x", "y")
p = Point()
try:
print(p.x)
except AttributeError:
print("x is declared but not set")
p.x = 10
print(p.x)
del p.x
print(hasattr(p, "x"))The output is x is declared but not set, then 10, then False. hasattr is a safe way to check whether a slot currently holds a value.
Code that relied on __dict__ breaks
Several common idioms assume every instance has a __dict__. They fail on slotted instances.
| Idiom | Result on a slotted instance |
|---|---|
| `p.__dict__` | `AttributeError` |
| `vars(p)` | `TypeError` |
| `p.__dict__.update(data)` | `AttributeError` |
| `functools.cached_property` | `TypeError` when the value is first computed |
You can still read and write slots dynamically by name with getattr and setattr. To list the declared names, read __slots__ from the class.
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
def to_dict(obj):
return {name: getattr(obj, name) for name in type(obj).__slots__}
p = Point(1, 2)
setattr(p, "x", 99)
print(to_dict(p))
try:
vars(p)
except TypeError as exc:
print("TypeError:", exc)to_dict prints {'x': 99, 'y': 2}. It reads __slots__ from the type, not the instance. This helper only handles a class that declares __slots__ directly. A subclass would need to walk its base classes as well, which a later chapter on inheritance covers.
Common mistakes
- Forgetting to list a name that
__init__assigns. The first instance you create fails withAttributeError. - Adding attributes from outside the class, for example in a test or a helper. This worked on the plain version and now fails.
- Using libraries or code that call
vars()orobj.__dict__on your objects. Check for this before converting an existing class.
Exercise
A class declares __slots__ = ("name",). Its __init__ runs self.name = name and then self.age = age. What happens when you create an instance, and what are two ways to fix it?
Show answer
self.age = age raises AttributeError, because age is not a slot and the instance has no __dict__. Fix it by adding "age" to __slots__, or by removing the assignment if the attribute is not needed. Opting back into a __dict__ by listing "__dict__" in __slots__ also works, but it gives up most of the benefit of slots.
Exercise
What does hasattr(p, "x") return for a slotted instance whose slot x was declared but never assigned, and why?
Show answer
It returns False. Reading an unset slot raises AttributeError, and hasattr reports False when the read raises AttributeError.