Dataclasses

Topic 4 of 4 in Classes and objects6 min readBeginnerFree course

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:

Python
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:

Python
from dataclasses import dataclass

@dataclass
class Book:
    title: str
    author: str
    pages: int = 0

What @dataclass writes for you. You write: from dataclasses import dataclass, @dataclass, class Book: with title: str, author: str and pages: int = 0. Generated for you: def init(self, title, author, pages=0) assigning self.title = title and so on; def repr(self) returning “Book(title=…, …)”; and def eq(self, other). Options: @dataclass(frozen=True) makes objects read-only; order=True adds < and > comparisons. Use dataclasses for objects that mainly hold data.

The two versions behave the same:

Python
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

Python
@dataclass
class Product:
    name: str
    price: float
    quantity: int = 0
    on_sale: bool = False

As 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:

Python
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 list

Methods work as usual

A dataclass is a normal class; add any methods and properties you like:

Python
@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__:

Python
@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

Python
@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

Python
@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

Python
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. Use default_factory for lists and dicts, frozen=True for read-only, order=True for sorting.

Exercise

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.

Python
from dataclasses import dataclass, field, FrozenInstanceError


# Book dataclass


# Isbn dataclass (frozen, ordered)

Summary

  • @dataclass generates __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=True adds <, > 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.