Sub topic 2
How Slots Work: Member Descriptors on the Class
Assume you know Python classes, __init__, instance and class attributes, inheritance, and basic dictionaries. This chapter focuses on how __slots__ changes attribute storage.
Member descriptors on the class
When Python sees __slots__, it creates a member descriptor, an object on the class that knows how to read and write one slot. The instance stores the value in the slot rather than in instance.__dict__.
class Point:
__slots__ = ("x", "y")
print(type(Point.__dict__["x"]).__name__)
point = Point()
try:
point.x
except AttributeError:
print("x has not been assigned")
point.x = 10
print(point.x)The descriptor exists on Point, but its value belongs to each Point instance. An unassigned slot has no value, so reading it raises AttributeError.
Measuring memory savings honestly
A normal instance usually has both the object itself and a separate dictionary. A slotted instance can avoid that dictionary. This simple comparison is useful, but the numbers are implementation-dependent.
import sys
class Plain:
def __init__(self, x, y):
self.x = x
self.y = y
class Slotted:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
plain = Plain(1, 2)
slotted = Slotted(1, 2)
print(sys.getsizeof(plain) + sys.getsizeof(plain.__dict__))
print(sys.getsizeof(slotted))sys.getsizeof does not measure every object referenced by an instance. Treat this as a rough comparison, not a universal savings guarantee. Measure representative objects in the Python version and implementation you deploy.
> callout note > Slots usually matter when you create many small, long-lived objects. For a small number of objects, the reduced flexibility may matter more than the saved memory.
Defaults and class-variable conflicts
A slot name cannot also be assigned as a class variable. Both declarations would need to control the same attribute, so class creation raises ValueError.
class Invalid:
__slots__ = ("x",)
x = 0Set the default in __init__ instead:
class Point:
__slots__ = ("x",)
def __init__(self, x=0):
self.x = xSlots and inheritance
A subclass that omits __slots__ gets a __dict__, even when its parent is slotted. To remain dict-free, every class in the hierarchy must declare slots.
class Base:
__slots__ = ("a",)
class LeakyChild(Base):
pass
class TightChild(Base):
__slots__ = ("b",)
print(hasattr(LeakyChild(), "__dict__"))
print(hasattr(TightChild(), "__dict__"))Exercise
Why does LeakyChild have a __dict__ while TightChild does not?
Show answer
LeakyChild does not declare __slots__, so Python adds an instance dictionary. TightChild declares its own slots and remains dict-free.