Sub topic 2
Your first dataclass: what @dataclass generates
This chapter assumes you can write a plain Python class with __init__, __repr__ and __eq__, that you can read annotations such as x: float, and that you run Python 3.7 or newer. By the end you will know which methods @dataclass writes for you and which it leaves out.
From annotated fields to a working class
A dataclass is an ordinary class with one extra step. You list fields as annotated names in the class body, and the @dataclass decorator reads them and adds methods to the class.
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)) # TruePoint(1.5) works because the decorator generated an __init__(self, x, y=0.0). The printed form comes from a generated __repr__. The == result comes from a generated __eq__.
The decorator modifies the class in place and returns it. No new class is created and no base class is added.
The generated methods
With default settings, @dataclass produces the following.
| Method | Behavior | Controlled by |
|---|---|---|
| `__init__` | One parameter per field, in declaration order, with the declared defaults | `init=True` |
| `__repr__` | `ClassName(field=value, ...)` | `repr=True` |
| `__eq__` | Compares fields as tuples, only between instances of the same class | `eq=True` |
| `__hash__` | Set to `None`, so instances are unhashable | `eq` and `frozen` |
| `__lt__`, `__le__`, `__gt__`, `__ge__` | Not generated | `order=False` |
Later chapters cover order and frozen. For now, remember that equality comes by default and ordering does not.
Only annotated names become fields
The decorator looks at annotations, not at assignments. A name without an annotation is a plain class attribute and is ignored.
from dataclasses import dataclass
@dataclass
class Tag:
name: str
count = 0 # no annotation, so this is not a field
t = Tag("python")
print(t) # Tag(name='python')Passing a second argument to Tag would raise a TypeError, because __init__ only accepts name. This is a common source of confusion. If a field seems to be missing from __repr__ or __init__, check its annotation first.
Equality and hashing in practice
Generated __eq__ compares the fields as tuples, but it refuses to compare against other types.
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float = 0.0
print(Point(1, 2) == Point(1, 2)) # True
print(Point(1, 2) == (1, 2)) # False
try:
hash(Point(1, 2))
except TypeError as e:
print(e) # unhashable type: 'Point'The tuple comparison is False because __eq__ returns NotImplemented for a different class, and Python then falls back to identity. The hash call fails because a class that defines value-based equality on mutable fields should not be hashable. If you need a dictionary key or set member, the frozen option in a later chapter solves this.
Field order and required fields
Parameters of the generated __init__ follow the order of the fields in the class body. Python does not allow a required parameter after one with a default, and the decorator enforces the same rule.
from dataclasses import dataclass
try:
@dataclass
class Broken:
a: int = 0
b: int # no default after a default
except TypeError as e:
print(e) # non-default argument 'b' follows default argumentThe exact wording of the message varies slightly across Python versions. Put required fields first, or use keyword-only fields, which a later chapter covers.
Exercise
Exercise
A class is declared as @dataclass class Item: with the body name: str, qty: int = 1 and unit = "kg". What does print(Item("rice")) show, and why is unit absent?
Show answer
It prints Item(name='rice', qty=1). The name unit has no annotation, so the decorator treats it as an ordinary class attribute rather than a field, and it appears in neither __init__ nor __repr__.