[Python-ideas] Make types.MappingProxyType hashable
Emanuel Barry
vgr255 at live.ca
Fri Jul 29 08:02:32 EDT 2016
All right, this makes sense. Thanks for the reply!
-Emanuel
> From: Nick Coghlan [mailto:ncoghlan at gmail.com]
> Subject: Re: [Python-ideas] Make types.MappingProxyType hashable
>
> 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.
More information about the Python-ideas
mailing list