[Python-ideas] Make types.MappingProxyType hashable

Nick Coghlan ncoghlan at gmail.com
Fri Jul 29 07:04:02 EDT 2016


On 29 July 2016 at 08:23, Emanuel Barry <vgr255 at live.ca> wrote:
> Not me, actually. Someone in #python asked about an immutable dict, and I pointed them towards mappingproxy, only to realize it wasn't hashable. Maybe something like frozendict could be added, though? At this point I don't really have an opinion, so it's up to the list to decide if they want it or not :)

For most cases where this kind of capability is needed, it will be
sufficient to model a frozen dict as a frozen set of 2-tuples:

>>> data = {k: str(k) for k in range(5)}
>>> data
{0: '0', 1: '1', 2: '2', 3: '3', 4: '4'}
>>> frozenset(data.items())
frozenset({(4, '4'), (3, '3'), (1, '1'), (0, '0'), (2, '2')})
>>> dict(frozenset(data.items()))
{0: '0', 1: '1', 2: '2', 3: '3', 4: '4'}

The fact the frozen set is keyed by the key-value pairs rather than
just the keys doesn't matter, as you can't add any new entries at all,
and the same goes for any other discrepancies between the invariants
of the two data structures: even though the frozen set doesn't enforce
any dict invariants, their preservation is ensured by the stricter
immutability and hashability invariants.

And in cases where you want to expose a read-only view to a normal
dictionary, then you have types.MappingProxyType.

So it's not that a frozendict type couldn't be provided, it's just of
highly questionable utility given other existing features.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list