Frozendict

2.4.7 · active · verified Sun Mar 29

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

Install

Imports

Quickstart

Demonstrates creating a frozendict, accessing elements, its immutability and hashability, and the use of `deepfreeze` for recursive immutability.

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}")

view raw JSON →