dataclasses and __slots__
As a Architect engineer, explain dataclasses and __slots__. What problem does it solve and how would you describe it in an interview?
Answers use simple, clear English.
Audio N/AQuick interview answer
At Architect depth: start with the problem, then mechanism, then a short example. @dataclass auto-generates __init__, __repr__, __eq__.
Detailed answer
At Architect depth: start with the problem, then mechanism, then a short example. @dataclass auto-generates __init__, __repr__, __eq__. slots=True (Py3.10+) fixes attributes and saves memory. frozen=True makes instances hashable if all fields hashable. Core: @dataclass auto-generates __init__, __repr__, __eq__. slots=True (Py3.10+) fixes attributes and saves memory. frozen=True makes instances hashable if all fields hashable. Real-time example: DTO layer: @dataclass(slots=True) OrderItem(sku: str, qty: int, price: Decimal). Pros: Less boilerplate than manual classes; slots reduce per-instance dict overhead. Cons: Inheritance with slots tricky; default mutable fields need default_factory. Common mistakes: Mutable default list in dataclass field; forgetting frozen for dict keys. Best practices: Use field(default_factory=list); kw_only=True for clarity in large models. Audience level: Architect.
Full explanation
@dataclass auto-generates __init__, __repr__, __eq__. slots=True (Py3.10+) fixes attributes and saves memory. frozen=True makes instances hashable if all fields hashable.
Real example & use case
DTO layer: @dataclass(slots=True) OrderItem(sku: str, qty: int, price: Decimal).
Pros & cons
Pros: Less boilerplate than manual classes; slots reduce per-instance dict overhead. Cons: Inheritance with slots tricky; default mutable fields need default_factory.
Common mistakes
Mutable default list in dataclass field; forgetting frozen for dict keys.
Best practices
Use field(default_factory=list); kw_only=True for clarity in large models.
Follow-up questions
- How would you test dataclasses and __slots__?
- What metrics prove dataclasses and __slots__ is healthy in prod?
- How does dataclasses and __slots__ change at 10× traffic?