dataclasses and __slots__
Compare dataclasses and __slots__ with a common alternative (angle 2). How do you decide in a design review?
Answers use simple, clear English.
Audio N/AQuick interview answer
Baseline: @dataclass auto-generates __init__, __repr__, __eq__. slots=True (Py3.10+) fixes attributes and saves memory.
Detailed answer
Baseline: @dataclass auto-generates __init__, __repr__, __eq__. slots=True (Py3.10+) fixes attributes and saves memory. frozen=True makes instances hashable if all fields hashable. Prefer when pros dominate: Less boilerplate than manual classes; slots reduce per-instance dict overhead.. Avoid when: Inheritance with slots tricky; default mutable fields need default_factory.. 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: Junior.
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
Only answered follow-ups are shown — click to open with full answers