Skip to the solution
MediumDSA11 min read

What are dataclasses?

733 views

The problem

Question presented to candidate: "We have a lot of small classes that just hold data and every one has the same hand-written __init__, __repr__ and __eq__. What does @dataclass do for us, how do you configure it, and where does it fall short?"

What a strong answer should cover:

  • @dataclass (standard library since Python 3.7, PEP 557) reads the annotated class attributes as fields and generates __init__, __repr__ and __eq__ from them, in declaration order
  • Defaults and the mutable-default rule: list, dict and set defaults are rejected with ValueError; use field(default_factory=list)
  • __post_init__ for validation and derived fields, field(init=False), InitVar, and helpers asdict, replace, fields
  • Options: frozen=True (immutable and hashable), order=True (tuple-style comparisons), slots=True and kw_only=True (3.10+); eq=True alone makes instances unhashable
  • Limits: type hints are not validated at runtime (that is what Pydantic is for), default-before-non-default ordering breaks with inheritance, and how it compares with NamedTuple and plain classes

Clarifying questions expected:

  • Do the objects need to be immutable or usable as dict keys?
  • Is the input trusted, or does it need runtime validation (for example parsed JSON)?

Code / implementation expected: Yes β€” a small dataclass with a default_factory field and a __post_init__ check, ideally a frozen one used as a dict key.

  • dataclasses

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonWhat @dataclass generates, default_factory, __post_init__ and the helpers
Pythonfrozen, order, slots, kw_only, InitVar, inheritance and match

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 69 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is asyncio.TaskGroup and why does it replace gather?

Continue