Sub topic 7
Slots and inheritance: when a subclass regains `__dict__`
This chapter assumes you know how __slots__ removes the instance __dict__ and how basic subclassing works. It covers what happens to that saving when you inherit from a slotted class.
Slots are a per-class decision
__slots__ does not pass down as a rule that applies to the whole hierarchy. Each class decides for itself whether its instances get a __dict__. A class gets one unless every class in its chain of bases declares __slots__.
class Base:
__slots__ = ("a",)
class LeakyChild(Base):
pass
class TightChild(Base):
__slots__ = ("b",)
print(hasattr(LeakyChild(), "__dict__"))
print(hasattr(TightChild(), "__dict__"))This prints True, then False.
LeakyChild has no __slots__ line, so Python adds the usual __dict__ to its instances. The slot a from Base still works. But LeakyChild instances now accept any attribute again and carry a dictionary each, so the memory saving is gone.
TightChild declares only the new names it adds, ("b",). Instances of TightChild have both a and b, and no __dict__.
The __slots__ line for a subclass lists only the new attributes. Don't repeat names the parent already has.
Slotted subclass of a regular class
The same rule applies in the other direction. If the parent is an ordinary class, its instances already have a __dict__, and a subclass cannot remove it.
class Plain:
pass
class Child(Plain):
__slots__ = ("a",)
c = Child()
c.a = 1
c.extra = 2
print(hasattr(c, "__dict__"))
print(c.__dict__)This prints True and then {'extra': 2}. The slot a is stored in its slot. The extra attribute goes into the inherited __dict__. The __slots__ line on Child adds nothing useful here.
Repeating a parent's slot names
Redeclaring a name the parent already has does not raise an error:
class Base:
__slots__ = ("a",)
class Child(Base):
__slots__ = ("a", "b")Python then allocates a second a slot in Child. The parent's a becomes unreachable through normal access, and each instance wastes a pointer. Declare only the new names.
Multiple inheritance and layout conflicts
Slots are stored at fixed positions in the instance's memory layout. Two parents that each add slots want incompatible layouts, so Python refuses to combine them:
class A:
__slots__ = ("a",)
class B:
__slots__ = ("b",)
try:
class C(A, B):
pass
except TypeError as exc:
print("TypeError:", exc)The error message is multiple bases have instance lay-out conflict. Having __slots__ on the child doesn't help. The conflict is between the parents.
The fix is to keep at most one parent with non-empty slots. Mixin-style classes, which only provide methods, should declare an empty __slots__:
class A:
__slots__ = ("a",)
class Mixin:
__slots__ = ()
def describe(self):
return f"a={self.a}"
class C(A, Mixin):
__slots__ = ("c",)
obj = C()
obj.a = 1
obj.c = 2
print(obj.describe())
print(hasattr(obj, "__dict__"))This prints a=1 and then False. An empty __slots__ = () adds no storage and no __dict__, so the mixin doesn't interfere with the layout or undo the saving.
Checking a hierarchy
If you suspect a __dict__ has crept back in, check one instance. You can also look at which classes in the MRO (method resolution order) lack their own __slots__:
class Base:
__slots__ = ("a",)
class LeakyChild(Base):
pass
for cls in LeakyChild.__mro__:
print(cls.__name__, "__slots__" in cls.__dict__)Every class in the output must show True, except object, which Python treats as slot-free. Here LeakyChild prints False, which identifies it as the class that brings the __dict__ back.
Summary of the rules
| Situation | Instances have `__dict__`? |
|---|---|
| Slotted child of slotted parent, child declares `__slots__` | No |
| Child of slotted parent, child omits `__slots__` | Yes |
| Slotted child of a regular parent | Yes |
| Two parents with non-empty slots | Not allowed (`TypeError`) |
| Mixin with `__slots__ = ()` | No effect on the layout |
Exercise
A team writes class Shape: __slots__ = ("name",) and class Circle(Shape): def __init__(self, name, r): self.name = name; self.r = r. Does Circle(...) work, and does it save memory compared with a regular class? Why?
Show answer
It works. name is stored in the inherited slot, and r is stored in a __dict__ that Circle gets because it doesn't declare __slots__. It saves little, since each instance still carries a dictionary. Adding __slots__ = ("r",) to Circle removes the __dict__.
Exercise
You want a Printable mixin with a show() method to be combined with a slotted Record class that has slots ("id",). How do you write the mixin so class Item(Record, Printable) has no __dict__ and no layout conflict?
Show answer
Give the mixin an empty slots declaration: class Printable: __slots__ = (). Then Item should declare its own __slots__ for any new attributes, for example __slots__ = ("price",).