liveBook · Manning

Field

As explained in Python How-To

field is a dataclass-module function that describes a data class attribute and its initialization, default, and representation behavior.

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

How Python How-To covers it

How deep it goes
Explains annotation-based discovery and default ordering, but stops short of showing field's call syntax.
Examples
Uses Bill defaults, inherited field ordering, and a mutable-list default challenge.
What it assumes
Assumes classes, type annotations, and function default-argument ordering; teaches annotation-based field discovery.
What you can do after
Apply it via the dataclass module to reason about mutable-field defaults and generated constructor arguments.
How it connects
Connects fields with dataclasses, type annotations, generated initializers, representations, defaults, and inheritance.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.