On Sat, Apr 02, 2022 at 09:28:55AM -0700, Christopher Barker wrote:
> Anyway, it would be nice for someone to take up the mantle of getting an
> immutable Mapping into the stdlib.
Here is a "FrozenMapping" class that could be added to collections. I
have tested it ~~extensively~~ for nearly two minutes and haven't been
able to break it, so it must be good *wink*
```
from collections.abc import Mapping
from types import MappingProxyType
class FrozenMapping(Mapping):
__slots__ = ('_proxy', '_hash')
def __new__(cls, *args, **kwargs):
a = dict(*args, **kwargs)
obj = super().__new__(cls)
obj._proxy = MappingProxyType(a)
obj._hash = None
return obj
def __getitem__(self, key):
return self._proxy[key]
def __iter__(self):
yield from self._proxy
def __len__(self):
return len(self._proxy)
def copy(self):
return self # We're immutable.
def __reversed__(self):
return reversed(self._proxy)
def __or__(self, other):
return type(self)(self._proxy | other)
def __ror__(self, other):
return type(self)(other | self._proxy)
def __hash__(self):
if self._hash is None:
self._hash = hash(frozenset(self.items()))
return self._hash
def __repr__(self):
items = ', '.join(['%r: %r' % t for t in self.items()])
return '%s({%s})' % (type(self).__name__, items)
```
I haven't considered pickling, or deep-copying. I don't think there is
any way to get access to the underlying dict and modify it, except
perhaps via ctypes, so I think it is as immutable as it is possible to
get from Python code. Feel free to take that as a challenge to break it.
Does anyone want to champion adding this to collections? I guess it will
need at least a short PEP to justify that there are use-cases for frozen
mappings.
--
Steve
_______________________________________________
Python-Dev mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/VDMJVEFP7FK3M25ICJGWG7XJXPPUN6OQ/
Code of Conduct: http://python.org/psf/codeofconduct/