On Sun, Jul 13, 2014 at 02:04:17PM +0000, Jason R. Coombs wrote:
> PEP-416 mentions a MappingProxyType, but that’s no help.
Well, it kindof is. By combining MappingProxyType and UserDict the
desired effect can be achieved concisely:
import collections
import types
class frozendict(collections.UserDict):
def __init__(self, d, **kw):
if d:
d = d.copy()
d.update(kw)
else:
d = kw
self.data = types.MappingProxyType(d)
_h = None
def __hash__(self):
if self._h is None:
self._h = sum(map(hash, self.data.items()))
return self._h
def __repr__(self):
return repr(dict(self))
> Although hashability is mentioned in the PEP under constraints, there are many
> use-cases that fall out of the ability to hash a dict, such as the one
> described above, which are not mentioned at all in use-cases for the PEP.
> If there’s ever any interest in reviving that PEP, I’m in favor of its
> implementation.
In its previous form, the PEP seemed more focused on some false
optimization capabilities of a read-only type, rather than as here, the
far more interesting hashability properties. It might warrant a fresh
PEP to more thoroughly investigate this angle.
David
_______________________________________________
Python-Dev mailing list
[email protected]
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe:
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com