Python · The language, not just syntax
When should you use a dataclass?
Short answer
Use a dataclass for classes that mainly hold data. The decorator generates __init__, __repr__ and __eq__, and options such as frozen, slots and order add immutability, memory savings and comparisons.
The dataclasses module removes repetitive constructor and representation code while keeping normal class semantics. It is a good default for configuration objects, domain records and internal DTOs where you do not need runtime validation.
from dataclasses import dataclass, field
@dataclass(frozen=True, slots=True)
class Order:
order_id: str
items: tuple[str, ...]
tags: list[str] = field(default_factory=list)
order = Order("A-1", ("book", "pen"))
print(order)
print(order == Order("A-1", ("book", "pen")))Useful options
- frozen=True: immutable instances and a generated __hash__
- slots=True: lower memory and faster attribute access, but no dynamic attributes
- order=True: generated comparison methods based on field order
- field(default_factory=...): safe defaults for mutable values
Dataclasses do not validate input or coerce types at runtime. If data arrives from JSON, an API or user input, use Pydantic or an explicit factory function to validate before constructing the object. Frozen only prevents rebinding fields; a contained list can still be mutated.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why does a mutable default require default_factory?
- 2Does frozen=True make nested objects immutable?
- 3How do dataclasses compare with Pydantic models or namedtuples?
- 4What does slots=True change about the class?
Say it in the interview
I use a dataclass when a class mostly carries data, because it generates the constructor, repr and equality from the field declarations. I add frozen for value objects, slots when memory matters, and default_factory for mutable defaults. I do not treat it as validation, since it will not reject bad input. For external data I validate with Pydantic or a factory before building the dataclass.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.