Python › Dataclasses & NamedTuples

How would you implement inheritance between dataclasses, and what field-ordering rule must be respected across the hierarchy?

Advanced

Answer

A dataclass CAN inherit from another dataclass; the subclass's own fields are appended AFTER the parent's fields in the generated __init__ signature — meaning if the parent has any field WITH a default, every field the subclass adds must ALSO have a default, or you'll hit the same 'non-default argument follows default argument' error.
@dataclass
class Animal:
    name: str
    sound: str = "..."

@dataclass
class Dog(Animal):
    breed: str = "unknown"  # must have a default, since parent's 'sound' already has one

d = Dog(name="Rex", breed="Labrador")
print(d)  # Dog(name='Rex', sound='...', breed='Labrador')
Real-world example Building a hierarchy of related dataclasses (like a base Event class extended by specific event types) sharing common fields.

Common follow-ups: How does Python 3.10+'s kw_only=True parameter help avoid this field-ordering restriction entirely?