Frozendict
Frozendict is a Python library that provides a simple immutable dictionary implementation, mimicking Python's built-in `dict` but with unchangeable contents after creation. It offers hashability, allowing frozendict instances to be used as keys in other dictionaries or elements in sets. The library is actively maintained, with version 2.4.7 being the latest, and sees regular releases with performance improvements, new features like `deepfreeze`, and support for various architectures.
Warnings
- breaking The `deepfreeze` function (introduced in v2.4.0) no longer modifies the original object in place. It now returns a new frozen object.
- gotcha Methods that create new frozendict instances, such as `set()`, `setdefault()`, and `delete()`, perform shallow copies. If the original frozendict contains mutable nested objects (e.g., lists or dictionaries), these nested objects will still be references to the original mutable objects in the new frozendict.
- gotcha The library typically uses a C extension for performance. In environments where C extensions are problematic or if you need to force the pure Python implementation for debugging, you can set an environment variable.
- gotcha Prior to version 2.4.7, pickling operations for the C extension could be significantly slower than the pure Python implementation or standard dicts. This was addressed with performance improvements in the latest release.
Install
-
pip install frozendict
Imports
- frozendict
from frozendict import frozendict
- deepfreeze
from frozendict import deepfreeze
Quickstart
from frozendict import frozendict, deepfreeze
# Create an immutable dictionary
fd = frozendict({'a': 1, 'b': 2, 'c': [3, 4]})
print(f"Initial frozendict: {fd}")
# Access elements like a regular dict
print(f"Value for 'a': {fd['a']}")
# Attempting to modify raises an error
try:
fd['d'] = 5
except TypeError as e:
print(f"Caught expected error on modification attempt: {e}")
# Note that nested mutable objects are still mutable unless deepfrozen
fd['c'].append(5)
print(f"Frozendict after modifying nested list: {fd}")
# Frozendict instances are hashable, so they can be dict keys
hash_map = {fd: 'this is a key'}
print(f"Using frozendict as a key: {hash_map[fd]}")
# Use deepfreeze for full immutability of nested structures
mutable_data = {'x': 10, 'y': [11, 12], 'z': {'key': 'value'}}
deep_frozen_data = deepfreeze(mutable_data)
print(f"Deep frozen data: {deep_frozen_data}")
try:
deep_frozen_data['y'].append(13) # This will now raise an error
except TypeError as e:
print(f"Caught expected error on deepfrozen nested modification: {e}")