Jason R. Coombs
2014-07-13 14:04:17 UTC
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 can see that the results are the same for the first two queries.
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.
File "<stdin>", line 1, in <module>
NameError: name 'frozendict' is not defined
PEP-416 mentions a MappingProxyType, but that's no help.
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.
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.
res = [db.cases.remove({'_id': doc['_id']}) for doc in fives]
len(res)
206len(res)
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}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):set(res_ex)
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.