Lesson · Advanced Object Model
Slots
75 min readSlots
`__slots__` changes instance attribute storage and can reduce per-instance memory. It is a layout/performance tool with inheritance and weak-reference implications, not an access-control feature.
Learning goals
- Declare
__slots__on a class and name the two things it changes: attribute storage and which names are allowed. - Explain the
AttributeErrorfrom an undeclared attribute using the missing dictionary and the fixed slot list. - Predict whether a subclass keeps the memory saving or reintroduces a
__dict__. - Compare a slotted class with a plain one using size evidence rather than intuition.
- Decide when the fixed attribute set is a benefit and when the lost flexibility costs more.
Mental model
The right-hand layout is smaller per instance but can only hold the names listed in __slots__; the left-hand layout accepts new attributes forever, at the cost of a dictionary per instance. Attribute reads and writes follow the descriptor on the right, which is why a name outside the list has nowhere to go.
Mental model
read it top to bottom
plain class: instance → __dict__ (flexible, larger) slotted class: instance → class slot descriptors (fixed, smaller)
Core idea
__slots__ swaps per-instance storage: the class declares a fixed set of attribute names, and reads and writes go through slot descriptors instead of a per-instance dictionary. The win is less memory per object and early detection of misspelled attributes; the price is lost flexibility, so slots are an optimization with a contract, not a default.
__slots__
__slots__ declares a fixed set of slot descriptors instead of the normal per-instance __dict__ for those attributes. It can reduce memory for many instances but changes extensibility and inheritance behavior.
Attribute storage
Normal instances often store attributes in __dict__; slot declarations replace selected storage with descriptors managed by the class. The representation affects memory and dynamic extensibility.
Memory tradeoffs
A slot-only object avoids the per-instance dictionary, which saves memory when you hold many objects and can speed up attribute access. Against that saving stand lost dynamic attributes, extra care with inheritance, and interactions with tools that expect __dict__, so measure the concrete workload before deciding.
Inheritance considerations
A subclass that omits __slots__ gets a __dict__ again, silently losing the memory saving for every instance below it, so derived classes usually declare __slots__ = () or their own slot list. Multiple inheritance has layout limits (only one base may contribute nonempty slots), and weak references need __weakref__ declared, so slotted hierarchies need planning.
Not primarily access control
Slots change storage, not visibility: point.x is still readable and writable from anywhere, and nothing stops code from assigning the declared attributes. If the goal is to hide data or validate access, the tools are properties, naming conventions, or a frozen dataclass, not __slots__.
Walkthrough
__slots__ = ("x", "y")tells the class to reserve storage for exactly these two names; it is a class-level declaration, not an attribute holding values.self.x = xin__init__writes through the slot descriptor, andpoint.xreads it back from that slot rather than from apoint.__dict__, which this class no longer gives its instances.point.z = 3raisesAttributeErrorbecause there is no slot namedzand no instance dictionary to absorb a new name; the except block prints the error type,AttributeError.- Predict before running: which of the three attribute operations succeed, and what
hasattr(point, "__dict__")reports for this class.
Experiments to try
- Check
hasattr(point, "__dict__")for the slotted class and for a small plain class with the same two attributes; only the plain instance carries a dictionary. - Remove
__slots__and rerun;point.z = 3now succeeds and the except block never prints. - Add
class Point3D(Point): passand testhasattr(Point3D(1, 2), "__dict__"); the subclass reintroduces a dictionary unless it declares__slots__ = (). - Measure
sys.getsizeoffor a slotted instance and a plain instance carrying the same two attributes, remembering that the plain instance's__dict__is a separate object to measure as well.
Common mistakes
- Expecting slots to enforce privacy: attributes declared in
__slots__are as public as any others, and only undeclared names are refused. - Forgetting
__slots__on a subclass: its instances receive a__dict__again, and the memory saving disappears for every derived type. - Reusing a name from
__slots__as a class variable: Python raisesValueErrorat class definition because one descriptor cannot serve two storage roles. - Adding slots before measuring: the saving is small for few or short-lived objects, while the loss of dynamic attributes can force restructuring, so measure first.
Practice: Easy
- Run the worked example and confirm the three printed lines; then remove the try/except and let the
AttributeErrorsurface with its full traceback. - Add
"z"to the slot tuple and assignpoint.z = 3; the write now succeeds andpoint.zreads back from its own slot. - Compare
hasattr(instance, "__dict__")forPointand for a small plain class with the same two attributes, and write one sentence per result.
Practice: Medium
- Add
class Point3D(Point): passand check whether its instances regain a__dict__; then change it toclass Point3D(Point): __slots__ = ()and compare the two layouts. - Force a slot and a class variable to share a name (
x = 0next to__slots__ = ("x", "y")) and read theValueError; move the default into__init__to fix it. - Create twenty thousand instances of each layout and compare total memory using
sys.getsizeofplus the size of each instance's__dict__; report the per-instance difference in bytes.
Practice: Hard
- Build a record type with slots, a property that validates a value, and an
__init__that assigns through the slots; write assertions for valid and invalid input. - Set up a failure lab with three broken classes: an undeclared attribute on a slotted class, a subclass that silently reintroduces
__dict__, and a slot name that collides with a class variable; explain each from the storage model. - Plan a two-level slotted hierarchy where the subclass adds one slot: decide the contents of each
__slots__, then check the layout withhasattr(instance, "__dict__")and a size comparison against the plain version.
Lesson checklist
- I can declare
__slots__and name the two operations it changes: storage and the set of allowed attribute names. - I can explain the
AttributeErrorfrom an undeclared attribute using slots and the missing__dict__. - I can predict whether a subclass keeps the saving or reintroduces a dictionary.
- I can measure a slotted layout against a plain one and state when the tradeoff is worth it.
Remember
`__slots__` replaces the per-instance dictionary with fixed slot descriptors, cutting memory per object and rejecting undeclared attributes, while removing dynamic attribute assignment and adding hierarchy constraints. Treat it as a measured optimization: adopt it when instances are many, the attribute set is truly fixed, and every subclass carries its own slot declaration.
Interview angles
What is the main purpose of **__slots__**?+
__slots__ declares a fixed set of slot descriptors instead of the normal per-instance __dict__ for those attributes. It can reduce memory for many instances but changes extensibility and inheritance behavior.
What should you pay attention to when using **Attribute storage**?+
Normal instances often store attributes in __dict__; slot declarations replace selected storage with descriptors managed by the class. The representation affects memory and dynamic extensibility.
How does **Memory tradeoffs** fit into this lesson?+
A slot-only object avoids the per-instance dictionary, which saves memory when you hold many objects and can speed up attribute access. Against that saving stand lost dynamic attributes, extra care with inheritance, and interactions with tools that expect __dict__, so measure the concrete workload before deciding.
Why does a subclass without its own `__slots__` undo the memory saving?+
Instances of that subclass receive a __dict__ again, because the subclass layout adds one when it does not declare __slots__. Every instance below that class then pays for the dictionary the base avoided.