Recalculate Derived Fields with dataclasses.replace
When an order quantity changes, its stored total must change too. dataclasses.replace() creates a new instance through its initializer, so __post_init__() can recalculate an init=False field.
Tested with Python 3.12.14 on Linux. The example uses only the standard library.
Prepare an isolated directory
Run this setup in Bash. If either command fails, stop before saving any files.
practice_dir=$(mktemp -d) && cd "$practice_dir"Replace the quantity and check ownership
The example stores prices as integer cents and validates the quantity. It does not validate prices; add that check before using this record in an application.
Save as replace_order.py:
from dataclasses import dataclass, field, replace
@dataclass
class Order:
quantity: int
unit_cents: int
labels: list[str] = field(default_factory=list)
total_cents: int = field(init=False)
def __post_init__(self):
if type(self.quantity) is not int or self.quantity < 0:
raise ValueError("quantity must be a nonnegative integer")
self.total_cents = self.quantity * self.unit_cents
original = Order(2, 350, ["pending"])
updated = replace(original, quantity=3)
print("Totals:", original.total_cents, updated.total_cents)
print("Same order:", original is updated)
print("Shared labels:", original.labels is updated.labels)
isolated = replace(original, quantity=4, labels=original.labels.copy())
isolated.labels.append("reviewed")
print("Original labels:", original.labels)
print("Isolated labels:", isolated.labels)
try:
replace(original, quantity=-1)
except ValueError as error:
print("Rejected:", error)
assert updated.total_cents == 1050
assert isolated.labels is not original.labelsRun:
python3 replace_order.pyOutput:
Totals: 700 1050
Same order: False
Shared labels: True
Original labels: ['pending']
Isolated labels: ['pending', 'reviewed']
Rejected: quantity must be a nonnegative integerChoose which fields should be copied
The new order has a fresh total, but its unchanged list field still refers to the original list. A default factory runs when a value is omitted during construction. Here, replace() supplies the existing field value, so the factory does not provide a fresh list.
Passing a copied list makes the two lists independent. That shallow copy is sufficient for these string labels. Lists containing mutable objects need an ownership policy for those objects as well.
In this example, initialization rebuilds the init=False total rather than copying it from the source. Passing that field in the changes to replace() raises ValueError. Keep initialization deterministic and account for any side effects, since replacement calls it again. Directly assigning a new quantity later would not rerun this calculation; use replacement consistently or compute the total through a property.
Clean up
From the practice directory, remove only the example file. Return to the previous directory before removing the now-empty temporary directory.
rm -- replace_order.py
cd - >/dev/null
rmdir -- "$practice_dir"Reference
Acknowledgements
This post was created with assistance from AI.