Stop 07 · Object-Oriented ProgrammingTopics · 10/10

Dataclasses

Part of the Python Roadmap

In short

Writing __init__, __repr__ and __eq__ for every small data-holding class is boring and error-prone. @dataclass writes them for you from a list of typed fields.

The @dataclass decorator writes __init__, __repr__ and __eq__ for you from type-annotated fields. It is ideal for classes that mainly hold data, and options like frozen=True make them immutable.

The jaadu cranks an old-fashioned printing press that pushes out a neat stack of identical blank forms.

Think of it like this

A pre-printed admission form

Instead of writing out 'Name: ___ Class: ___ Roll: ___' by hand on every sheet, the school prints the form once and you just fill in values. @dataclass is that printing press: declare the fields once and Python prints the constructor, the display text and the comparison for you.

Watch it happen

Hand-written class vs dataclass

Regular class

  • Write __init__ yourself
  • Write __repr__ yourself
  • Write __eq__ yourself
  • Easy to forget a field

@dataclass

  • Fields declared once with types
  • __init__, __repr__, __eq__ generated
  • Options: frozen, order, slots
  • Still a normal class with methods

If a class mainly stores data, start with @dataclass. Switch to a hand-written class only when construction needs complex logic.

The big ideas

What you need to know

Typed fields

Each field is name: type, with optional defaults. Fields without defaults must come first.

field(default_factory=list)

Never write tags: list = []. Use field(default_factory=list) so every object gets its own new list.

frozen=True

Makes objects read-only after creation, and hashable, so they can go in sets and be dict keys.

__post_init__

Runs right after the generated __init__. Use it for validation or computed fields.

See it in code

Walk through the code

python
1from dataclasses import dataclass, field2 3@dataclass4class Product:5    name: str6    price: float7    qty: int = 18    tags: list[str] = field(default_factory=list)9 10    def __post_init__(self) -> None:11        if self.price < 0:12            raise ValueError("Price can't be negative")13 14    @property15    def total(self) -> float:16        return self.price * self.qty17 18@dataclass(frozen=True)19class PinCode:20    code: str21    city: str22 23p = Product("Kurta", 799, 2)24print(p)              # Product(name='Kurta', price=799, qty=2, tags=[])25print(p.total)        # 159826print(p == Product("Kurta", 799, 2))   # True27 28delivery = {PinCode("560001", "Bengaluru"), PinCode("400001", "Mumbai")}29print(len(delivery))  # 2

1/7Four typed fields. qty and tags have defaults, so they come after name and price.

A Product dataclass with defaults, validation and a computed property, plus a frozen PinCode usable in a set.

Save yourself the pain

Common mistakes

Oops

Writing tags: list = [] as a field default.

Do this instead

Python raises ValueError for mutable defaults. Use field(default_factory=list).

Oops

Putting a field without a default after one with a default.

Do this instead

Order matters, like function parameters. Put required fields first.

Your mission

Train booking records

~20 min

Quick check

Which method does @dataclass NOT generate by default?

Go deeper

  1. 1Rewrite a simple data-holding class as a dataclass.
  2. 2Use field(default_factory=list) for a list field.
  3. 3Try frozen=True and see what happens when you change a field.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge