Sub topic 3
Weak References, `__dict__`, and Practical Uses of `__slots__`
Assume you know classes, inheritance, instance attributes, and dictionaries. Earlier, you saw that __slots__ removes an instance’s normal __dict__ and limits its attributes. This chapter covers exceptions and practical decisions.
Weak references and opting back into `__dict__`
A weak reference points to an object without keeping that object alive. Caches and observer systems commonly use weak references.
A slotted class does not support weak references unless __weakref__ appears in __slots__. You can also restore dynamic attributes by adding __dict__:
import weakref
class Node:
__slots__ = ("value", "__weakref__", "__dict__")
def __init__(self, value):
self.value = value
node = Node(5)
node.label = "root"
reference = weakref.ref(node)
print(reference() is node)
print(node.__dict__)Here, value uses a slot, while label uses the restored dictionary. Add these special slots only when the required behavior is worth the extra storage.
Slotted dataclasses
On Python 3.10 and later, @dataclass(slots=True) generates slots for the declared fields. It preserves useful dataclass features such as generated initialization and defaults.
from dataclasses import dataclass
@dataclass(slots=True)
class Point:
x: int
y: int = 0
point = Point(3)
print(point)
print(hasattr(point, "__dict__"))The output shows a Point with y set to its default, followed by False.
Pickling and copying
The pickle module can serialize many simple slotted objects, and copy.copy() can make shallow copies. Custom state, inheritance, or resources such as open files may require __getstate__ and __setstate__.
import copy
import pickle
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
original = Point(1, 2)
restored = pickle.loads(pickle.dumps(original))
duplicate = copy.copy(original)
print(restored.x, restored.y)
print(duplicate.x, duplicate.y)Test serialization and copying when they are part of your class’s contract.
When slots are worth it
Use slots when you create many small, stable objects and want lower per-instance memory use or protection against accidental attribute names. Do not use them only because they look faster. They restrict debugging, extensions, and some library integrations. A regular __dict__ is often the simpler choice when fields change frequently.
Exercise
Which slots must a class add to support both weak references and arbitrary new attributes?
Show answer
Add both "_weakref" and "dict" to slots_.