datarekha
Python Easy Asked at GoogleAsked at MetaAsked at AmazonAsked at StripeAsked at Airbnb

What does `@dataclass` give you over a plain class, and what are its main configuration options?

The short answer

`@dataclass` auto-generates `__init__`, `__repr__`, and `__eq__` from the field annotations declared in the class body, eliminating boilerplate. Key options include `frozen=True` for immutability and automatic `__hash__`, `order=True` for comparison operators, and `slots=True` (Python 3.10+) for memory-efficient slot-based storage.

How to think about it

@dataclass is a class decorator that reads your field annotations and generates the dunder boilerplate you’d otherwise write by hand. The important thing to understand is what it generates, when, and which options change that behaviour — because frozen=True, order=True, and slots=True come up constantly in interviews.

What’s really being tested

The interviewer wants to see that you can contrast the boilerplate saved, explain the configuration options, and know the gotcha: mutable defaults (tags: list = []) are rejected at class-definition time with a helpful ValueError.

Step 1 — See what gets generated

A @dataclass with three fields auto-creates __init__, __repr__, and __eq__. Compare to writing all of that manually.

Step 2 — Key configuration options

  • frozen=True makes instances immutable and generates __hash__, so you can use them as dict keys or set members.
  • order=True generates __lt__, __le__, __gt__, __ge__ comparing fields left-to-right in declaration order.
  • field(default_factory=list) is the safe way to declare a mutable default.

slots=True (Python 3.10+)

@dataclass(slots=True)
class Pixel:
    x: int
    y: int
    color: str

Equivalent to declaring __slots__ manually — no __dict__, lower memory per instance, faster attribute access. Useful when you’re creating millions of instances.

Learn it properly dataclasses

Keep practising

All Python questions

Explore further

Skip to content