Sub topic 3
Fields, annotations and defaults
This chapter assumes you can write a basic Python class, know what __init__ and __repr__ do, can read type annotations such as x: int, and have seen the @dataclass decorator generate methods. It covers how a dataclass decides which names are fields, and how defaults change the generated __init__.
What counts as a field
The decorator looks at the class body's __annotations__. A name becomes a field only if it has an annotation. A plain assignment without one is an ordinary class attribute and is ignored.
from dataclasses import dataclass, fields
@dataclass
class Item:
name: str
price: float = 1.0
category = "general" # no annotation, so not a field
print([f.name for f in fields(Item)]) # ['name', 'price']
print(Item("pen")) # Item(name='pen', price=1.0)
print(Item.category) # generalThe annotation is not enforced. Python stores it, and the dataclass uses it only to find the field and record its type. Item("pen", "cheap") runs without error, and price holds a string.
Two annotations get special treatment. ClassVar[...] marks a class-level attribute that is not a field. InitVar[...] marks an init-only argument, which a later chapter covers.
from dataclasses import dataclass
from typing import ClassVar
@dataclass
class Counter:
count: int = 0
instances: ClassVar[int] = 0 # shared by the class, not a field
print(Counter()) # Counter(count=0)How defaults shape `__init__`
Fields appear as __init__ parameters in the order you declare them. A field with a default value becomes an optional parameter. Python does not allow a required parameter after an optional one, so the dataclass enforces the same rule.
from dataclasses import dataclass
@dataclass
class Broken:
label: str = "none"
value: int # TypeError at class creationThis raises TypeError: non-default argument 'value' follows default argument. The fix is to put required fields first.
from dataclasses import dataclass
@dataclass
class Reading:
sensor: str
value: float
unit: str = "C"
print(Reading("t1", 21.5)) # Reading(sensor='t1', value=21.5, unit='C')
print(Reading("t1", 21.5, "F"))The error appears when the class is defined, not when you create an instance. You find the mistake as soon as the module is imported.
Defaults are evaluated once
The default expression runs once, when the class is created. Every instance that omits the argument receives that same object. For immutable values such as numbers, strings, tuples and None, sharing is harmless. For a mutable value it is a bug, because one instance can change what the others see.
from dataclasses import dataclass
try:
@dataclass
class Basket:
items: list[str] = []
except ValueError as e:
print(e)The dataclass refuses this definition and raises ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory. The check rejects list, dict and set defaults. It does not catch every mutable object. The next chapter shows the safe pattern.
Annotations are required, but their content is flexible
Any annotation works, including Any, strings, and generic types. When a field has no useful type, use typing.Any.
from dataclasses import dataclass
from typing import Any
@dataclass
class Event:
name: str
payload: Any = None
print(Event("click")) # Event(name='click', payload=None)Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Attribute missing from `repr` and `__init__` | No annotation, so not a field | Add `: type` |
| `TypeError: non-default argument ... follows default argument` | Required field after a defaulted one | Reorder fields |
| `ValueError: mutable default` | `list`, `dict` or `set` as default | Use `default_factory` |
| Wrong type accepted silently | Annotations are not checked at runtime | Validate in `__post_init__` or use a type checker |
Exercise
What happens with this code, and how do you fix it? @dataclass class Order: status: str = "new" order_id: int
Show answer
It raises TypeError when the class is defined, because orderid has no default but follows status, which has one. Move orderid before status: order_id: int, then status: str = "new".
Exercise
A class has tag = "x" in its body with no annotation. Is tag an __init__ parameter, and does it appear in the repr?
Show answer
No to both. Without an annotation it is a plain class attribute, not a field, so the generated __init__, __repr__ and __eq__ ignore it.