dataclasses and __slots__
Implement or sketch code for dataclasses and __slots__. Explain the logic, complexity, and pros/cons of this approach.
Answers use simple, clear English.
Quick interview answer
Logic: @dataclass auto-generates __init__, __repr__, __eq__. slots=True (Py3.10+) fixes attributes and saves memory.
Detailed answer
Logic: @dataclass auto-generates __init__, __repr__, __eq__. slots=True (Py3.10+) fixes attributes and saves memory. frozen=True makes instances hashable if all fields hashable. Complexity notes included in code section when present. Pros: Less boilerplate than manual classes; slots reduce per-instance dict overhead. Cons: 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: Fresher.
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.
Code example
from dataclasses import dataclass, field
@dataclass(slots=True, frozen=True)
class Point:
x: float
y: float
@dataclass
class Cart:
items: list[str] = field(default_factory=list)
def add(self, sku: str) -> None:
self.items.append(sku)Practice code · python (view only · no execution)
from dataclasses import dataclass, field
@dataclass(slots=True, frozen=True)
class Point:
x: float
y: float
@dataclass
class Cart:
items: list[str] = field(default_factory=list)
def add(self, sku: str) -> None:
self.items.append(sku)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