Python — From Basics to Advanced · Dataclasses and Enums
field() and Special Dataclass Fields
Dataclasses and Enums
Introduction
The field() function from the dataclasses module fine-tunes individual dataclass fields. The most common parameters: default_factory (for mutable defaults like list/dict/set), init=False (field excluded from __init__), repr=False (field hidden in __repr__ — e.g. passwords, large buffers), compare=False (field excluded from __eq__ and __lt__), hash=False (field excluded from __hash__), metadata=... (a mapping for external tooling, ignored by @dataclass itself). Special annotations: ClassVar[T] — a class attribute, not an instance field; InitVar[T] — an argument forwarded to __post_init__ but never stored as a field. These tools give precise control over what the dataclass actually generates.