Immutable Dictionary
immutabledict is a Python library providing an immutable wrapper around dictionaries. It functions as a drop-in replacement for standard dictionaries where immutability is desired, implementing the complete mapping interface. Forked from `frozendict`, `immutabledict` offers an MIT-licensed alternative to the LGPL-3.0 licensed original. It also includes `ImmutableOrderedDict` for order-preserving immutable mappings. The library is actively maintained with frequent minor and patch releases.
Warnings
- breaking The `copy()` method signature was changed to no longer accept keyword arguments, aligning its behavior with the standard `dict.copy()` method. Previously, `copy(key='value')` would add `key: 'value'` to the copied dictionary.
- breaking Support for Python 3.7 was officially dropped.
- gotcha While `immutabledict` ensures the dictionary's structure (keys and their assigned values) is immutable, it does *not* recursively make the *values* themselves immutable. If you store mutable objects (e.g., lists, other dictionaries) as values, those objects can still be modified in place through their references.
- gotcha Operations that appear to 'modify' an `immutabledict` (like `set()`, `delete()`, `discard()`, or using the `|` operator) actually return a *new* `immutabledict` instance with the changes, rather than modifying the original in-place. This can incur performance overhead due to repeated object creation and copying if used in tight loops or scenarios with very frequent updates.
- gotcha Starting from v4.0.0, the internal implementation of `immutabledict` switched from overriding `__init__` to overriding `__new__` for constructor calls. While this is primarily an internal refactoring, it's a significant change that could affect advanced use cases such as highly specialized subclassing or detailed introspection that relied on the previous `__init__` behavior.
Install
-
pip install immutabledict
Imports
- immutabledict
from immutabledict import immutabledict
- ImmutableOrderedDict
from immutabledict import ImmutableOrderedDict
Quickstart
from immutabledict import immutabledict
# Create an immutable dictionary
my_item = immutabledict({"a": "value", "b": "other_value"})
print(f"Value for 'a': {my_item['a']}")
# Attempting to modify an immutabledict will raise a TypeError
try:
my_item["c"] = "new_value"
except TypeError as e:
print(f"Attempted modification failed: {e}")
# You can create a new immutabledict with changes using dictionary union operator (PEP 584)
new_item = my_item | {"c": "another_value"}
print(f"New item (original unchanged): {new_item}")
print(f"Original item: {my_item}")