Sub topic 7
Slots and inheritance: when a subclass regains `__dict__`
This chapter assumes you can define classes with __init__, and that you know how a plain instance stores attributes in its __dict__. It also assumes you know how __slots__ fixes an instance's attributes and removes that dict, and that you are comfortable with single and multiple inheritance. The question here is what happens to the dict-free layout once classes inherit from each other.
The rule: `__slots__` is a per-class decision
Declaring __slots__ in a class only affects instances of that class if no other class in the hierarchy already supplies a __dict__. Each class in the inheritance chain makes its own choice:
- A class that defines
__slots__adds those slots and adds no__dict__. - A class that does not define
__slots__adds a__dict__(and a__weakref__slot) to its instances. - An instance has a
__dict__if any class in its MRO (method resolution order) provides one.
Here are two subclasses of one slotted base:
class Base:
__slots__ = ("a",)
class LeakyChild(Base):
pass
class TightChild(Base):
__slots__ = ("b",)
print(hasattr(Base(), "__dict__"))
print(hasattr(LeakyChild(), "__dict__"))
print(hasattr(TightChild(), "__dict__"))This prints False, True, False. LeakyChild has no __slots__ line, so Python treats it as an ordinary class and gives its instances a dict. The base's slot a still works, and it does not move into the dict.
class Base:
__slots__ = ("a",)
class LeakyChild(Base):
pass
c = LeakyChild()
c.a = 1
c.extra = 2
print(c.__dict__)The output is {'extra': 2}. The name a is stored in its slot, and only names that are not slots go into the dict. The memory saving is partly lost, because every instance now carries a dict (CPython creates it lazily on some versions, but the capacity is there).
Deciding whether a hierarchy is dict-free
The decision follows this flow for each class you write.
You can also check the class objects directly. The __dict__ of an instance is itself served by a descriptor stored on the class that introduces it:
class Base:
__slots__ = ("a",)
class LeakyChild(Base):
pass
class TightChild(Base):
__slots__ = ("b",)
for cls in (Base, LeakyChild, TightChild):
print(cls.__name__, "__dict__" in vars(cls))The output is Base False, LeakyChild True, TightChild False. A class that introduces the dict has a __dict__ entry in its own namespace. A class that inherits the dict does not, so test the instance with hasattr(obj, "__dict__") when the hierarchy is deep.
Common cases
| Definition | Instances have `__dict__`? | Reason |
|---|---|---|
| `class A: __slots__ = ("a",)` | No | Slots only, `object` has no dict |
| `class B(A): pass` | Yes | `B` has no `__slots__`, so it adds a dict |
| `class C(A): __slots__ = ("c",)` | No | Every class in the chain declares slots |
| `class D(A): __slots__ = ()` | No | Empty slots add nothing and keep the layout dict-free |
| `class E: pass` then `class F(E): __slots__ = ("f",)` | Yes | `E` already supplies a dict |
| `class G(A): __slots__ = ("g", "__dict__")` | Yes | The dict is requested explicitly |
The last row shows that you can opt back into a dict on purpose by listing "__dict__" in __slots__. The __weakref__ entry works the same way, and a later chapter covers both.
The fifth row is the one that surprises people. One undeclared class near the root of a hierarchy defeats slots for every descendant, however carefully the leaf classes declare theirs.
How slots accumulate across levels
A subclass lists only its new names. The instance layout contains the base's slots plus the subclass's slots, and __slots__ in each class shows just that class's share. To see the full set, walk the MRO:
def all_slots(cls):
names = []
for klass in cls.__mro__:
slots = klass.__dict__.get("__slots__", ())
if isinstance(slots, str):
slots = (slots,)
names.extend(slots)
return names
class Base:
__slots__ = ("a",)
class TightChild(Base):
__slots__ = ("b",)
print(all_slots(TightChild))
t = TightChild()
t.a = 1
t.b = 2
print(t.a, t.b)The helper prints ['b', 'a'] because it walks from the subclass up. Both names are assignable on the instance. A bare string such as __slots__ = "x" means a single slot named x, which is why the helper handles that case.
Do not repeat a base class's slot
Python does not stop you from declaring a slot that a base class already has:
class Base:
__slots__ = ("a",)
class Child(Base):
__slots__ = ("a", "b")
c = Child()
c.a = 1
print(c.a)
try:
print(Base.a.__get__(c, Child))
except AttributeError:
print("the base class slot a is empty")The subclass creates a second slot called a that hides the first. c.a reads the new one, and the base's slot occupies memory that nothing can reach by normal attribute access. The Python data model documentation says the meaning of such a program is undefined. Leave the name out of the subclass and rely on inheritance.
Empty `__slots__` for dict-free subclasses and mixins
A subclass that adds no attributes still needs a __slots__ line to avoid the dict. Use an empty tuple:
class Base:
__slots__ = ("a",)
class Specialised(Base):
__slots__ = ()
def describe(self):
return f"a={self.a}"
s = Specialised()
s.a = 5
print(s.describe())
print(hasattr(s, "__dict__"))This prints a=5 and False. Adding behavior (methods, properties, class constants) never requires slots. Only new per-instance data does.
The same technique matters for mixins and abstract base classes. A mixin with no instance data should declare __slots__ = (), so that classes using it can stay dict-free. The classes in collections.abc, such as Sequence and Mapping, do this, so subclassing them does not add a dict unless your own class forgets __slots__.
Multiple inheritance and layout conflicts
Slots are stored at fixed offsets inside the instance. Two bases that each add non-empty slots both claim the space after the object header, and CPython cannot merge them:
class A:
__slots__ = ("a",)
class B:
__slots__ = ("b",)
try:
class C(A, B):
pass
except TypeError as exc:
print("TypeError:", exc)The error is multiple bases have instance lay-out conflict. The fix is to make sure at most one base in the list brings in non-empty slots, and that the others (typically mixins) use __slots__ = ():
class Mixin:
__slots__ = ()
def shout(self):
return str(self.a).upper()
class A:
__slots__ = ("a",)
class C(Mixin, A):
__slots__ = ("c",)
obj = C()
obj.a = "hi"
obj.c = 1
print(obj.shout())
print(hasattr(obj, "__dict__"))This prints HI and False. Another way to get a conflict is mixing a slotted class with a non-slotted one that has its own instance layout, such as a class written in C. Layout conflicts appear at class creation, so they are easy to catch in tests.
Built-in bases
Some built-in types constrain what slots can do.
- Variable-size types such as
int,bytesandtuplerefuse non-empty slots in subclasses.class N(int): __slots__ = ("x",)raisesTypeError, whileclass N(int): __slots__ = ()is allowed. For tuple-like objects with names, usetyping.NamedTupleorcollections.namedtupleinstead. - Exception classes always have a dict, because
BaseExceptionprovides one. Adding__slots__to an exception subclass changes nothing about the dict, though the slots themselves still work. - Subclassing
dictorlistwith__slots__works, but the dict-free layout only affects the subclass's extra attributes.
Worked example: a small hierarchy that stays dict-free
class Shape:
__slots__ = ("name",)
def __init__(self, name):
self.name = name
class Circle(Shape):
__slots__ = ("radius",)
def __init__(self, radius):
super().__init__("circle")
self.radius = radius
class UnitCircle(Circle):
__slots__ = ()
def __init__(self):
super().__init__(1)
for obj in (Shape("blob"), Circle(2), UnitCircle()):
print(type(obj).__name__, hasattr(obj, "__dict__"))
u = UnitCircle()
try:
u.colour = "red"
except AttributeError:
print("cannot add colour")All three classes print False, and the final assignment fails. Each level declares exactly the data it introduces and nothing it inherits, and the leaf that adds no data uses ().
If someone later adds class Tagged(UnitCircle): pass, instances of Tagged get a dict again. A short test that asserts not hasattr(instance, "__dict__") for each concrete class catches this regression.
Summary of practical rules
- Put
__slots__in every class of the hierarchy, starting at the root. - List only the names a class adds. Never repeat a base class's slot.
- Use
__slots__ = ()for subclasses and mixins that add behavior but no data. - Allow at most one base with non-empty slots when using multiple inheritance.
- Verify with
hasattr(instance, "__dict__")instead of trusting the class text.
Exercise
Given the classes below, which of A(), B() and C() have a __dict__, and what happens if you then run C().c = 1; C().z = 2 on separate instances? Explain why.
class A:
_slots = ("a",)
class B(A):
pass
class C(B):
slots_ = ("c",)
Show answer
A() has no __dict__. B() and C() both have one. B declares no __slots__, so its instances get a dict, and C inherits that dict even though it declares slots of its own. C().c = 1 stores 1 in the slot named c. C().z = 2 also succeeds, because z is not a slot and goes into the inherited __dict__. To make C dict-free, B would need __slots__ = ().
Exercise
Why does class C(A, B): pass raise a TypeError when A has __slots__ = ("a",) and B has __slots__ = ("b",), and how do you fix it while keeping both attributes available?
Show answer
Both bases add non-empty slots, and each claims the same position in the instance layout, so CPython reports an instance lay-out conflict. Make only one class bring its own slots. For example, give B an empty __slots__ = () and move the b attribute into C's own __slots__ = ("b",). Alternatively, define C with a single slotted base and declare the other attribute in C. Mixins that hold no data should always use __slots__ = ().