Dataclasses
Last updated
Most of the classes so far have been mostly data: a title, an author, a number of copies. Writing __init__, __repr__ and __eq__ for each one is the same work every time. In this lesson Python writes them for you. You'll turn a class into a dataclass, see what it wrote, give fields defaults, read the error a list default gets you, sort with order=True, and decide when to write a class by hand.
By the end of this lesson you can
- Write a dataclass, and say which methods
@dataclasswrites for you - Give fields defaults, using
field(default_factory=list)for a list - Make dataclass objects sortable with
order=True, and leave a field out of comparisons - Choose between a dataclass and a class written by hand
@dataclass
@dataclass is a decorator, like @classmethod in lesson 3.4, but it goes above the whole class. It reads the fields you list and writes the usual methods for you.
Each field is a name and a type, the type hints from lesson 2.11: title: str. There's no __init__ and no self anywhere, yet Book("Dune", "Frank Herbert", 1965) works.
You got three things for free: an __init__ that takes the fields in order, or by name (line 15), a __repr__ that shows every field (lines 12 and 16), and an __eq__ that compares every field (line 14).
As in lesson 2.11, the types are notes for people and for mypy. Python doesn't check them. Book("Dune", "Frank Herbert", "soon") runs without complaint.
What it writes for you
Here's what @dataclass wrote for step 1's Book, written out by hand. That's about a dozen lines you no longer type, keep in step with the fields, or get wrong.
class Book: def __init__(self, title, author, year): self.title = title self.author = author self.year = year def __repr__(self): return f"Book(title={self.title!r}, author={self.author!r}, year={self.year!r})" def __eq__(self, other): if other.__class__ is not self.__class__: return NotImplemented return (self.title, self.author, self.year) == (other.title, other.author, other.year)
A dataclass is still an ordinary class. You can add your own methods, and they use self as always.
Lines 23 and 24 look inside the class. @dataclass wrote __eq__, but not __lt__, and it set __hash__ to None, as lesson 3.5 said Python does for any class with __eq__.
| Method | Written? | What it does |
|---|---|---|
__init__ | Always | One parameter for each field, in order |
__repr__ | Always | Book(title='Dune', …). print uses it too, unless you write __str__ |
__eq__ | Always | Equal when every field is equal |
__lt__ and the other orderings | Only with order=True | Compares the fields in order, like tuples |
__hash__ | No: it’s set to None | So objects can’t go in a set. Lesson 4.4 shows frozen=True, which makes one |
Defaults
A field can have a default, written like a default in a def (lesson 1.8): limit: int = 5. Leave it out when making a member, and they get 5.
A list is different. Each member needs their own list of loans, so the default is field(default_factory=list). field comes from dataclasses too. default_factory takes a function, here list, and calls it for every new member to make a fresh, empty list.
Sam's book on line 13 is only in Sam's list. Ana's is empty.
Fields with defaults must come after fields without. Move name: str below limit and run it: Python stops with non-default argument 'name' follows default argument 'limit', the same rule as in a def.
A list as a default
Why not just write loans: list[str] = []? Try it.
ValueError: mutable default <class 'list'> for field loans is not allowed: use default_factory. That one list would be made once and shared by every member: the trap from lessons 2.5 and 3.4. A plain class lets you fall into it. A dataclass stops you the moment Python reads the class, before any member exists.
Change line 1 to import field as well, and line 7 to loans: list[str] = field(default_factory=list), then run it.
order=True
@dataclass(order=True) also writes __lt__ and the other orderings. Objects compare field by field, from the top, like tuples. So the order you list the fields in is the order they sort in. Here author comes first, so books sort by author, then title.
copies shouldn't decide either order or equality: two cards for Emma are the same book, however many copies are on the shelf. field(compare=False) leaves a field out of == and <.
Swap the author and title lines in the class, and fix the values on lines 12 to 14 to match. The books now sort by title.
When to write the class by hand
A dataclass is the usual choice for a class that's mostly data. Write it by hand when the class is mostly behaviour, or when what @dataclass writes isn't what you want.
| If the class… | Use |
|---|---|
| It mostly holds data | A dataclass |
Its __init__ just stores what it’s given | A dataclass |
| Equal should mean "every field is equal" | A dataclass, using compare=False for fields that don’t count |
| It’s made from something else, like a CSV row | Either: add a @classmethod, as in lesson 3.4 |
Its __init__ must check or work out values | Either: a dataclass can do this in __post_init__, but a short __init__ by hand can be clearer |
| It’s mostly behaviour, like a menu or a report | By hand |
In other languages (optional): most languages now have a short way to write a class that's mostly data.
| Language | How |
|---|---|
| Python | @dataclass on a class with typed fields |
| Java | A record: record Book(String title, String author, int year) {}. Its fields can’t change |
| C# | A record, much like Java’s |
| Rust | A struct with #[derive(Debug, PartialEq, PartialOrd)]: see Simple Rust 4.4 |
Check what you learned
Three questions. Pick or type an answer, then check it.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- The Python Standard Library: dataclasses
- dataclasses: the dataclass decorator and its parameters: init, repr, eq, order and what each one writes
- dataclasses: Mutable default values: why a list default is refused
- dataclasses: field: default_factory and compare
- PEP 557: Data Classes
- The Java Language Specification: 8.10 Record Classes: Java records
- The Rust Programming Language: Derivable Traits: what #[derive] writes for a Rust struct