Sub topic 3
What changes: no __dict__ and no new attributes
This chapter covers what you can no longer do to an instance once its class declares __slots__. It assumes you can write classes with __init__, you know the difference between instance and class attributes, and you know that a regular instance stores its attributes in a dictionary. The previous chapter showed how to declare __slots__. Here the focus is the visible consequences, the errors they produce, and the code that stops working.
The instance has no `__dict__`
A regular instance owns a dictionary, reachable as obj.__dict__. Every attribute assignment adds a key to it. A class with __slots__ does not create that dictionary, so the object has nowhere to put an attribute whose name you did not declare.
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(hasattr(p, "__dict__"))
try:
p.__dict__
except AttributeError as exc:
print("AttributeError:", exc)
try:
vars(p)
except TypeError as exc:
print("TypeError:", exc)The first line prints False. Reading p.__dict__ raises AttributeError. Calling vars(p) raises TypeError, because vars() works only on objects that have a __dict__. The exact message text differs between Python versions, so don't match on it in code.
The class still has a __dict__. Point.__dict__ is the usual read-only view of the class namespace, holding methods and the slot descriptors. Only the instances lose their dictionary.
New attribute names are rejected
Assigning to a name that is not a slot fails, whether you use dot syntax or setattr.
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("dot assignment:", exc)
try:
setattr(p, "z", 3)
except AttributeError as exc:
print("setattr:", exc)
p.x = 10
setattr(p, "y", 20)
print(p.x, p.y)Names listed in __slots__ can be assigned any number of times with either syntax. Names that are not listed fail.
A side effect: typo protection
With a regular class, a misspelled attribute name silently creates a new attribute:
class PlainCounter:
def __init__(self):
self.count = 0
c = PlainCounter()
c.cuont = c.count + 1 # typo: creates a second attribute, count stays 0
print(c.count, c.__dict__)A slotted class turns the same mistake into an immediate error:
class SlottedCounter:
__slots__ = ("count",)
def __init__(self):
self.count = 0
c = SlottedCounter()
try:
c.cuont = c.count + 1
except AttributeError as exc:
print("caught typo:", exc)Some teams value this for that reason alone. Treat it as a side benefit, though. __slots__ is not a validation framework. It restricts names, not values or types, and a type checker or a properly designed class does that job better.
What happens on assignment
The diagram shows how CPython decides what to do with obj.name = value on a slotted class with no __dict__.
The last branch is the normal case for regular classes. A slotted class without __dict__ never takes it. The next chapter looks at the descriptor in the first branch.
Slots can be empty, and deleting is allowed
Declaring a slot does not give it a value. Reading a slot that was never assigned raises AttributeError, exactly like a missing instance attribute. You can also delete a slot, which returns it to the unset state.
class Point:
__slots__ = ("x", "y")
p = Point()
print(hasattr(p, "x"))
p.x = 1
print(hasattr(p, "x"))
del p.x
print(hasattr(p, "x"))
print(getattr(p, "x", "unset"))
try:
del p.y
except AttributeError:
print("cannot delete a slot that was never set")This prints False, True, False, unset, and then the final message. Two practical points follow:
hasattrandgetattr(obj, name, default)are the correct way to test whether a slot currently holds a value.- Set every slot in
__init__unless you deliberately want some of them optional. A slot that was never assigned causes errors far from where the object was created.
Class attributes still work, but are read-only through instances
You can still add attributes to the class itself. Instances can read them, but they cannot assign to a name that exists only as a plain class attribute.
class Point:
__slots__ = ("x", "y")
Point.label = "point"
p = Point()
print(p.label)
try:
p.label = "other"
except AttributeError as exc:
print("AttributeError:", exc)Without a __dict__, an assignment such as p.label = "other" cannot create an instance-level override that shadows the class attribute. In a regular class that is exactly what it does. The slotted instance has no place to keep the override, so CPython rejects the assignment. The next chapters build on this when they cover defaults.
Code that depends on `__dict__` breaks
Anything that assumes obj.__dict__ exists fails on a slotted instance. Common cases:
| Code | Result on a slotted instance without `__dict__` |
|---|---|
| `obj.__dict__` | `AttributeError` |
| `vars(obj)` | `TypeError` |
| `obj.__dict__.update(data)` | `AttributeError` |
| `setattr(obj, name, value)` for a declared slot | Works |
| `setattr(obj, name, value)` for any other name | `AttributeError` |
| `functools.cached_property` | `TypeError` on first access |
| `dir(obj)` | Works, and lists the slot names |
The pattern self.__dict__.update(kwargs) is common in small initializers. The slotted replacement is a loop over names:
class Settings:
__slots__ = ("host", "port")
def __init__(self, **kwargs):
for name, value in kwargs.items():
setattr(self, name, value)
s = Settings(host="localhost", port=8080)
print(s.host, s.port)
try:
Settings(host="localhost", debug=True)
except AttributeError as exc:
print("unknown option rejected:", exc)Here the restriction does useful work, because an unknown keyword argument becomes an error instead of a silent new attribute.
`cached_property` needs a dictionary
functools.cached_property stores its result in the instance __dict__. On a slotted class without one, the first access fails:
from functools import cached_property
class Circle:
__slots__ = ("radius",)
def __init__(self, radius):
self.radius = radius
@cached_property
def area(self):
return 3.14159 * self.radius ** 2
try:
Circle(2).area
except TypeError as exc:
print("TypeError:", exc)You have three options. Compute the value each time with a plain property. Store the cached value in a slot you manage yourself. Or give up some of the savings and add "__dict__" to the slots, a technique a later chapter covers.
Inspecting a slotted object
Without __dict__, you read state from the slot names instead. The class keeps them in __slots__. With inheritance, the names are spread across several classes, so a general helper walks the method resolution order (the list of classes Python searches, in order):
def slot_state(obj):
names = []
for klass in type(obj).__mro__:
slots = klass.__dict__.get("__slots__", ())
if isinstance(slots, str):
slots = (slots,)
names.extend(n for n in slots if n not in ("__dict__", "__weakref__"))
return {name: getattr(obj, name) for name in names if hasattr(obj, name)}
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
class Point3D(Point):
__slots__ = ("z",)
def __init__(self, x, y, z):
super().__init__(x, y)
self.z = z
print(slot_state(Point3D(1, 2, 3)))The output is a dictionary with keys z, x, and y, in that order. The hasattr check skips slots that were never set. This sketch ignores slots whose names Python rewrites to avoid clashes (names starting with two underscores), so don't treat it as complete. Libraries such as dataclasses and pickle have their own more careful handling.
A string is also a legal value for __slots__. __slots__ = "x" declares one slot named x. A common mistake is writing __slots__ = ("x"), which is just the string "x" in parentheses. It happens to work for one name, but it makes a bug if you later add a second name without a comma. Write ("x",) with the trailing comma.
Summary of the changes
- Instances have no
__dict__, sovars()andobj.__dict__fail. - Only declared names can be assigned. Typos become errors.
- A slot can be unset, and reading it then raises
AttributeError. - Plain class attributes can be read through an instance, but not assigned through it.
- Code that assumes
__dict__, such ascached_propertyor__dict__.update, needs to be changed.
Exercise
A class is declared as class Temp: __slots__ = ("celsius",). A colleague writes t = Temp(); t.celsius = 20; t.fahrenheit = 68. Which line raises an error, which exception type is it, and what are two different ways to make the third line work without removing __slots__?
Show answer
The line t.fahrenheit = 68 raises AttributeError, because fahrenheit is not a slot and the instance has no __dict__ to hold it. Two fixes: add "fahrenheit" to __slots__ so it becomes a declared slot, or add "__dict__" to __slots__ so the instance gets a dictionary for undeclared names, which gives up some of the memory savings. A third option is to define fahrenheit as a property on the class that computes it from celsius, so no new storage is needed.
Exercise
For class Box: __slots__ = ("size",), what do hasattr(Box(), "size") and hasattr(Box, "__dict__") return, and why are the two answers different?
Show answer
Both calls give different results: hasattr(Box(), "size") is False because the slot was declared but never assigned, so reading it raises AttributeError. hasattr(Box, "__dict__") is True because the class itself always has a namespace dictionary (a mapping proxy). Only instances of the class lose their __dict__.