Sub topic 5
Fine-tuning fields with field()
This chapter assumes you can write a basic @dataclass with annotated fields and defaults. It also assumes you know why mutable defaults need default_factory. Here you will use field() to control how each field takes part in the generated methods.
Why field() exists
A plain default such as visits: int = 0 only sets a value. Sometimes you need more. You may want a field hidden from repr, left out of comparisons, or excluded from __init__. Assigning field(...) as the default lets you set these options for one field at a time.
The main options
| Option | Default | Effect |
|---|---|---|
| `default` | none | A plain default value. |
| `default_factory` | none | A function called with no arguments to build the default. |
| `init` | `True` | If `False`, the field is not an `__init__` parameter. |
| `repr` | `True` | If `False`, the field is left out of `__repr__`. |
| `compare` | `True` | If `False`, the field is ignored by `__eq__` and ordering. |
| `hash` | `None` | Follows `compare` unless you set it explicitly. |
| `metadata` | empty | A read-only mapping for your own data. Python never uses it. |
| `kw_only` | `False` | If `True`, the field must be passed by keyword (Python 3.10+). |
You can give default or default_factory, but not both.
Hiding and ignoring fields
from dataclasses import dataclass, field
@dataclass
class Session:
user: str
token: str = field(repr=False)
visits: int = field(default=0, compare=False)
cache: dict = field(default_factory=dict, init=False, repr=False, compare=False)
a = Session("ana", "abc")
b = Session("ana", "abc", visits=3)
print(a) # Session(user='ana', visits=0)
print(a == b) # TrueEach option does a separate job here:
repr=Falsekeeps the token out of logs and tracebacks.compare=Falsemeans two sessions that differ only invisitsare equal.init=Falsemeans callers cannot passcache. Thedefault_factorystill creates an empty dict for each instance.
A field with repr=False can still be read and set as a normal attribute.
Keeping hash and compare consistent
hash=None makes a field take part in __hash__ exactly when it takes part in comparison. That keeps the rule "equal objects have equal hashes" intact. If you set hash=True on a field with compare=False, two equal objects can get different hashes. Do this only when you have a specific reason, such as a field that is costly to compare but cheap to hash.
Attaching metadata
metadata stores information about a field. Libraries and your own code can read it through fields(). The dataclass machinery ignores it.
from dataclasses import dataclass, field, fields
@dataclass
class Product:
name: str = field(metadata={"label": "Product name"})
price: float = field(default=0.0, metadata={"unit": "EUR"})
for f in fields(Product):
print(f.name, dict(f.metadata))
# name {'label': 'Product name'}
# price {'unit': 'EUR'}The mapping is read-only, so write metadata when you define the class and do not edit it afterwards.
Per-field keyword-only
On Python 3.10 or newer, kw_only=True on one field moves it to the end of __init__ and requires a keyword. This also fixes the "non-default argument follows default argument" error:
from dataclasses import dataclass, field
@dataclass
class Job:
name: str
retries: int = field(default=3, kw_only=True)
timeout: float = 10.0
print(Job("backup", 30.0, retries=5))
# Job(name='backup', retries=5, timeout=30.0)Keyword-only fields are not counted in the "defaults must come last" rule, so retries can sit in the middle of the field list.
Common errors
- Writing
field(default=[])orfield(default={}). Python raisesValueErrorfor mutable defaults. Usedefault_factory. - Passing both
defaultanddefault_factory. This raisesValueError. - Using
field()with no default and then putting it before fields that have defaults. A field with no default must still come before fields with defaults, unless it iskw_only. - Expecting
compare=Falseto remove a field fromrepr. The two options are independent.
Exercise
A dataclass Order has fields id: int and updated_at: float. Two orders with the same id should compare equal even if updated_at differs, and updated_at should not appear in the printed form. How do you declare updated_at?
Show answer
Use updated_at: float = field(compare=False, repr=False). compare=False removes it from __eq__, and repr=False removes it from __repr__. Since it has no default, it must come before any field that has one, or you can add default=0.0 and place it last.