[New-bugs-announce] [issue43829] MappingProxyType cannot hash a hashable underlying mapping

Andy Maier report at bugs.python.org
Tue Apr 13 04:25:32 EDT 2021


New submission from Andy Maier <andreas.r.maier at gmx.de>:

Objects of MappingProxyType do expose a __hash__() method, but if the underlying mapping is hashable, it still does not support hashing it.

Example:

Content of mp_hash.py:

------
#!/usr/bin/env python

from nocasedict import NocaseDict, HashableMixin
from types import MappingProxyType

class HashableDict(HashableMixin, NocaseDict):
    """A hashable dictionary"""
    pass

hd = HashableDict({'a': 1, 'b': 2})
print("hash(hd): {}".format(hash(hd)))

mp = MappingProxyType(hd)
print("hash(mp): {}".format(hash(mp)))
-------

Running the mp_hash.py script:

hash(hd): 3709951335832776636
Traceback (most recent call last):
  File "/Users/maiera/Projects/Python/cpython/issues/mappingproxy/./mp_hash.py", line 14, in <module>
    print("hash(mp): {}".format(hash(mp)))
TypeError: unhashable type: 'mappingproxy'

There are use cases where a function wants to return an immutable view on an internal dictionary, and the caller of the function should be able to use the returned object like a dictionary, except that it is read-only.

Note there is https://bugs.python.org/issue31209 on the inability to pickle MappingProxyType objects which was closed without adding the capability. That would fall under the same argument.

----------
components: Library (Lib)
messages: 390936
nosy: andymaier
priority: normal
severity: normal
status: open
title: MappingProxyType cannot hash a hashable underlying mapping
type: behavior
versions: Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43829>
_______________________________________


More information about the New-bugs-announce mailing list