Skip to content

Module 17 · Advanced Python Concepts — topic 13 of 14

Dataclasses

Concise data-holding classes with @dataclass: automatic __init__, __repr__ and __eq__, default values and default_factory, ordering, frozen instances, __post_init__ validation, computed fields, asdict and replace.

Beginner 10 min read·Lesson 259 of 306 in Python Programming

Learning objectives

  • Define dataclasses with defaults
  • Use options such as order and frozen
  • Validate and compute fields in __post_init__

Definition

The @dataclass decorator generates common methods for classes that mainly store data, based on their annotated fields: __init__, __repr__, __eq__ and optionally ordering and immutability.

Introduction

A Point class with __init__, __repr__ and __eq__ takes a dozen lines. With @dataclass it takes three.

Why it matters

Dataclasses remove boilerplate, prevent mistakes in hand-written equality and repr methods, and make data models obvious at a glance.

Detailed explanation

Decorate a class with @dataclass and declare fields with annotations: x: float. Fields with defaults must come after fields without.

Generated __init__ takes the fields in order; __repr__ shows them; __eq__ compares them.

Mutable defaults need field(default_factory=list) so each instance gets its own list.

@dataclass(order=True) adds <, <=, >, >= comparing fields in order; frozen=True makes instances immutable (and hashable).

__post_init__ runs after the generated __init__, ideal for validation and computing derived fields declared with field(init=False).

dataclasses.asdict converts an instance (recursively) to a dictionary; replace creates a modified copy.

slots=True (Python 3.10+) adds __slots__ for lower memory use.

kw_only=True makes every field keyword-only, so calls such as Order(id=1, discount=0.1) stay readable and can't silently swap two arguments of the same type.

field(repr=False) hides a field (such as a password hash) from the generated repr, and field(compare=False) excludes it from equality and ordering.

Compared with namedtuple, dataclasses are mutable by default, support defaults and methods naturally, and validate in __post_init__; compared with a hand-written class, they remove boilerplate without hiding any behaviour.

Syntax

Python
from dataclasses import dataclass, field
@dataclass
class Cart:
owner: str
items: list[str] = field(default_factory=list)
discount: float = 0.0
  • Fields come from annotations.
  • default_factory for mutable defaults.
  • order and frozen options.

Code examples

A first dataclass

Python
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float = 0.0
p = Point(3, 4)
print(p, p == Point(3, 4), Point(1))
Output
Point(x=3, y=4) True Point(x=1, y=0.0)

Ordering, frozen and default_factory

Python
from dataclasses import FrozenInstanceError, dataclass, field
@dataclass(order=True, frozen=True)
class Version:
major: int
minor: int = 0
print(sorted([Version(2, 1), Version(1, 9), Version(2, 0)]))
v = Version(1)
try:
v.major = 3
except FrozenInstanceError as e:
print(type(e).__name__)
@dataclass
class Cart:
items: list[str] = field(default_factory=list)
a, b = Cart(), Cart()
a.items.append("pen")
print(a, b)
Output
[Version(major=1, minor=9), Version(major=2, minor=0), Version(major=2, minor=1)]
FrozenInstanceError
Cart(items=['pen']) Cart(items=[])

More examples

Validation and computed fields

Python
from dataclasses import asdict, dataclass, field, replace
@dataclass
class Order:
id: int
items: list[tuple[str, float, int]] = field(default_factory=list)
discount: float = 0.0
total: float = field(init=False)
def __post_init__(self):
if not 0 <= self.discount <= 0.5:
raise ValueError("discount must be between 0 and 0.5")
self.total = round(sum(p * q for _, p, q in self.items) * (1 - self.discount), 2)
o = Order(1, [("pen", 20.0, 3), ("bag", 1200.0, 1)], discount=0.1)
print(o.total)
print(asdict(o)["items"][0])
o2 = replace(o, id=2, discount=0.0)
print(o2.id, o2.total)
try:
Order(3, discount=0.9)
except ValueError as e:
print(e)
Output
1134.0
('pen', 20.0, 3)
2 1260.0
discount must be between 0 and 0.5

Step-by-step explanation

  • total is not an __init__ argument; __post_init__ computes it after validating the discount.
  • asdict turns the order into plain data, ready for JSON.
  • replace builds a new order, running __init__ and __post_init__ again, so the total is recalculated.

Expected output

Running “Validation and computed fields” prints exactly:

TextOutput
1134.0
('pen', 20.0, 3)
2 1260.0
discount must be between 0 and 0.5

Practical applications

  • Configuration objects and API response models.
  • Records read from CSV files.

Best practices

  • Use dataclasses for data-centred classes.
  • Validate in __post_init__.
  • Use frozen=True for value objects.

Common mistakes

Mutable default value

Avoid

@dataclass
class Cart:
items: list = []

Prefer

items: list = field(default_factory=list)

dataclasses reject plain mutable defaults with ValueError.

Important notes

  • Dataclasses are ordinary classes: you can add methods and properties.

Key takeaways

  • @dataclass generates __init__, __repr__ and __eq__.
  • default_factory, order and frozen customise it.
  • __post_init__ validates and computes.

Try it yourself

  1. 1
    Write a frozen Money dataclass with amount and currency and an add method that checks currencies.
  2. 2
    Convert a list of Student dataclasses to JSON using asdict.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
Practise this topic