Understand Slots and Instance Dictionaries
Core idea
slots declares named instance storage through descriptors created on the class. In a simple slotted class without an inherited instance dictionary or an explicit dict slot, arbitrary new instance attributes are unavailable. Slots can reduce storage overhead, but do not make instances immutable. Subclasses without slots can regain a dictionary; inherited dictionaries cannot be removed merely by declaring slots.
class Point: __slots__ = ('x', 'y') def __init__(self, x, y): self.x, self.y = x, yp = Point(2, 3)p.x = 8print(p.x, hasattr(p, '__dict__'))try: p.label = 'origin'except AttributeError: print('unknown field')The declared field remains writable; the undeclared attribute cannot be stored.
Compare subclass storage
class Base: __slots__ = ('code',)class Open(Base): passclass Closed(Base): __slots__ = ()a, b = Open(), Closed()a.code, b.code = 'A', 'B'a.note = 'extra'print(vars(a), b.code)print(hasattr(b, '__dict__'))Open gains a dictionary, but code still uses the inherited slot. Closed adds no dictionary.
Common mistake
Do not use a class attribute as the default for a slot of the same name; the names conflict. Initialize the slot in init. Weak references may require weakref in slots when not inherited.
Practice
Create a subclass with slots = ("note",) and check which fields it accepts and whether vars(instance) is available.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Slots and instance dictionaries
Check your understanding of slots and instance dictionaries.
What is printed?
class C: __slots__=('x',)c=C(); c.x=1; c.x=2print(c.x)What is printed?
class A: passclass B(A): __slots__=('x',)b=B(); b.y=5print(vars(b))What does an empty __slots__ in a subclass of a slotted base do?
Where are slot defaults normally initialized?