Store derived display data outside dataclass equality
Also published in our Blogger archive.
Store derived display data outside dataclass equality
A record can carry text intended for display without allowing that text to redefine the record’s business equality. Product stores a SKU and a price in cents as its core values. It also stores display, a preformatted presentation string. Declaring display with field(compare=False) excludes it from the generated equality method.
The example compares two products with the same SKU and cents but different display formats: "$12.50" and "12,50 USD". They compare equal because the declared comparison fields match, while a direct assertion confirms the display text itself differs. A third product changes the cents value, so it compares unequal. The output therefore reads True False.
This is appropriate only when the excluded value is genuinely outside the record’s equality semantics. Do not use compare=False to conceal a field that must distinguish products in caches, sets, or business rules. For frozen dataclasses, the default generated hash follows the comparison fields; consider that consequence before using such values as dictionary keys. Also, storing display text means it may become stale if locale or formatting requirements change; calculating it at render time is often a better boundary. compare on field() is available with dataclasses in Python 3.7 and later.
The official dataclasses documentation states that compare=True by default and controls inclusion in generated equality and ordering methods.
AI assistance disclosure: This article was drafted with AI assistance and should be reviewed for the application’s equality and localization policy.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Product:
sku: str
cents: int
display: str = field(compare=False)
stored = Product("BK-1", 1250, "$12.50")
localized = Product("BK-1", 1250, "12,50 USD")
changed_price = Product("BK-1", 1300, "$13.00")
assert stored == localized
assert stored != changed_price
assert stored.display != localized.display
print(stored == localized, stored == changed_price)
True False