Python OOP and typing · Trade-off
dataclass, Pydantic model or attrs
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
You need a class for an order: id, customer, items, amount and created time. Would you use a dataclass, a Pydantic model, attrs, or a plain class? What changes if the data comes from a partner's JSON API?
Then
Follow-ups the interviewer asks next
- The partner sends
"amount": "499.00"as a string. What does each option do? - Why might creating 10 lakh Pydantic objects in a loop be slow, and what would you do?
- What does
frozen=Truegive you, and what doesn't it protect? - When would you use a
TypedDictinstead?
The answer
What a strong answer covers
- Dataclass: standard library; generates
__init__,__repr__,__eq__; optionsfrozen,slotsandkw_only(3.10),field(default_factory=...),__post_init__. Type hints are not checked at runtime. - Pydantic (v2, Rust core; 2.14 as of Oct 2026): validates and converts at runtime, parses and writes JSON, makes JSON Schema; lax mode turns
"499.00"into a number, strict mode refuses it. Costs more per object than a dataclass. - attrs: the third-party library dataclasses grew from; validators, converters, slots by default with
@define. - Rule of thumb: validate at the edges (API input, config, model output), plain dataclasses inside. Money as
Decimal. frozen=Truestops reassigning fields, but a list field can still be changed in place.TypedDictfor typed dicts passed around as JSON-like data;NamedTuplefor small read-only records.
The red pen
Common traps
Avoid:"dataclasses validate types"; Pydantic models for every internal object in a hot loop.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.