Sub topic 2
Your first dataclass: what @dataclass generates
This chapter assumes you can write a Python class with __init__, __repr__ and __eq__, that you can read annotations such as x: int, and that you run Python 3.7 or newer. A few items marked below need 3.10. By the end you will know exactly which methods @dataclass adds, when it adds them, and where its defaults can surprise you.
The idea in one example
A dataclass is an ordinary class with a decorator applied. The decorator reads the class's annotated attributes and writes methods for you.
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)) # TrueYou wrote no __init__, __repr__ or __eq__, yet all three work. Each annotated name (x, y) becomes a field. A field is a piece of per-instance data that the generated methods know about. A field with a value on the right (y: float = 0.0) has a default.
What you would have written by hand
The decorator produces code equivalent to this class:
class PointByHand:
def __init__(self, x, y=0.0):
self.x = x
self.y = y
def __repr__(self):
return f"{self.__class__.__qualname__}(x={self.x!r}, y={self.y!r})"
def __eq__(self, other):
if other.__class__ is self.__class__:
return (self.x, self.y) == (other.x, other.y)
return NotImplemented
print(PointByHand(1.5)) # PointByHand(x=1.5, y=0.0)
print(PointByHand(1, 2) == PointByHand(1, 2)) # TrueEvery field name appears three or more times in the hand-written version. With ten fields, keeping all those methods in sync is where bugs come from. The dataclass version has one line per field.
Two details of the generated code matter later:
__repr__uses!r, so strings print with quotes and nested objects print their ownrepr.__eq__compares fields as tuples, and only when both objects are of exactly the same class. For anything else it returnsNotImplemented, so Python falls back to identity comparison and the result isFalse.
How the decorator works
@dataclass is a plain function that receives your finished class, modifies it in place, and returns it. It is not a metaclass and it does not create a subclass. (The one exception is slots=True, which has to build a new class. That is covered in a later chapter.)
flowchart TDHere is the real diagram, which follows the same steps in order:
The decorator runs once, at class creation time. Instances created later pay no cost for it, and the generated methods are ordinary methods.
What gets generated
| Method or attribute | Generated when | Behavior |
|---|---|---|
| `__init__` | `init=True` (default) | Takes one parameter per field, in definition order |
| `__repr__` | `repr=True` (default) | `ClassName(field=value, ...)` |
| `__eq__` | `eq=True` (default) | Tuple comparison of fields, same class only |
| `__hash__` | Depends on `eq`, `frozen`, `unsafe_hash` | Set to `None` by default, see below |
| `__lt__`, `__le__`, `__gt__`, `__ge__` | `order=True` | Tuple comparison of fields |
| `__setattr__`, `__delattr__` | `frozen=True` | Raise `FrozenInstanceError` |
| `__match_args__` | `match_args=True` (default, 3.10+) | Enables positional patterns in `match` |
| `__dataclass_fields__` | Always | Dict of field name to `Field` object |
Ordering and frozen instances each get their own chapter. For now, notice that a bare @dataclass gives you exactly three methods you must understand: __init__, __repr__ and __eq__. It also changes __hash__.
Inspecting the result
You can look at what the decorator left on the class:
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float = 0.0
p = Point(1.5)
print(Point.__match_args__) # ('x', 'y')
print(list(Point.__dataclass_fields__)) # ['x', 'y']
print(Point.__hash__) # None
print(Point(1, 2) == (1, 2)) # False: different classes
try:
{p}
except TypeError as e:
print(e) # unhashable type: 'Point'__hash__ is None because of a rule Python itself follows: if you define __eq__ without __hash__, instances become unhashable. Mutable objects that compare by value should not be hashed, because their hash would change when a field changes. The dataclass decorator applies that rule for you when eq=True and frozen=False. That means plain dataclass instances cannot be set members or dictionary keys. The frozen chapter shows how to fix that when you need it.
On Python 3.10 or newer, __match_args__ lets you destructure instances with structural pattern matching:
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float = 0.0
def describe(p: Point) -> str:
match p:
case Point(0, 0):
return "origin"
case Point(x, 0):
return f"on the x axis at {x}"
case Point(x, y):
return f"at ({x}, {y})"
print(describe(Point(0, 0))) # origin
print(describe(Point(4))) # on the x axis at 4
print(describe(Point(1, 2))) # at (1, 2)Only annotated names become fields
The decorator looks at the class's __annotations__. The annotation is what makes a field. The type itself is not checked at runtime. A dataclass will happily accept Point("a", "b"). Annotations are for readers and type checkers, not enforcement.
from dataclasses import dataclass, fields
@dataclass
class Settings:
name: str
retries = 3 # no annotation: a plain class attribute, not a field
s = Settings("job")
print(s) # Settings(name='job')
print([f.name for f in fields(s)]) # ['name']
print(Settings.retries) # 3
try:
Settings("job", 5)
except TypeError as e:
print(e) # Settings.__init__() takes 2 positional arguments but 3 were givenA missing annotation is the most common first mistake. The attribute still exists, but retries is shared by every instance, is not in __init__, and does not appear in repr or ==.
The opposite case is useful. To keep a class-level constant that does look annotated, mark it ClassVar and the decorator skips it:
from dataclasses import dataclass
from typing import ClassVar
@dataclass
class Circle:
radius: float
PI: ClassVar[float] = 3.14159
print(Circle(2)) # Circle(radius=2)
print(Circle.PI) # 3.14159Field order and required arguments
Fields appear in __init__ in the order you declare them. Python does not allow a required parameter after one with a default, and the decorator enforces the same rule when it builds __init__:
from dataclasses import dataclass
try:
@dataclass
class Bad:
a: int = 0
b: int
except TypeError as e:
print(e) # non-default argument 'b' follows default argumentThe error appears when the class is defined, not when you create an instance. Put required fields first, or use kw_only=True (a later chapter).
Your own methods win
The decorator does not overwrite __init__, __repr__ or __eq__ if you define them in the class body. It leaves yours in place without a warning.
from dataclasses import dataclass
@dataclass
class Tag:
label: str
def __repr__(self):
return f"<{self.label}>"
print(Tag("new")) # <new>
print(Tag("a") == Tag("a")) # True: __eq__ was still generatedThis is convenient, but it also means a typo in a method name (__repr_) quietly gives you the generated one. Some options behave differently: order=True raises TypeError if you define a comparison method, and frozen=True raises if you define __setattr__.
Decorator parameters at a glance
@dataclass and @dataclass() are the same. Parameters let you switch behavior on or off:
| Parameter | Default | Effect |
|---|---|---|
| `init` | `True` | Generate `__init__` |
| `repr` | `True` | Generate `__repr__` |
| `eq` | `True` | Generate `__eq__` |
| `order` | `False` | Generate ordering methods (needs `eq=True`) |
| `unsafe_hash` | `False` | Force a generated `__hash__` |
| `frozen` | `False` | Block attribute assignment |
| `match_args` | `True` | Add `__match_args__` (3.10+) |
| `kw_only` | `False` | Make all fields keyword-only (3.10+) |
| `slots` | `False` | Use `__slots__` (3.10+) |
Common errors
- Forgetting the annotation, so the attribute is not a field.
- Putting a required field after a defaulted one, which raises
TypeErrorat class definition. - Using instances as dictionary keys or set members and getting
unhashable type. - Comparing a dataclass to a tuple and expecting
True. Equality requires the same class. - Writing
items: list = []. This raisesValueErrorabout a mutable default, and the next chapters explain the fix.
Exercise
Given the class below, what does Pair(1, 2) == Pair(1, 2) return, what does hash(Pair(1, 2)) do, and why?
@dataclass
class Pair:
a: int
b: int
Show answer
The comparison returns True, because the generated _eq compares (a, b) tuples for two instances of the same class. hash(Pair(1, 2)) raises TypeError: unhashable type: 'Pair'. With eq=True and frozen=False the decorator sets hash_ to None, since a mutable object compared by value should not have a hash that can change.
Exercise
A teammate writes the class below and reports that Config(name="x") prints Config(name='x') but Config(name="x", debug=True) fails. What is wrong, and how do you fix it? @dataclass class Config: name: str debug = False
Show answer
debug has no annotation, so it is a plain class attribute and not a field. It is missing from _init_, so passing debug=True raises TypeError for an unexpected keyword argument. Change the line to debug: bool = False.