←back to thread

191 points jwilk | 4 comments | | HN request time: 0s | source
Show context
pansa2 ◴[] No.46230704[source]
I wonder whether Raymond Hettinger has an opinion on this PEP. A long time ago, he wrote: "freezing dicts is a can of worms and not especially useful".

https://mail.python.org/pipermail/python-dev/2006-February/0...

replies(8): >>46230899 #>>46230957 #>>46231064 #>>46231597 #>>46232170 #>>46234698 #>>46235104 #>>46271495 #
morshu9001 ◴[] No.46234698[source]
I agree, same with frozenset. If you really want to use one of those as a key, convert to a tuple. There might be niche use cases for all this, but it's not something that the language or even the standard lib need to support.
replies(1): >>46234934 #
1. boothby ◴[] No.46234934[source]
Problem being that sets aren't consistently ordered and conversion to a tuple can result in an exponential (specifically, factorial) explosion in the number of possible keys associated with a single set. Nor can you sort all objects. Safe conversion of sets to tuples for use as keys is possible but the only technique I know requires an auxiliary store of objects (mapping objects to the order in which they were first observed), which doesn't parallelize well.
replies(1): >>46235200 #
2. morshu9001 ◴[] No.46235200[source]
tuple(sorted(s)) and if you can't even sort the values, they're probably not hashable. I get that this involves a copy, but so does frozenset, and you can cross that bridge in various ways if it's ever a problem.
replies(1): >>46236204 #
3. boothby ◴[] No.46236204[source]
Here are some types that support hashing:

  str
  bytes
  int, float
  complex
  tuple
  frozenset
Aside from int and float, you cannot perform comparisons between objects of different types. Moreover, you cannot sort complex numbers at all.

I have crossed that bridge, and I'm telling you (again) that a sorted tuple is not a generic solution.

replies(1): >>46236536 #
4. morshu9001 ◴[] No.46236536{3}[source]
I'm not saying the problem with tuple doesn't exist, but that there doesn't need to be a built-in way to deal with it. If for some unfortunate reason you've got a mixed-type set that you also want to use as a dict key, you can write a helper.