[Python-ideas] Revisiting Immutable Mappings

Steven D'Aprano steve at pearwood.info
Tue Oct 16 05:23:39 EDT 2018

On Tue, Oct 16, 2018 at 01:02:03AM -0700, George Leslie-Waksman wrote:
> Would a frozendict require that keys and values be hashable?

Keys, yes. Values, no.

If the values were hashable, the frozendict itself would also be 
hashable. If not, then it would be like trying to hash a tuple with 
unhashable items:

py> hash((1, 2, {}, 3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

> It seems to me that we would need this restriction to make a reasonably
> universal frozendict that is, itself, hashable.

When people talk about frozendicts being hashable, they mean it in the 
same sense that tuples are hashable. 

For what it is worth, here's an incomplete, quick and dirty proof of 
concept frozendict, using automatic delegation:

# Not good enough for production, not tested, buyer beware, etc.
class frozendict:
    def __new__(cls, *args, **kwargs):
        d = dict(*args, **kwargs)
        proxy = types.MappingProxyType(d)
        instance = super().__new__(cls)
        instance.__proxy = proxy
        return instance
    def __hash__(self):
        return hash(tuple(self.items()))
    def __getattr__(self, name):
        return getattr(self.__proxy, name)
    def __getitem__(self, key):
        return self.__proxy[key]
    def __repr__(self):
        return "%s(%r)" % (type(self).__name__, dict(self))


More information about the Python-ideas mailing list