DevPath
Foundation lesson · 12 min

Model values without losing meaning

Use dataclasses and decimal values for domain concepts.

Make invalid states harder to create

A dictionary can hold any keys and values, which is flexible at a boundary but fragile deep in a program. A dataclass names the fields of a domain value. Validate invariants when creating it: an amount may need to be non-negative and a currency code must be known. Frozen values help prevent accidental mutation after validation.

Avoid binary floats for money

A float stores a binary approximation and can produce surprising decimal results. Use Decimal from a string or integer minor units, and define rounding rules at the boundary. Do not build a Decimal from a float if exact decimal input matters.

from dataclasses import dataclass
from decimal import Decimal

@dataclass(frozen=True)
class Price:
    amount: Decimal
    currency: str

Test the invariant

Test a valid price, negative amount, unsupported currency, and an exact decimal such as 0.10. Specify whether zero is valid. A model is only useful if callers cannot easily bypass its invariant; centralize creation rather than repeating ad hoc checks throughout the code.

Check your understanding

Why construct Decimal from `'0.10'` instead of `0.10`?

Show explanation

The string preserves the intended decimal value; the float may already contain a binary approximation.

Put this lesson into practice

A practice activity at this level in the same module.

Try: De-duplicate values preserving order

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.