Question presented to candidate:
"We have a lot of small classes that just hold data and every one has the same hand-written __init__, __repr__ and __eq__. What does @dataclass do for us, how do you configure it, and where does it fall short?"
What a strong answer should cover:
@dataclass(standard library since Python 3.7, PEP 557) reads the annotated class attributes as fields and generates__init__,__repr__and__eq__from them, in declaration order- Defaults and the mutable-default rule:
list,dictandsetdefaults are rejected withValueError; usefield(default_factory=list) __post_init__for validation and derived fields,field(init=False),InitVar, and helpersasdict,replace,fields- Options:
frozen=True(immutable and hashable),order=True(tuple-style comparisons),slots=Trueandkw_only=True(3.10+);eq=Truealone makes instances unhashable - Limits: type hints are not validated at runtime (that is what Pydantic is for), default-before-non-default ordering breaks with inheritance, and how it compares with
NamedTupleand plain classes
Clarifying questions expected:
- Do the objects need to be immutable or usable as dict keys?
- Is the input trusted, or does it need runtime validation (for example parsed JSON)?
Code / implementation expected: Yes β a small dataclass with a default_factory field and a __post_init__ check, ideally a frozen one used as a dict key.