Sub topic 11
Inheritance and Field Ordering
Dataclass inheritance works by merging field definitions from several classes into one ordered list. That list sets the parameter order of the generated __init__, the order of repr output, and the order used for comparison. This chapter explains how the list is built and which errors come from it. It also covers how to design hierarchies that avoid those errors.
I assume you know @dataclass, field(), default_factory and __post_init__ from earlier chapters. I also assume you know Python's method resolution order (MRO), the sequence in which Python searches base classes. The kw_only parts need Python 3.10 or newer.
How fields are collected
When @dataclass processes a class, it builds an ordered mapping of field names to field definitions. It does this in two steps:
- It walks the class's bases in reverse MRO order, from the most distant base to the nearest. For each base that is itself a dataclass, it copies that base's fields into the mapping.
- It then processes the class's own annotations. A new name goes at the end of the mapping. A name that already exists replaces the old definition but keeps its original position.
The resulting order controls the __init__ signature, __repr__, __eq__, ordering comparisons and astuple().
A basic hierarchy
from dataclasses import dataclass, field, fields
@dataclass
class Animal:
name: str
sound: str = "..."
@dataclass
class Dog(Animal):
sound: str = "woof"
tricks: list[str] = field(default_factory=list)
print(Dog("Rex")) # Dog(name='Rex', sound='woof', tricks=[])
print([f.name for f in fields(Dog)]) # ['name', 'sound', 'tricks']Dog redefines sound. The field keeps its second position, so Dog("Rex", "bark") still sets sound. The new default "woof" replaces the inherited "...". Then tricks is appended at the end.
Redefining a field replaces the whole definition, not only its default. If the subclass writes sound: str with no default, sound becomes required again, even though the base class gave it one.
The default-ordering error
The generated __init__ is an ordinary function signature, and Python forbids a parameter without a default after one that has a default. Inheritance makes this easy to hit. The base class fields always come first, so a base class with a default blocks every required field in a subclass.
from dataclasses import dataclass
@dataclass
class Base:
name: str
sound: str = "..."
try:
@dataclass
class Bad(Base):
age: int # required field after a defaulted one
except TypeError as e:
print(type(e).__name__) # TypeErrorThe exact message wording differs between Python versions. It always says that a non-default argument follows a default argument.
There are three ways to fix this:
| Fix | How | Trade-off |
|---|---|---|
| Give the new field a default | `age: int = 0` | Makes the field optional, which may not match your design |
| Make the subclass keyword-only | `@dataclass(kw_only=True)` | Callers must name the subclass's fields |
| Mark single fields keyword-only | `field(kw_only=True)` or the `KW_ONLY` marker | Mixed positional and keyword signature |
Keyword-only fields in subclasses
Keyword-only fields are removed from the positional part of __init__ and placed after a * marker. They can therefore never trigger the ordering error, whatever defaults surround them.
from dataclasses import dataclass, KW_ONLY, fields
@dataclass
class Base:
name: str
sound: str = "..."
@dataclass(kw_only=True)
class Pet(Base):
owner: str # required, but keyword-only
@dataclass
class Cat(Base):
_: KW_ONLY
indoor: bool # required, keyword-only
print(Pet("Rex", owner="Ana"))
print(Cat("Tom", indoor=True))
print([f.name for f in fields(Pet)]) # ['name', 'sound', 'owner']The kw_only=True argument applies only to fields defined in that class. The inherited name and sound in Pet stay positional. In Cat, every field declared after _: KW_ONLY is keyword-only. The name _ is only a placeholder, and the marker does not create a field.
Keyword-only fields also make hierarchies easier to extend. When you add a field to a base class later, subclasses that use keyword-only fields keep working.
Subclasses must be decorated
@dataclass only inspects the class it decorates. If you forget the decorator on a subclass, the subclass inherits the parent's generated methods, and its new annotations are ordinary class attributes.
from dataclasses import dataclass, fields
@dataclass
class Base:
name: str
class Sub(Base): # no @dataclass
extra: int = 0
s = Sub("a")
print(s) # Base(name='a')... shown as Sub(name='a')
print([f.name for f in fields(Sub)]) # ['name']
print(s.extra) # 0, a plain class attributeThe repr uses the real class name, so it prints Sub(name='a'). The field extra is missing from the repr, from __init__ and from comparison. Decorating Sub fixes this. This is a common source of silent bugs, because nothing raises an error.
Multiple inheritance
Because bases are walked in reverse MRO, the leftmost base in the class statement has its fields placed last among the bases.
from dataclasses import dataclass, fields
@dataclass
class A:
a: int = 0
@dataclass
class B:
b: int = 0
@dataclass
class C(B, A):
c: int = 0
print([f.name for f in fields(C)]) # ['a', 'b', 'c']
print(C()) # C(a=0, b=0, c=0)The MRO of C is C, B, A, object. Reversed, that gives A first, then B. This is the opposite of what many readers expect from class C(B, A). If two bases define the same field name, the one nearer the front of the MRO wins, and it takes the position of the earlier definition.
A base class that is not a dataclass contributes no fields, even if it has annotations. This makes plain mixin classes safe for adding behavior. Keep data in dataclass bases and methods in mixins.
`__post_init__` is not chained automatically
A subclass's __post_init__ replaces the base class's version. Python does not call both. You must call the parent explicitly, or its validation is skipped.
from dataclasses import dataclass
@dataclass
class Account:
owner: str
balance: float = 0.0
def __post_init__(self):
if self.balance < 0:
raise ValueError("balance must be non-negative")
@dataclass
class Savings(Account):
rate: float = 0.02
def __post_init__(self):
super().__post_init__()
if not 0 <= self.rate <= 1:
raise ValueError("rate must be between 0 and 1")
try:
Savings("Ana", -5)
except ValueError as e:
print(e) # balance must be non-negativeIf you remove the super().__post_init__() line, Savings("Ana", -5) is accepted without error.
Equality, ordering and frozen across classes
Comparison methods are generated with a strict class check. The generated __eq__ returns NotImplemented unless both objects have exactly the same class. Python then falls back to identity, so the result is False.
from dataclasses import dataclass
@dataclass
class P:
x: int
@dataclass
class Q(P):
pass
print(P(1) == P(1)) # True
print(P(1) == Q(1)) # False: different classesThe same check applies to order=True. Comparing a base instance with a subclass instance using < raises TypeError.
The frozen setting must match across a hierarchy. A frozen dataclass cannot be inherited by a non-frozen one, and a non-frozen dataclass cannot be inherited by a frozen one. Mixing them raises TypeError when the class is created.
from dataclasses import dataclass
@dataclass(frozen=True)
class Fixed:
x: int
try:
@dataclass
class Loose(Fixed):
y: int
except TypeError as e:
print(e) # cannot inherit non-frozen dataclass from a frozen oneDeclare frozen=True on every class in the hierarchy.
Gotchas with `slots=True`
With slots=True, the decorator creates a new class object to hold __slots__. Two consequences matter for inheritance:
- Slots save memory only if every dataclass in the chain uses them. A base class without
__slots__still gives each instance a__dict__. - Zero-argument
super()inside methods of aslots=Trueclass can fail in some Python versions, because the method refers to the original class that the decorator replaced. If you hit this, use a different class design or check the notes for your Python version.
Design guidelines
- Keep base classes small and free of defaults, or make the optional fields keyword-only.
- Use
kw_only=Trueon subclasses that add required fields to a base with defaults. - Decorate every subclass, and use the same
frozensetting throughout. - Call
super().__post_init__()whenever a base class defines one. - Prefer composition (a field holding another dataclass) when the "is-a" relationship is weak. Inheritance couples field order across classes.
Exercise
A base dataclass has a: int = 1. A subclass decorated with @dataclass adds b: int. Why does this fail, and give two different ways to fix it.
Show answer
Base fields come first, so the generated __init__(self, a=1, b) would put a required parameter after a defaulted one, which raises TypeError when the class is created. Fix 1: give b a default (b: int = 0). Fix 2: make b keyword-only with @dataclass(kw_only=True) on the subclass, or b: int = field(kw_only=True), so that b moves after the * marker in __init__.
Exercise
Given class A with fields x and y (both int), and class B(A) that redefines x: str = "hi" and adds z: int = 0, what is the field order of B, and what does B(y=5) fail on, if anything?
Show answer
The order is y... no: x, y, z. The redefined x keeps its first position and now has the default "hi". However, y has no default and follows x, which now has one, so creating B raises TypeError. The fix is to give y a default or to make y or the later fields keyword-only. B(y=5) never runs, because the class definition itself fails.