What is Python's @dataclass vs namedtuple vs attrs?
Why Interviewers Ask This
Senior Python engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.
Answer
All three create data containers with reduced boilerplate but differ significantly. namedtuple: immutable, tuple-based, memory-efficient, supports unpacking and indexing, no mutability — use for simple read-only records. @dataclass: mutable by default (frozen=True for immutability), supports inheritance, post_init, field() customization, default_factory — use for most data classes. Generates __init__, __repr__, __eq__. Optional: __hash__, __lt__. attrs (third-party): the most powerful — validators, converters, slots support, factory functions, frozen, evolved API — more features than dataclasses with similar syntax. Pydantic: runtime data validation, JSON serialization, schema generation — the go-to for API data validation (used by FastAPI). Choose: namedtuple for simple immutable, @dataclass for general purpose, Pydantic for validated data from external sources.
Common Mistake
Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex Python answers easy to follow.
Previous
What is Python's Abstract Base Classes?
Next
What is Python's memory management and garbage collection?