Sub topic 5
Fine-tuning fields with field()
This chapter assumes you can write a basic @dataclass, know why mutable defaults need default_factory, and have Python 3.7 or newer. The per-field kw_only option needs Python 3.10 or newer.
A plain annotation such as x: int = 0 gives a field a name, a type, and a default. The field() function lets you configure that one field further. You can hide it from repr, exclude it from comparison, leave it out of __init__, or attach your own metadata. You assign the result of field() where you would otherwise write the default value.
What field() accepts
All parameters are keyword-only.
| Parameter | Default | Effect |
|---|---|---|
| `default` | none | Constant default value. Same as writing `= value`. |
| `default_factory` | none | Zero-argument callable run for each new instance. |
| `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 by ordering. |
| `hash` | `None` | `None` means "follow `compare`". `True` or `False` forces it in or out of `__hash__`. |
| `metadata` | none | A mapping of your own data. Dataclasses never read it. |
| `kw_only` | `MISSING` | If `True`, the `__init__` parameter is keyword-only (3.10+). |
You can only give one of default and default_factory. Passing both raises ValueError: cannot specify both default and default_factory.
Hiding fields with repr=False
Use repr=False for values that are noisy or sensitive, such as tokens or large caches.
from dataclasses import dataclass, field
@dataclass
class Account:
owner: str
balance: float = 0.0
token: str = field(default="", repr=False)
history: list[float] = field(default_factory=list, repr=False, compare=False)
a = Account("ana", 10.0, "t1")
b = Account("ana", 10.0, "t1")
a.history.append(5.0)
print(a) # Account(owner='ana', balance=10.0)
print(a == b) # True, history is ignored by comparisontoken still takes part in ==, because only repr was turned off. history is excluded from comparison, so a and b are equal even though their histories differ.
Excluding fields from comparison with compare=False
Bookkeeping data such as view counters, timestamps, and caches should usually not decide whether two objects are equal. Set compare=False on them. The flag affects every generated comparison method: __eq__, and __lt__, __le__, __gt__, __ge__ when order=True.
This means that two instances can be "equal" while holding different data. Keep that in mind when you write tests, and keep it for fields that truly do not matter.
Fields outside __init__ with init=False
A field with init=False is not a parameter of __init__. It still exists on the instance and still appears in repr and comparisons. There are three ways to fill it.
- Give it a
default. The generated__init__assigns that constant. - Give it a
default_factory. The generated__init__calls it for each instance. - Assign it yourself in
__post_init__.
from dataclasses import dataclass, field
from itertools import count
_ids = count(1)
@dataclass
class Ticket:
title: str
id: int = field(init=False, default_factory=lambda: next(_ids))
print(Ticket("login bug")) # Ticket(title='login bug', id=1)
print(Ticket("slow page")) # Ticket(title='slow page', id=2)If you give an init=False field no default and never assign it, the attribute does not exist. Reading it raises AttributeError, and so does repr(), because the generated __repr__ reads every field with repr=True.
from dataclasses import dataclass, field
@dataclass
class Box:
w: int
area: int = field(init=False)
b = Box(2)
try:
print(b.area)
except AttributeError:
print("area was never set")Fields with init=False are also exempt from the "non-default field after default field" rule, because that rule only applies to parameters of __init__.
Controlling hashing with hash
The hash option only matters when a __hash__ method is generated. That happens with frozen=True (and the default eq=True), or with unsafe_hash=True. In every other case the option is ignored. A plain @dataclass with eq=True sets __hash__ to None, which makes its instances unhashable.
With hash=None, the field follows compare. Set hash=False when a field should count for equality but cannot or should not be hashed, such as a list.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Reading:
sensor: str
value: float
tags: list[str] = field(default_factory=list, hash=False)
r1 = Reading("s1", 1.0, ["a"])
r2 = Reading("s1", 1.0, ["b"])
print(r1 == r2) # False, tags take part in equality
print(hash(r1) == hash(r2)) # True, tags are left out of the hashWithout hash=False, hash(r1) would fail with TypeError: unhashable type: 'list'. Two objects that are equal must have equal hashes, and this example respects that. Objects with different tags are unequal but share a hash, which is allowed and only causes a hash collision.
A frozen class with a mutable list field is not truly immutable. Only attribute assignment is blocked, so r1.tags.append("c") still works and changes the instance's equality.
Attaching metadata
metadata holds any mapping you like. The dataclass machinery never reads it. Libraries and your own code read it through fields(). The mapping is wrapped in a read-only view, so you cannot change it after the class is created.
from dataclasses import dataclass, field, fields
@dataclass
class Product:
name: str = field(metadata={"label": "Product name", "max_length": 10})
price: float = field(default=0.0, metadata={"label": "Price", "unit": "EUR"})
def __post_init__(self):
for f in fields(self):
limit = f.metadata.get("max_length")
if limit is not None and len(getattr(self, f.name)) > limit:
raise ValueError(f"{f.name} is longer than {limit} characters")
for f in fields(Product):
print(f.name, dict(f.metadata))
# name {'label': 'Product name', 'max_length': 10}
# price {'label': 'Price', 'unit': 'EUR'}
Product("Pen", 1.5) # fine
try:
Product("A very long product name")
except ValueError as e:
print(e) # name is longer than 10 charactersThis pattern keeps validation rules next to the field they describe. Use it for form labels, serialization names, units, and validation limits.
Keyword-only fields with kw_only
On Python 3.10 or newer, field(kw_only=True) makes one field keyword-only without changing the others. Keyword-only fields move to the end of the __init__ signature. This also lets a required keyword-only field follow fields that have defaults.
from dataclasses import dataclass, field
@dataclass
class Job:
name: str
retries: int = field(default=3, kw_only=True)
timeout: float = field(kw_only=True)
print(Job("backup", timeout=30.0))
# Job(name='backup', retries=3, timeout=30.0)
try:
Job("backup", 3, 30.0)
except TypeError:
print("retries and timeout must be passed by keyword")repr still lists fields in the order you declared them. Only the __init__ parameter order changes. The class-wide form, @dataclass(kw_only=True), is covered in a later chapter on slots=True and kw_only.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ValueError: cannot specify both default and default_factory` | Both were passed to `field()`. | Pick one. |
| `ValueError: mutable default ... use default_factory` | `field(default=[])` or `= []`. | Use `default_factory=list`. |
| `AttributeError` when printing an instance | An `init=False` field has no default and was never assigned. | Add a default or assign it in `__post_init__`. |
| `TypeError: unhashable type` on a frozen class | A list or dict field is part of the hash. | Add `hash=False` to that field. |
| Equal objects with different data | A field has `compare=False`. | Expected. Remove the flag if the field matters. |
| `TypeError: non-default argument follows default argument` | A required parameter follows one with a default. | Reorder the fields, or use `kw_only=True` on the required one. |
Exercise
A frozen dataclass Session has user: str, token: str and visits: list[int]. The token must never appear in the printed text, and the list must not break hashing. How do you declare token and visits, and does the hidden token still show up in asdict()?
Show answer
Declare token: str = field(repr=False) and visits: list[int] = field(default_factory=list, hash=False). Because token has no default, put it before any field that has one, or give it a default. repr=False only affects the printed text, so asdict() still returns the token. visits is still compared for equality but is left out of the hash, so hash() works.
Exercise
Given @dataclass class C: a: int; b: int = field(init=False), what happens on C(1).b, and which two changes to the class would make it return a value?
Show answer
It raises AttributeError, because b is not an __init__ parameter and nothing assigns it. You can fix it by giving b a default, as in field(init=False, default=0), or by adding a __post_init__ method that assigns self.b.