Interview frequency: …
Short answer
It automatically generates __init__, __repr__ and __eq__ (and optionally ordering, hash and freezing) from the fields declared with type annotations.
Explanation
dataclass reduces boilerplate for data-holding classes. The key options are frozen=True to prevent modification and make the object hashable, slots=True to reduce memory, kw_only=True to force keyword arguments, and order=True to generate comparison operations. Use field(default_factory=list) for mutable defaults, and put validation in __post_init__. Note that dataclass does not check types at runtime.
Code example
from dataclasses import dataclass, field
@dataclass(frozen=True, slots=True)
class Order:
id: int
items: tuple[str, ...] = ()
@dataclass
class Cart:
lines: list[str] = field(default_factory=list)
def __post_init__(self):
if len(self.lines) > 100:
raise ValueError("too many lines")Common mistakes
- Writing lines: list = [] directly, which dataclass rejects with a ValueError.
- Assuming dataclass validates types at runtime like Pydantic does.