Sub topic 1
Python `__slots__` and Attribute Storage: How Instances Hold Their Data
Prerequisites
This chapter assumes you can define classes, write __init__ methods, distinguish instance attributes from class attributes, and use dictionaries.
Where attributes live by default: the instance `__dict__`
A normal Python instance usually stores its attributes in an instance dictionary named __dict__. Each object gets a dictionary that maps attribute names to values.
class PlainPoint:
def __init__(self, x, y):
self.x = x
self.y = y
point = PlainPoint(1, 2)
print(point.__dict__)
point.z = 3
print(point.__dict__)The first output is {'x': 1, 'y': 2}. Python then accepts z because the instance dictionary can receive new keys. This flexibility is useful when objects need optional or changing attributes.
The class also has a __dict__, but that dictionary stores class-level data such as methods and class attributes. point.__dict__ stores data belonging only to point.
Declaring `__slots__` to fix an instance's attributes
__slots__ is a class declaration that lists the instance attributes the class expects. Python creates storage for those names without giving each instance a normal __dict__.
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
point = Point(1, 2)
print(point.x, point.y)
print(hasattr(point, "__dict__"))This prints 1 2 and then False. The slot names must be strings. They can be written as a tuple, list, or other iterable, although a tuple is conventional.
What changes: no `__dict__` and no new attributes
A slotted instance accepts assignments only for its declared slots. Assigning another name raises AttributeError.
class Point:
__slots__ = ("x", "y")
point = Point()
point.x = 1
try:
point.z = 3
except AttributeError as error:
print(type(error).__name__)The restriction can catch spelling mistakes and reduce per-instance overhead when many objects have the same fixed shape. It also means code that expects obj.__dict__, dynamically adds attributes, or serializes objects by reading that dictionary needs another design.
Exercise
What happens when p.z = 3 runs for a class with __slots__ = ("x", "y")?
Show answer
It raises AttributeError because z is not a declared slot and the instance has no _dict_ for storing it.