← All lessons
Python advanced · Lesson 4 of 11

Special methods and dataclasses

Python's built-in operations are hooks into special methods. len(x) calls x.__len__(), a == b calls a.__eq__(b), a + b calls a.__add__(b), a < b calls a.__lt__(b), and for item in x uses x.__iter__(). Define them on your class and your objects work with Python's own syntax. This is how the standard library's types do it too.

There are two ways an object turns into text. __str__ is the friendly version for users, used by print(). __repr__ is the precise version for programmers, used in the interactive shell, in lists and in debuggers; ideally it looks like the code that would recreate the object. If you only write one, write __repr__: print() falls back to it.

class Money:
    def __init__(self, cents):
        self.cents = cents

    def __repr__(self):
        return f"Money({self.cents})"

    def __str__(self):
        return f"${self.cents / 100:.2f}"

    def __add__(self, other):
        return Money(self.cents + other.cents)

    def __eq__(self, other):
        return isinstance(other, Money) and self.cents == other.cents

    def __lt__(self, other):
        return self.cents < other.cents

prices = [Money(250), Money(99)]
print(prices)
print(prices[0] + prices[1])
print(Money(5) == Money(5), min(prices))
Prints
[Money(250), Money(99)]
$3.49
True $0.99

Without __eq__, == falls back to is, so two equal-looking objects compare unequal. With __lt__, sorted(), min() and max() work. Return the special value NotImplemented from these methods when the other object is a type you don't handle, and Python will try the other side or raise a clear TypeError.

Writing __init__, __repr__ and __eq__ for every small data class is repetitive, so the dataclasses module writes them for you. Put @dataclass above the class (a line starting with @ is a decorator; a later lesson explains them) and list the attributes with their types.

from dataclasses import dataclass, field

@dataclass
class Item:
    name: str
    price: float
    tags: list[str] = field(default_factory=list)

    def with_tax(self):
        return round(self.price * 1.2, 2)

a = Item("tea", 2.5)
print(a)
print(a == Item("tea", 2.5), a.with_tax())
Prints
Item(name='tea', price=2.5, tags=[])
True 3.0

field(default_factory=list) gives each instance its own new list, avoiding the mutable default trap. @dataclass(frozen=True) makes instances immutable (assigning an attribute raises an error), which also lets them be dict keys and set items; @dataclass(order=True) adds < and friends, comparing the fields in order.

from dataclasses import dataclass

@dataclass(frozen=True, order=True)
class Version:
    major: int
    minor: int

print(sorted([Version(2, 0), Version(1, 9), Version(1, 10)]))
print(len({Version(1, 0), Version(1, 0)}))
Prints
[Version(major=1, minor=9), Version(major=1, minor=10), Version(major=2, minor=0)]
1

Reach for a dataclass whenever a class is mainly a bundle of named data. For values with no behaviour at all, typing.NamedTuple is a lighter option.

Practice

What does this print?

class Team:
    def __init__(self, members):
        self.members = members
    def __len__(self):
        return len(self.members)

print(len(Team(["a", "b", "c"])))
More info

Quick reference

__repr__ / __str__Text for programmers (lists, shell, debugger) / for users (print).
__eq__ __lt__ __add__ __len__Hooks for ==, <, + and len().
NotImplementedReturn it from an operator method for types you don't handle.
@dataclassWrites __init__, __repr__ and __eq__ from the listed fields.
field(default_factory=list)A fresh mutable default for each instance.
frozen=True / order=TrueImmutable and hashable / comparable with <.

Related courses