Design immutable value objects when equality should depend on content rather than identity.
What You Will Learn
A value object represents a quantity or fact such as a coordinate, date range, or money amount. frozen dataclasses prevent ordinary field assignment and generate useful equality rules. Immutability works best when nested fields are also immutable; a frozen object can still contain a mutable list. Hashability additionally depends on the field types.
Class interfaces should preserve their stated invariants. Type annotations describe intent but do not enforce runtime types on their own.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from dataclasses import dataclass
@dataclass(frozen=True)
class Coordinate:
latitude: float
longitude: float
office = Coordinate(32.0, 34.9)
same_place = Coordinate(32.0, 34.9)
print(office == same_place)
print(len({office, same_place}))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: dataclasses.
- The class Coordinate groups data and behavior; its methods run when called on an instance.
- The variable office holds the result of Coordinate(32.0, 34.9). Later lines use that value or inspect how it changes.
- The variable same_place holds the result of Coordinate(32.0, 34.9). Later lines use that value or inspect how it changes.
Expected output from the example:
True
1
When You Would Use This
A class becomes useful when several operations must maintain rules around related data. Think about which state belongs to each instance, which operations should be public, and how errors should be reported. Avoid making the design more complex than the underlying task.
Practice: Modify the Code
Add a label field and decide whether changing the label should create a different value object.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Thinking frozen=True recursively freezes every object referenced by a field.
- Expecting a mutable nested list to become safely hashable because the outer class is frozen.
Key Takeaways
- Design immutable value objects when equality should depend on content rather than identity.
- A value object represents a quantity or fact such as a coordinate, date range, or money amount. frozen dataclasses prevent ordinary field assignment and generate useful equality rules.
- Apply this operation only after checking the assumptions and input conditions shown in the example.