Skip to content

Instantly share code, notes, and snippets.

@silas
Created December 31, 2021 03:47
Show Gist options
  • Save silas/217e441e22297d7901e97d8c6ddd2162 to your computer and use it in GitHub Desktop.
Save silas/217e441e22297d7901e97d8c6ddd2162 to your computer and use it in GitHub Desktop.
Python FrozenMap (frozendict, immutable dict, etc...)
import collections.abc
import typing as typ
K = typing.TypeVar("K")
V = typing.TypeVar("V")
class FrozenMap(typing.Generic[K, V], collections.abc.Mapping[K, V]):
__slots__ = ("_dict", "_hash")
def __init__(self, *args, **kwargs):
self._dict: typing.Dict[K, V] = dict(*args, **kwargs)
self._hash: typing.Optional[int] = None
def __getitem__(self, key: K) -> V:
return self._dict[key]
def __contains__(self, key: K) -> bool:
return key in self._dict
def __iter__(self) -> typing.Iterator[K]:
return iter(self._dict)
def __len__(self) -> int:
return len(self._dict)
def __repr__(self) -> str:
return f"FrozenMap({repr(self._dict)})"
def __hash__(self) -> int:
if self._hash is None:
self._hash = hash(frozenset(self._dict.items()))
return self._hash
def replace(self, /, **changes):
return self.__class__(self, **changes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment