What does the `@dataclass` decorator generate for you, and when is a plain class still the better choice?
Answer
`@dataclass` inspects a class's annotated fields and automatically generates `__init__`, `__repr__` and `__eq__` (comparing all fields), removing the boilerplate of writing those by hand for a class that mostly just carries data. `frozen=True` makes field assignment raise after `__init__` — `instance.x = 5` fails — which emulates read-only fields, but it does not make an instance deeply immutable: a field holding a mutable object like a list can still be mutated through that object's own methods. Hashability is a separate, related option: a dataclass is unhashable by default once `eq=True` (the default) generates `__eq__`, since a mutable object with value-based equality is deliberately made unhashable to avoid silently corrupting a set or dict; `frozen=True` combined with `eq=True` is what actually makes instances hashable, and only if every field's current value is itself hashable. A plain class is still the better choice when the type has significant custom behavior, invariants enforced across many methods, or an inheritance hierarchy where the generated dunder methods would not do the right thing.
Strong answer includes
- frozen=True prevents field reassignment but does not make referenced mutable objects immutable
- hashability depends on frozen=True combined with eq=True, and on every field being itself hashable
- plain class better for heavy custom behavior or complex hierarchies
Practical example
@dataclass(frozen=True)
class Point:
x: float
y: floatgives a fully working, hashable, immutable value type in four lines instead of about twenty lines of hand-written dunder methods.