Guides / Python

Python · guide

Python dataclasses: records without boilerplate

A dataclass writes __init__, __repr__ and equality for you, so a record type takes a few lines.

The basics

from dataclasses import dataclass

@dataclass
class Player:
    name: str
    level: int = 1

p = Player("Kai", 12)
print(p)            # Player(name='Kai', level=12)
print(p == Player("Kai", 12))   # True

Mutable defaults need field()

from dataclasses import dataclass, field

@dataclass
class Team:
    name: str
    members: list = field(default_factory=list)

Writing members: list = [] is rejected because every instance would share one list.

Immutable records

@dataclass(frozen=True)
class Point:
    x: int
    y: int

Frozen instances cannot be changed and can be used as dict keys.

When to use what

Practise it

Share on LinkedIn

Practise this for free

Run real code, get instant checks and keep your progress. Free to join with Google.

Start free → Choose a career path

More guides