Compare immutable-style dataclass objects with frozendict mappings.
What You Will Learn
A frozen dataclass blocks normal field reassignment but does not deeply freeze nested mutable fields. Python frozendict blocks mapping updates and may be hashable only if its stored values are hashable; use each for its data model.
frozendict is built in for Python; frozen dataclasses have been available longer.
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 ServiceEndpoint:
hostname: str
port: int
endpoint = ServiceEndpoint("example.test", 443)
settings = frozendict({"hostname": "example.test", "port": 443})
print(endpoint.hostname)
print(settings["port"])
How the Example Works
- The imports provide the standard-library tools used in the demonstration: dataclasses.
- The class ServiceEndpoint groups data and behavior; its methods run when called on an instance.
- The variable endpoint holds the result of ServiceEndpoint('example.test', 443). Later lines use that value or inspect how it changes.
- The variable settings holds the result of frozendict({'hostname': 'example.test', 'port': 443}). Later lines use that value or inspect how it changes.
This code uses an API available from Python 3.15. Run it in Python 3.15 or newer; older interpreters may fail at the import statement.
The hostname line should be example.test and the port line should be 443. The runtime here cannot execute the built-in frozendict example.
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
Represent one configuration with each approach and compare their access patterns.
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
- Assuming frozen dataclasses recursively freeze mutable objects stored in their fields.
- Assuming every frozendict with nested unhashable values can be used as a dictionary key.
Key Takeaways
- Compare immutable-style dataclass objects with frozendict mappings.
- A frozen dataclass blocks normal field reassignment but does not deeply freeze nested mutable fields.
- frozendict is built in for Python; frozen dataclasses have been available longer.