Dataclasses
Overview
Many classes mostly hold data: a book, a point, a product, an expense. Writing them by hand means typing every attribute three times in __init__, then writing __repr__ and __eq__ too. The dataclasses module writes all that for you from a short list of fields.
Before and after
By hand:
class Book:
def __init__(self, title, author, pages=0):
self.title = title
self.author = author
self.pages = pages
def __repr__(self):
return f"Book(title={self.title!r}, author={self.author!r}, pages={self.pages!r})"
def __eq__(self, other):
if not isinstance(other, Book):
return NotImplemented
return (self.title, self.author, self.pages) == (other.title, other.author, other.pages)With a dataclass:
from dataclasses import dataclass
@dataclass
class Book:
title: str
author: str
pages: int = 0The two versions behave the same:
b = Book("Dune", "Frank Herbert", 412)
print(b) # Book(title='Dune', author='Frank Herbert', pages=412)
b == Book("Dune", "Frank Herbert", 412) # True
b.pages += 10 # normal attributes@dataclass is a decorator: it takes the class you wrote and adds the generated methods to it. The fields are the annotated names in the class body (name: type), in order. The type hints aren’t checked at run time (Type hints and docstrings), but they’re required to declare a field.
Defaults
@dataclass
class Product:
name: str
price: float
quantity: int = 0
on_sale: bool = FalseAs with function parameters, fields with defaults must come after fields without.
Mutable defaults: field(default_factory=…)
You can’t write tags: list[str] = [] — dataclasses refuse, with ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory, protecting you from the shared-list trap. Use field with a factory — a function called to make a fresh default for each object:
from dataclasses import dataclass, field
@dataclass
class Book:
title: str
tags: list[str] = field(default_factory=list)
a = Book("Dune")
b = Book("Emma")
a.tags.append("sci-fi")
b.tags # [] — each book has its own listMethods work as usual
A dataclass is a normal class; add any methods and properties you like:
@dataclass
class Rectangle:
width: float
height: float
@property
def area(self) -> float:
return self.width * self.height
def scaled(self, factor: float) -> "Rectangle":
return Rectangle(self.width * factor, self.height * factor)Validation: post_init
The generated __init__ just stores values. To check or compute something afterwards, define __post_init__:
@dataclass
class Expense:
amount: float
category: str
def __post_init__(self):
if self.amount <= 0:
raise ValueError("amount must be positive")
self.category = self.category.strip().lower()Options
order=True: sorting
@dataclass(order=True)
class Version:
major: int
minor: int
patch: int
sorted([Version(1, 10, 0), Version(1, 2, 3)])
# [Version(major=1, minor=2, patch=3), Version(major=1, minor=10, patch=0)]Objects compare like tuples of their fields, in order. To sort by something else, use a key function as usual.
frozen=True: read-only objects
@dataclass(frozen=True)
class Point:
x: float
y: float
p = Point(3, 4)
p.x = 10 # dataclasses.FrozenInstanceError: cannot assign to field 'x'Frozen objects can’t be changed by accident and can be used as dictionary keys or set members. To “change” one, make a modified copy: dataclasses.replace(p, x=10).
Other handy options
@dataclass(slots=True)— uses less memory and makes typos in attribute names an error.@dataclass(kw_only=True)— every field must be passed by keyword:Product(name="Pen", price=1.5).field(repr=False)— hide a field (like a password) from the repr.
Converting to dicts
from dataclasses import asdict
asdict(Book("Dune", ["sci-fi"])) # {'title': 'Dune', 'tags': ['sci-fi']}That’s ideal for saving to JSON: json.dump(asdict(book), f). To load, unpack the dict back into the class: Book(**data).
Dataclass or regular class?
- Dataclass: the object is mainly data — records, settings, results, messages. Most “nouns” in a program.
- Regular class: complex behaviour, careful control over how the object is created or changes, or nothing much to compare or print.
You can always start with a dataclass and add methods as the class grows.
Remember: list the fields with type hints, add
@dataclass, and get__init__,__repr__and__eq__for free. Usedefault_factoryfor lists and dicts,frozen=Truefor read-only,order=Truefor sorting.
A library catalogue
Write a @dataclass Book with title, author, year and tags (a list that defaults to empty — use field(default_factory=list)), plus a method age(current_year) returning how old the book is. Add __post_init__ that raises ValueError if the year is in the future (after 2026). Then write a frozen, ordered dataclass Isbn with a single code string. Create three books, print one (to see the automatic repr), compare two books with ==, sort the books by year with a key, and show that changing an Isbn raises an error and that a future year is rejected.
from dataclasses import dataclass, field, FrozenInstanceError
# Book dataclass
# Isbn dataclass (frozen, ordered)from dataclasses import dataclass, field, FrozenInstanceError
@dataclass
class Book:
title: str
author: str
year: int
tags: list[str] = field(default_factory=list)
def __post_init__(self):
if self.year > 2026:
raise ValueError(f"year {self.year} is in the future")
def age(self, current_year: int) -> int:
return current_year - self.year
@dataclass(frozen=True, order=True)
class Isbn:
code: str
books = [
Book("Dune", "Frank Herbert", 1965, ["sci-fi"]),
Book("Educated", "Tara Westover", 2018),
Book("Emma", "Jane Austen", 1815, ["classic", "romance"]),
]
print(books[1])
print(books[1] == Book("Educated", "Tara Westover", 2018)) # True
print([b.title for b in sorted(books, key=lambda b: b.year)]) # ['Emma', 'Dune', 'Educated']
print(books[0].age(2026)) # 61
print(sorted([Isbn("978-3"), Isbn("978-1")]))
isbn = Isbn("978-0-14-143951-8")
try:
isbn.code = "changed"
except FrozenInstanceError:
print("Isbn is read-only")
try:
Book("Future", "Nobody", 2030)
except ValueError as error:
print("Error:", error)Summary
@dataclassgenerates__init__,__repr__and__eq__from the annotated fields in the class body.- Fields with defaults must come after fields without; use
field(default_factory=list)for mutable defaults. @dataclass(frozen=True)makes objects read-only (and hashable);order=Trueadds<,>and sorting.__post_init__runs after the generated__init__— the place to validate or compute values.- Dataclasses are normal classes: add methods and properties as usual.