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

Mark Roberts wizzat at gmail.com
Sun Jul 13 18:50:53 CEST 2014


I find it handy to use named tuple as my database mapping type. It allows you to perform this behavior seamlessly.

-Mark

On Jul 13, 2014, at 7:04, "Jason R. Coombs" <jaraco at jaraco.com> wrote:

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.


Python-Dev mailing list Python-Dev at python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/wizzat%40gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20140713/e4053ff9/attachment-0001.html>



More information about the Python-Dev mailing list