Sub topic 3
Fields, annotations and defaults
This chapter covers what counts as a field in a dataclass, how defaults work, and why field order matters. It assumes you can define a Python class, you know what __init__ and __repr__ do, and you can read annotations such as x: int. The examples run on Python 3.7 or newer.
What makes something a field
A dataclass field is a name in the class body that has a type annotation. The @dataclass decorator reads the class's __annotations__ mapping, in the order the names were written, and turns each entry into a field. A name with no annotation is not a field, even if it has a value.
from dataclasses import dataclass, fields
@dataclass
class Item:
name: str
price: float = 0.0
tax_rate = 0.2 # no annotation: a plain class attribute, not a field
print([f.name for f in fields(Item)]) # ['name', 'price']
print(Item("pen", 1.5)) # Item(name='pen', price=1.5)
print(Item.tax_rate) # 0.2tax_rate is still readable as Item.tax_rate, but the generated __init__ does not accept it, __repr__ does not show it, and __eq__ ignores it. This is a common source of silent bugs. If you forget the annotation on a field, nothing fails at definition time. The value is simply left out of the generated methods.
The decorator decides how to treat each name in the class body like this:
Annotations are labels, not checks
The annotation tells the decorator that a field exists. Python does not check the type. Dataclasses never validate or convert values against the annotation.
from dataclasses import dataclass
@dataclass
class Counter:
count: int = 0
c = Counter("many")
print(c) # Counter(count='many')Static checkers such as mypy and pyright do read the annotations and would flag this call, but the interpreter accepts it. If you need runtime checks, write them yourself in __post_init__ (covered in a later chapter) or use a library built for validation.
The annotation can be any valid expression. int, list[str], Optional[int] and "Node" (a forward reference as a string) all work, because the decorator mostly does not interpret them. Two cases are the exception: typing.ClassVar and dataclasses.InitVar change how a field is treated. Both appear later in this chapter or in the InitVar chapter.
If a module starts with from __future__ import annotations, every annotation is stored as a string. Dataclasses still work. The decorator recognizes ClassVar and InitVar in the string form by inspecting its text, which is enough for the usual spellings (ClassVar[int], typing.ClassVar[int]).
Required fields and defaults
A field with no assigned value is required. A field with a value after = is optional, and that value is its default.
import inspect
from dataclasses import dataclass
@dataclass
class Item:
name: str
price: float = 0.0
print(inspect.signature(Item)) # (name: str, price: float = 0.0) -> None
print(Item("pen")) # Item(name='pen', price=0.0)
print(Item("pen", 2.5)) # Item(name='pen', price=2.5)
print(Item(price=3.0, name="cup")) # Item(name='cup', price=3.0)The generated __init__ has one parameter per field, in the same order as the fields in the class body. Callers may pass arguments by position or by keyword. Omitting name raises the same TypeError that a hand-written __init__ would raise for a missing argument.
The field order also controls the other generated methods. __repr__ prints fields in order. __eq__ compares the fields as tuples, in order. With order=True, the comparison methods use the same tuple order. Reordering fields can therefore change behavior beyond the constructor signature.
Required fields must come before defaulted fields
The generated __init__ is an ordinary function, and Python does not allow a parameter without a default to follow one that has a default. The decorator checks this when the class is defined.
from dataclasses import dataclass
try:
@dataclass
class Bad:
a: int = 0
b: int
except TypeError as exc:
print(type(exc).__name__) # TypeErrorThe error appears at class creation, not when you first call the class. The message names the offending field. The fix is to reorder the fields so that required ones come first:
from dataclasses import dataclass
@dataclass
class Good:
b: int
a: int = 0
print(Good(5)) # Good(b=5, a=0)If you cannot reorder, because the order is part of a public API or comes from a base class, the chapters on inheritance and kw_only show other ways out.
What the default value actually is
For a simple default, the decorator keeps the value as an ordinary class attribute. Each instance gets its own attribute only after assignment. That means two lookups are possible:
from dataclasses import dataclass
@dataclass
class Settings:
retries: int = 3
s = Settings()
print(Settings.retries) # 3 (class attribute)
print(s.retries) # 3 (set by the generated __init__)
s.retries = 5
print(s.retries) # 5
print(Settings.retries) # 3 (unchanged)The generated __init__ assigns self.retries = retries every time, so each instance has its own value in its instance dictionary. The class attribute only serves as the default that __init__ uses when the caller passes nothing.
This works well for immutable defaults such as numbers, strings, tuples, None and frozenset. Immutable values cannot be changed in place, so sharing one object across all instances is harmless.
Mutable defaults are rejected
A default that can be changed in place, such as a list, would be one shared object used by every instance created without that argument. In an ordinary function this is the well-known mutable default argument bug. Dataclasses refuse to let it happen:
from dataclasses import dataclass
try:
@dataclass
class Basket:
items: list[str] = []
except ValueError as exc:
print(type(exc).__name__) # ValueErrorThe error is raised when the class is defined. Which defaults are rejected depends on the Python version. Before 3.11, the decorator rejects only list, dict and set instances. From 3.11 on, it rejects any default whose class is unhashable. That also catches custom classes and ordinary dataclass instances, which define __eq__ without __hash__. The next chapter explains the standard fix, field(default_factory=...), which builds a fresh object for each instance.
Fields that are not fields: ClassVar
Sometimes a value belongs to the class, not to each instance. Annotate it with typing.ClassVar and the decorator skips it:
from dataclasses import dataclass, fields
from typing import ClassVar
@dataclass
class Employee:
name: str
salary: float = 0.0
company: ClassVar[str] = "Acme"
e = Employee("Ana", 5000)
print(e) # Employee(name='Ana', salary=5000)
print(Employee.company) # Acme
print([f.name for f in fields(e)]) # ['name', 'salary']A ClassVar can be mutable, because it is not a field and the mutable default check does not apply to it. Because it is shared on purpose, mutating it affects every instance, as with any class attribute.
Compare the two ways of declaring a non-field:
| Declaration | In `__init__` | In `__repr__` and `__eq__` | Use for |
|---|---|---|---|
| `tax_rate = 0.2` | No | No | Constants. Easy to write by accident. |
| `tax_rate: ClassVar[float] = 0.2` | No | No | Constants, with the intent visible to readers and type checkers. |
| `tax_rate: float = 0.2` | Yes | Yes | Per-instance data with a default. |
The first two behave identically at runtime. The ClassVar version is preferable because a type checker will then know the attribute is not an instance field, and a reader will see that omitting the annotation was deliberate.
Fields with no annotation and an existing value
One more edge case: a name that has a value but no annotation is never turned into a field, even when it looks like one. The decorator only walks __annotations__. So the class below has a single field:
from dataclasses import dataclass, fields
@dataclass
class Point:
x: int
y = 0
print([f.name for f in fields(Point)]) # ['x']
print(Point(1)) # Point(x=1)If you want y to be a field, write y: int = 0. When a dataclass seems to ignore one of your attributes, check for a missing annotation first.
Checking what the decorator found
dataclasses.fields() returns the list of Field objects for a class or an instance. Each one records its name, type, and default. It is the quickest way to confirm what the decorator saw:
from dataclasses import dataclass, fields, MISSING
@dataclass
class Item:
name: str
price: float = 0.0
for f in fields(Item):
required = f.default is MISSING
print(f.name, f.type, "required" if required else f"default={f.default}")
# name <class 'str'> required
# price <class 'float'> default=0.0MISSING is a sentinel object that means "no default was given". Use it for comparisons instead of None, because None is a legitimate default value. With from __future__ import annotations, f.type is the string 'str' rather than the class.
Summary of the rules
- A name is a field only if it is annotated and the annotation is not
ClassVar(orInitVar, which is covered later). - Field order in the class body sets the order of
__init__parameters,__repr__output and comparison tuples. - Fields without defaults must come before fields with defaults.
- Annotations are not enforced at runtime.
- Simple defaults are stored as class attributes and copied into each instance by
__init__. - Mutable defaults raise
ValueErrorwhen the class is defined.
Exercise
Predict the output of this code, then explain why. How many fields does Order have, and what happens on the last line?
from dataclasses import dataclass, fields
from typing import ClassVar
@dataclass
class Order:
id: int
quantity = 1
note: str = ""
currency: ClassVar[str] = "EUR"
print([f.name for f in fields(Order)])
print(Order(7, "rush"))
Order(7, 3)
Show answer
The first line prints ['id', 'note']. Order has two fields. quantity has no annotation, so it is a plain class attribute. currency is a ClassVar, so it is also skipped. The second line prints Order(id=7, note='rush'). The positional arguments map to id and note in order. The last line, Order(7, 3), does not raise an error, because the annotation str is not enforced and 3 is stored in note. A type checker would flag it, but Python runs it and the result is Order(id=7, note=3), which is not printed here.
Exercise
This class fails when it is defined. Name the error, explain the cause, and write a corrected version that keeps currency defaulting to "USD".
from dataclasses import dataclass
@dataclass
class Price:
currency: str = "USD"
amount: float
Show answer
It raises a TypeError, because the required field amount follows the defaulted field currency. The generated _init_ cannot have a parameter without a default after one with a default. Reorder the fields so the required one comes first:
@dataclass
class Price:
amount: float
currency: str = "USD"
Price(9.99) now gives Price(amount=9.99, currency='USD').