compare approaches one problem · two ways
Compare Approaches
The same problem solved different ways in Python, run on the same input, with what really differs and when to use each.
Mutable records vs immutable recordsbehaves differently
Share one order record between two parts of a program, then apply a discount in one of them.
what differs
Mutating the shared object changes it for everyone holding a reference, including the report. With a frozen record, ‘changing’ means making a new one; the original stays as it was.
at a glance
| approach | use it when |
|---|---|
| A · mutable dataclass | The record really is one changing thing (a shopping cart being edited). |
| B · frozen dataclass + replace | Values passed around many places: nobody can change them under you, and they can be dict keys. |
Watch out: frozen only stops attribute assignment; a list field inside can still be mutated. Use tuples for collections in frozen records.
the outputs
Each approach runs on the same input.
concepts
immutabilityaliasingdataclasses.replace
learn it
Special methods: printing, comparing and operators
related comparisons