A program loads editable settings, then exposes a safe snapshot.
What You Need to Understand
Both dict and frozendict map hashable keys to values. dict allows adding, replacing and deleting entries; frozendict offers a read-only mapping structure without mutation methods such as update() or pop().
When to Use It
A program loads editable settings, then exposes a safe snapshot.
Step-by-Step Python Example
editable = {"theme": "light"}
immutable = frozendict(editable)
editable["theme"] = "dark"
print(editable["theme"])
print(immutable["theme"])
How the Example Works
Constructing the frozen mapping makes a shallow copy of entries, so changing the outer editable dictionary does not update the snapshot.
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
settings = frozendict(a=1)
print(settings | {"b": 2})
Important Behavior and Edge Cases
Unlike dict, frozendict is not a dict subclass. Use collections.abc.Mapping when accepting any read-only mapping interface.
This example uses a Python feature. It must be run with Python or newer; earlier interpreters may reject the syntax or lack the built-in type.
Try It Yourself
Try immutable | {"page_size": 10} and inspect the returned type.
Common Beginner Mistakes
- Unlike dict,
frozendictis not a dict subclass. Usecollections.abc.Mappingwhen accepting any read-only mapping interface. - Treating missing dictionary keys, replacement precedence, and shallow copies as if they had identical behavior in every context.
Key Takeaways
- Both
dictandfrozendictmap hashable keys to values. - Constructing the frozen mapping makes a shallow copy of entries, so changing the outer editable dictionary does not update the snapshot.
- Unlike dict,
frozendictis not a dict subclass.