Python 3.7+dataclassesfunction
dataclasses.field()
field
The field() function sets extra properties of a field: its default value, its factory, and whether it takes part in repr/compare/init.
Syntax
dataclasses.field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, compare=True, init=True)
field() exists mainly because of mutable defaults: a value written in the class body would be shared by every instance, so dataclass raises ValueError on an unhashable default and demands default_factory. The catch is that the check keys on hashability — your own mutable class with a normal __hash__ slips through as default= and is silently shared by all instances. compare=False and repr=False are handy for bookkeeping fields such as caches or ids that should not affect equality or output.
Examples
from dataclasses import dataclass, field
@dataclass
class Bag:
items: list = field(default_factory=list)
_id: int = field(default=0, repr=False, compare=False)
b = Bag()
b.items.append(1)
repr(b) # → 'Bag(items=[1])'
Bag() == Bag() # → True
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy