A simple immutable dictionary implementation with hashing support and performance optimizations
85
The main frozendict class providing an immutable dictionary with complete dict-compatible API, hashing support, and specialized methods for creating modified copies while maintaining immutability.
Creates frozendict instances from various input types with the same constructor API as the built-in dict.
class frozendict(dict):
def __init__(*args, **kwargs):
"""
Initialize frozendict with same arguments as dict.
Parameters:
- *args: Positional arguments (mapping, iterable of pairs, etc.)
- **kwargs: Keyword arguments for key-value pairs
"""
@classmethod
def fromkeys(cls, *args, **kwargs):
"""
Create frozendict from keys with default value.
Identical to dict.fromkeys().
Parameters:
- keys: Iterable of keys
- value: Default value for all keys (default: None)
Returns:
frozendict: New frozendict instance
"""Usage Example:
from frozendict import frozendict
# From dict
d1 = frozendict({'a': 1, 'b': 2})
# From key-value pairs
d2 = frozendict([('x', 10), ('y', 20)])
# From keyword arguments
d3 = frozendict(name='Alice', age=30)
# Using fromkeys
d4 = frozendict.fromkeys(['a', 'b', 'c'], 0) # {'a': 0, 'b': 0, 'c': 0}Provides hashing support when all values are hashable, enabling use as dictionary keys and set members.
def __hash__(self):
"""
Return hash of frozendict if all values are hashable.
Returns:
int: Hash value
Raises:
TypeError: If any value is not hashable
"""
def copy(self):
"""
Return self since frozendict is immutable.
Returns:
frozendict: Returns self
"""
def __copy__(self):
"""
Support for copy.copy().
Returns:
frozendict: Returns self
"""
def __deepcopy__(self, memo):
"""
Support for copy.deepcopy().
Parameters:
- memo: Memoization dictionary for deepcopy
Returns:
frozendict: Deep copy of frozendict with deep-copied values
"""Usage Example:
from frozendict import frozendict
# Hashable frozendict
d = frozendict({'a': 1, 'b': 2})
my_set = {d} # Can be used in sets
cache = {d: "result"} # Can be used as dict keys
# Non-hashable values prevent hashing
d_unhashable = frozendict({'a': [1, 2, 3]})
# hash(d_unhashable) # Would raise TypeErrorMethods for creating new frozendict instances with modifications while preserving immutability of the original.
def set(self, key, val):
"""
Return new frozendict with key set to val.
Parameters:
- key: Key to set
- val: Value to set
Returns:
frozendict: New frozendict with modification
"""
def delete(self, key):
"""
Return new frozendict without key.
Parameters:
- key: Key to remove
Returns:
frozendict: New frozendict without the key
Raises:
KeyError: If key is not present
"""
def setdefault(self, key, default=None):
"""
Return new frozendict with key set to default if key is missing.
Parameters:
- key: Key to check and potentially set
- default: Value to set if key is missing (default: None)
Returns:
frozendict: New frozendict with key set if it was missing, or original if key existed
"""Usage Example:
from frozendict import frozendict
original = frozendict({'a': 1, 'b': 2})
# Create modified copies
updated = original.set('c', 3) # {'a': 1, 'b': 2, 'c': 3}
modified = original.set('a', 10) # {'a': 10, 'b': 2}
smaller = original.delete('b') # {'a': 1}
defaulted = original.setdefault('d', 4) # {'a': 1, 'b': 2, 'd': 4}
# Original remains unchanged
print(original) # frozendict({'a': 1, 'b': 2})Methods for accessing items by insertion order index, maintaining compatibility with modern dict ordering.
def key(self, index=0):
"""
Get key by insertion order index.
Parameters:
- index: Position index (default: 0)
Returns:
Key at the specified index position
Raises:
IndexError: If index is out of range
"""
def value(self, index=0):
"""
Get value by insertion order index.
Parameters:
- index: Position index (default: 0)
Returns:
Value at the specified index position
Raises:
IndexError: If index is out of range
"""
def item(self, index=0):
"""
Get (key, value) tuple by insertion order index.
Parameters:
- index: Position index (default: 0)
Returns:
tuple: (key, value) pair at the specified index position
Raises:
IndexError: If index is out of range
"""Usage Example:
from frozendict import frozendict
d = frozendict([('first', 1), ('second', 2), ('third', 3)])
# Access by index
print(d.key(0)) # 'first'
print(d.value(1)) # 2
print(d.item(2)) # ('third', 3)
# Negative indexing supported
print(d.key(-1)) # 'third'
print(d.value(-2)) # 2Support for union operators to merge frozendict instances.
def __or__(self, other):
"""
Union operator |. Returns new frozendict with items from both.
Parameters:
- other: Mapping to merge with
Returns:
frozendict: New frozendict with combined items (other takes precedence)
"""
def __ior__(self, other):
"""
In-place union operator |=. Returns new frozendict (immutable).
Parameters:
- other: Mapping to merge with
Returns:
frozendict: New frozendict with combined items (other takes precedence)
"""Usage Example:
from frozendict import frozendict
d1 = frozendict({'a': 1, 'b': 2})
d2 = frozendict({'b': 20, 'c': 3})
# Union operations
merged = d1 | d2 # frozendict({'a': 1, 'b': 20, 'c': 3})
d1 |= d2 # d1 is now frozendict({'a': 1, 'b': 20, 'c': 3})All standard dictionary methods are available with read-only semantics.
def keys(self): ...
def values(self): ...
def items(self): ...
def get(self, key, default=None): ...
def __getitem__(self, key): ...
def __len__(self): ...
def __iter__(self): ...
def __reversed__(self): ...
def __contains__(self, key): ...
def __repr__(self): ...
def __str__(self): ...
def __eq__(self, other): ...
def __ne__(self, other): ...Built-in support for pickle and unpickle operations.
def __reduce__(self):
"""
Support for pickle serialization.
Returns:
tuple: Reconstruction information for pickle
"""Usage Example:
import pickle
from frozendict import frozendict
d = frozendict({'a': 1, 'b': 2})
# Pickle and unpickle
pickled = pickle.dumps(d)
restored = pickle.loads(pickled)
print(restored == d) # Trueclass frozendict(dict):
"""
A simple immutable dictionary that supports hashing and maintains
dict API compatibility while guaranteeing immutability.
"""
__slots__ = ("_hash",)Install with Tessl CLI
npx tessl i tessl/pypi-frozendictevals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10