Classes and objects · lesson 6 of 7
Parts in this lesson
A@dataclasswrites the methods for you
Btitle: str2.11: a field, with its type
Climit: int = 5a default
Dfield(default_factory=list)a new list for each
E@dataclass(order=True)sorts by its fields

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 @dataclass writes 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.

Step 1 code main.py
Edit the code, then run it again

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.

Step 2 code main.py
Edit the code, then run it again

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__.

What @dataclass writes
MethodWritten?What it does
__init__AlwaysOne parameter for each field, in order
__repr__AlwaysBook(title='Dune', …). print uses it too, unless you write __str__
__eq__AlwaysEqual when every field is equal
__lt__ and the other orderingsOnly with order=TrueCompares the fields in order, like tuples
__hash__No: it’s set to NoneSo 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.

Step 3 code main.py
Edit the code, then run it again

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.

Step 4 code main.py
Edit the code, then run it again

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 <.

Step 5 code main.py
Edit the code, then run it again

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.

Dataclass or by hand
If the class…Use
It mostly holds dataA dataclass
Its __init__ just stores what it’s givenA 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 rowEither: add a @classmethod, as in lesson 3.4
Its __init__ must check or work out valuesEither: 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 reportBy hand

In other languages (optional): most languages now have a short way to write a class that's mostly data.

A data-holding class
LanguageHow
Python@dataclass on a class with typed fields
JavaA record: record Book(String title, String author, int year) {}. Its fields can’t change
C#A record, much like Java’s
RustA 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.

What does this program print?
from dataclasses import dataclass


@dataclass(order=True)
class Loan:
    days: int
    title: str


loans = [Loan(21, "Dune"), Loan(7, "Emma"), Loan(14, "Beloved")]
print(min(loans).title)
Which method does a plain @dataclass NOT write?
How do you give each Member its own empty list of loans in a dataclass?

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.

All sources for Simple Python