Use field when a dataclass attribute needs explicit configuration, particularly a safe default for a mutable value such as a list. Dataclass attributes must have type annotations so the decorator can discover them as fields and use them when generating methods such as __init__ and __repr__. section 9.2.2 section 9.2.6
Keep these field behaviors in mind:
- A field with a regular default can be omitted during construction; the generated initializer supplies that value. section 9.2.2
- Fields without defaults must precede fields with defaults, including across a dataclass inheritance hierarchy. section 9.2.2 section 9.2.4
- Use the dataclass module's field function when the default concerns a mutable field rather than treating it like an ordinary function default. section 9.2.6
A defaulted dataclass field
In a Bill dataclass, the annotated tip_amount field receives a default of 0, so Bill(5, 60.5, "John") is valid and produces Bill(table_number=5, meal_amount=60.5, served_by='John', tip_amount=0). section 9.2.2
print(Bill.__annotations__)
# output: {'table_number': <class 'int'>, 'meal_amount':
<class 'float'>, 'served_by': <class 'str'>,
'tip_amount': <class 'float'>}
Inspect the annotations that the dataclass decorator uses to locate fields. section 9.2.2
