Skip to the page

Python OOP and typing · Trade-off

dataclass, Pydantic model or attrs

The 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

  1. The partner sends "amount": "499.00" as a string. What does each option do?
  2. Why might creating 10 lakh Pydantic objects in a loop be slow, and what would you do?
  3. What does frozen=True give you, and what doesn't it protect?
  4. When would you use a TypedDict instead?

The answer

What a strong answer covers

  • Dataclass: standard library; generates __init__, __repr__, __eq__; options frozen, slots and kw_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=True stops reassigning fields, but a list field can still be changed in place.
  • TypedDict for typed dicts passed around as JSON-like data; NamedTuple for 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 voice

Practise 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.

Start your free interview