Skip to content
Codewilds

Lesson 27 of 34 · Classes & OOP

Python Dataclasses

medium20 XP3 min read

Many classes exist mainly to hold data: a point, a product, a player record. Writing __init__, __repr__ and __eq__ for each of them by hand is repetitive and error-prone. Python's dataclasses generate all of that for you from a short list of typed fields.

Your first dataclass

from dataclasses import dataclass


@dataclass
class Point:
    x: int
    y: int


p = Point(3, 4)
print(p)                    # Point(x=3, y=4)
print(p.x)                  # 3
print(p == Point(3, 4))     # True

The @dataclass decorator reads the annotated class attributes — x: int and y: int — and writes an __init__, a readable __repr__ and a value-based __eq__ for you. Compare that with the dozen lines the same class needed in the previous lessons.

Default values and methods

Fields can have defaults, and dataclasses are still normal classes, so you can add methods freely:

@dataclass
class Player:
    name: str
    level: int = 1
    gold: float = 0.0

    def is_rich(self):
        return self.gold >= 1000


bo = Player("Bo")
print(bo)                        # Player(name='Bo', level=1, gold=0.0)
print(Player("Ada", gold=1500).is_rich())   # True

Just like function parameters, fields without defaults must come before fields with defaults.

Mutable defaults need default_factory

A list, dict or set default would be shared by every instance — the same trap as mutable default arguments. Dataclasses refuse it outright, so use field(default_factory=...) to create a fresh value for each object:

from dataclasses import dataclass, field


@dataclass
class Party:
    name: str
    members: list[str] = field(default_factory=list)


a = Party("Owls")
b = Party("Foxes")
a.members.append("Ada")
print(b.members)   # []  — each party has its own list

Frozen dataclasses

@dataclass(frozen=True) makes instances immutable. Assigning to a field raises FrozenInstanceError, and frozen instances are hashable, so they can be stored in sets or used as dictionary keys:

@dataclass(frozen=True)
class Coord:
    row: int
    col: int


visited = {Coord(0, 0), Coord(0, 1)}
print(Coord(0, 0) in visited)   # True

Ordering

@dataclass(order=True) adds <, <=, > and >=, comparing fields in the order they are declared — so sorted() works out of the box.

Validation with __post_init__

The generated __init__ calls __post_init__ (if you define one) after setting the fields — the place for validation or derived values:

@dataclass
class Potion:
    name: str
    power: int

    def __post_init__(self):
        self.power = max(0, min(self.power, 100))   # clamp to 0-100

The dataclasses module also offers helpers such as asdict(), which converts an instance to a dictionary.

Common mistakes

  • Forgetting the type annotation: name = "x" without : str is an ordinary class attribute, not a field.
  • Mutable defaults: members: list = [] raises ValueError: mutable default ... is not allowed: use default_factory.
  • A field without a default after one with a default raises TypeError when the class is created.
  • Expecting type checks: annotations aren't enforced at runtime — Point("a", "b") works fine.

Assignment

Turn two classes into dataclasses:

  1. Item with the fields name: str, price: float and quantity: int (default 1), plus a method total() that returns price * quantity.
  2. Cart with the fields owner: str and items: list[Item], which defaults to a new empty list for every cart. Add a method add(item) that appends an item, and total() that returns the sum of all item totals (0 for an empty cart).
cart = Cart("Ada")
cart.add(Item("Potion", 2.5, 2))
cart.add(Item("Arrow", 0.5, 10))
cart.total()               # 10.0
Item("Map", 3.0)           # Item(name='Map', price=3.0, quantity=1)

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Value objects and equality in other languages

Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.

Lesson last updated on .

Write code ↓
Python+20 XP

Lesson 27 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.