Sub topic 1
The boilerplate problem with plain classes
Prerequisites
This chapter assumes you can already:
- Define a class and create instances in Python.
- Read and write the special methods
__init__,__repr__and__eq__. - Use type annotation syntax such as
x: int. - Tell mutable objects (lists, dicts) from immutable ones (tuples, strings).
You need Python 3.7 or newer. Later chapters use features that need 3.10.
A class that only holds data
Many classes exist to hold a few values together: a point, a user record, a configuration. For these you usually want three behaviors:
- A constructor that stores each argument.
- A readable
repr, so printing shows the values. - Equality based on values, not identity.
Python gives you none of these by default. You write them yourself:
class Point:
def __init__(self, x, y=0.0):
self.x = x
self.y = y
def __repr__(self):
return f"Point(x={self.x!r}, y={self.y!r})"
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
p = Point(1.5)
print(p) # Point(x=1.5, y=0.0)
print(p == Point(1.5, 0.0)) # TrueThis is 13 lines for a class with two fields. Each field name appears four times in __init__, __repr__ and __eq__, and again whenever you read the class.
What goes wrong
The repetition is tedious, and it also causes bugs. Common errors:
- Forgetting
__repr__. Printing an instance shows something like<__main__.Point object at 0x7f...>, which is useless when debugging. - Forgetting
__eq__. Without it,==compares identity. Two points with the same values are not equal:
class RawPoint:
def __init__(self, x, y=0.0):
self.x = x
self.y = y
print(RawPoint(1, 2) == RawPoint(1, 2)) # False- Adding a field in only some places. If you add
zto__init__but not to__repr__or__eq__, two points that differ only inzcompare equal. Nothing raises an error. - Losing hashability. Defining
__eq__without__hash__sets__hash__toNone. Your instances then cannot be dict keys or set members, and the error appears far from its cause.
None of these mistakes is hard to avoid in one class. They add up across dozens of classes, each of which must be kept in sync by hand.
The dataclass alternative
The dataclasses module (standard library, Python 3.7+) removes this duplication. You list the fields once, as annotated class attributes. The @dataclass decorator reads that list and generates the methods:
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float = 0.0
p = Point(1.5)
print(p) # Point(x=1.5, y=0.0)
print(p == Point(1.5, 0.0)) # TrueThe behavior matches the hand-written class, in 5 lines. Adding a field is a one-line change, and __init__, __repr__ and __eq__ update with it.
The decorator is not magic. It builds ordinary methods and attaches them to your class when the class is defined. After that, the class behaves like one you wrote by hand. The following chapters cover how it reads fields, which options change the output, and where the limits are.
When the boilerplate is not the problem
Dataclasses fit classes whose main job is to store values. If a class is mostly behavior, with little state and no need for value equality, a plain class is clearer. The final chapter of this tutorial compares dataclasses with NamedTuple, plain classes and third-party libraries.
Exercise
A teammate adds a field z to a hand-written class's __init__ but forgets to update __eq__. What bug does this cause, and how does a dataclass avoid it?
Show answer
Two instances that differ only in z compare equal, because __eq__ ignores z, and no error is raised. A dataclass builds __eq__ (and __init__ and __repr__) from its field list, so adding z: float as a field includes it in all three methods automatically.