[Python-Dev] Another case for frozendict (original) (raw)

Jason R. Coombs jaraco at jaraco.com
Sun Jul 13 16:04:17 CEST 2014


I repeatedly run into situations where a frozendict would be useful, and every time I do, I go searching and find the (unfortunately rejected) PEP-416. I'd just like to share another case where having a frozendict in the stdlib would be useful to me.

I was interacting with a database and had a list of results from 206 queries:

res = [db.cases.remove({'id': doc['id']}) for doc in fives] len(res) 206

I can see that the results are the same for the first two queries.

res[0] {'n': 1, 'err': None, 'ok': 1.0} res[1] {'n': 1, 'err': None, 'ok': 1.0}

So I'd like to test to see if that's the case, so I try to construct a 'set' on the results, which in theory would give me a list of unique results:

set(res) Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'dict'

I can't do that because dict is unhashable. That's reasonable, and if I had a frozen dict, I could easily work around this limitation and accomplish what I need.

set(map(frozendict, res)) Traceback (most recent call last): File "", line 1, in NameError: name 'frozendict' is not defined

PEP-416 mentions a MappingProxyType, but that's no help.

resex = list(map(types.MappingProxyType, res)) set(resex) Traceback (most recent call last): File "", line 1, in TypeError: unhashable type: 'mappingproxy'

I can achieve what I need by constructing a set on the 'items' of the dict.

set(tuple(doc.items()) for doc in res) {(('n', 1), ('err', None), ('ok', 1.0))}

But that syntax would be nicer if the result had the same representation as the input (mapping instead of tuple of pairs). A frozendict would have readily enabled the desirable behavior.

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. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20140713/28d1dc79/attachment.html>



More information about the Python-Dev mailing list