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" <jar...@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 "<stdin>", line 1, in <module> > 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 "<stdin>", line 1, in <module> > NameError: name 'frozendict' is not defined > > PEP-416 mentions a MappingProxyType, but that’s no help. > > >>> res_ex = list(map(types.MappingProxyType, res)) > >>> set(res_ex) > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > 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@python.org > https://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: > https://mail.python.org/mailman/options/python-dev/wizzat%40gmail.com
_______________________________________________ Python-Dev mailing list Python-Dev@python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com