Sub topic 11
Inheritance and field ordering
This chapter assumes you can write a basic @dataclass with defaults and default_factory, and that you know how normal class inheritance works. The kw_only example needs Python 3.10 or newer.
How fields are collected
A dataclass subclass inherits the fields of its parent dataclasses. When you apply @dataclass to the subclass, Python builds the field list in this order:
- It starts with the fields of the base classes, working from the most distant base toward the nearest.
- It adds the fields declared in the subclass itself.
- If the subclass redeclares a field that already exists, the new definition replaces the old one. The field keeps its original position.
from dataclasses import dataclass, field
@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=[])Dog redefines sound, so the default changes to "woof", but sound stays second. The new field tricks is added at the end. The generated __init__ signature is (name, sound="woof", tricks=...).
The default-ordering problem
The generated __init__ is an ordinary function. In a Python function signature, a parameter without a default cannot follow one that has a default. Dataclass inheritance runs into this rule often, because base class fields always come first.
from dataclasses import dataclass
@dataclass
class Animal:
name: str
sound: str = "..."
try:
@dataclass
class Puppy(Animal):
age: int # no default, but it comes after sound
except TypeError as e:
print(e) # non-default argument 'age' follows default argumentThe error appears when the class is defined, not when you create an instance. You have three ways to fix it.
- Give the new field a default, such as
age: int = 0. - Move the default out of the base class, if you own it.
- Make the new fields keyword-only.
Fixing it with kw_only
Keyword-only fields are moved to the end of the __init__ signature, after the positional ones. They are exempt from the ordering rule.
from dataclasses import dataclass
@dataclass
class Animal:
name: str
sound: str = "..."
@dataclass(kw_only=True)
class Puppy(Animal):
age: int
print(Puppy("Rex", age=1)) # Puppy(name='Rex', sound='...', age=1)kw_only=True applies only to the fields declared in Puppy itself. The inherited name and sound stay positional. Callers must write age=1, so mixed positional and keyword calls stay readable.
You can also mark single fields with field(kw_only=True). The KW_ONLY sentinel from dataclasses makes every field after it keyword-only.
Rules to remember
- Only dataclass bases contribute fields. A plain base class can add methods, but its annotations are not collected as fields unless the base is also decorated with
@dataclass. - Redefining keeps the position. Overriding a default does not move a field. Overriding a field is the way to change a parent's default.
- Frozen status must match. A frozen dataclass cannot inherit from a non-frozen one, and a non-frozen one cannot inherit from a frozen one. Either mix raises
TypeError. - Generated methods are rebuilt. Each decorated class gets its own
__init__,__repr__and__eq__that cover all fields, including inherited ones. __post_init__is a normal method. If a subclass defines its own, it replaces the parent's. Callsuper().__post_init__()if the parent's validation must still run.
from dataclasses import dataclass
@dataclass
class Shape:
name: str
def __post_init__(self):
self.name = self.name.strip()
@dataclass
class Circle(Shape):
radius: float = 1.0
def __post_init__(self):
super().__post_init__()
if self.radius <= 0:
raise ValueError("radius must be positive")
print(Circle(" disc ", 2.0)) # Circle(name='disc', radius=2.0)Without the super() call, the name would keep its extra spaces.
Equality across classes
The generated __eq__ compares two instances only if they have exactly the same class. An Animal("Rex") is not equal to a Dog("Rex"), even when the shared fields match. This differs from some hand-written __eq__ methods that check isinstance.
Exercise
A base dataclass Item has the fields sku: str and price: float = 0.0. You write @dataclass class Perishable(Item): days_left: int. What happens, and how do you fix it while keeping days_left required?
Show answer
Defining Perishable raises TypeError: non-default argument 'days_left' follows default argument, because days_left comes after price, which has a default. Declare the subclass with @dataclass(kw_only=True) (Python 3.10 or newer). The field then moves to the keyword-only part of __init__ and stays required, so callers write Perishable("A1", days_left=3).