Object-Oriented ProgrammingIntermediate6 min47 / 66

Dataclasses

Let @dataclass write the boilerplate — __init__, __repr__, and equality — from a few typed fields.

Classes that mostly hold data need a repetitive __init__, a readable __repr__, and often an __eq__. The @dataclass decorator (from the standard library) generates all of that from a few annotated fields.

the same class, far less code
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int = 0        # a default value

p = Point(3, 4)
print(p)              # nice repr, for free
print(p == Point(3, 4))  # value equality, for free
print(Point(5))       # y defaults to 0

Without @dataclass you'd hand-write __init__ to assign each field, plus __repr__ and __eq__. The decorator reads the class-level type annotations and does it for you.

#Handy options

frozen (immutable) & ordering
from dataclasses import dataclass

@dataclass(frozen=True, order=True)
class Version:
    major: int
    minor: int

v1 = Version(1, 2)
print(v1 < Version(1, 5))  # order=True gives comparisons
# v1.major = 2  # frozen=True -> raises FrozenInstanceError
Tip

When to reach for it

Use a dataclass whenever a class is mostly a bundle of values (config, records, DTOs, coordinates). frozen=True makes instances immutable (and hashable); order=True adds <, >, etc. For heavy behavior, a regular class is still the right call.

Quick check

What does @dataclass generate for you from the annotated fields?

Key takeaways

  • `@dataclass` auto-generates `__init__`, `__repr__`, and `__eq__` from annotated fields.
  • Fields are declared as class-level annotations: `x: int`, with optional defaults (`y: int = 0`).
  • `frozen=True` makes instances immutable; `order=True` adds comparison operators.
  • Ideal for value/record classes; use a regular class when behavior dominates.
Practice challenges
Test yourself · earn XP
0/3
Predict the output#1

What does this print?

predict-output
from dataclasses import dataclass

@dataclass
class P:
    x: int
    y: int = 0

print(P(3))
Predict the output#2

What does this print?

predict-output
from dataclasses import dataclass

@dataclass
class P:
    x: int
    y: int

print(P(1, 2) == P(1, 2))
Fill in the blank#3

Complete the line so instances are immutable.

@dataclass(=True)
class Point:
    x: int
Your turn
Practice exercise

Turn this plain class into a dataclass with fields title: str and pages: int (default 0):

``python class Book: def __init__(self, title, pages=0): self.title = title self.pages = pages ``

Try it live — edit the code and hit Run to execute real Python:

solution.py · editable