On 02/22/2013 03:57 PM, Bruce Leban wrote:
On Fri, Feb 22, 2013 at 3:16 PM, Ethan Furman
mailto:ethan@stoneleaf.us> wrote: Problem here: should we have our enums hash the same as the underlying value? Consider:
<snip>
From a practicality standpoint the question is: How likely is it to use different enum classes as keys?
Having the same hash value isn't the problem.
True -- the problem is using two different enum classes with the same underlying int value as keys and then using ints instead of the enums to try to access the values.
The problem is that black == 0 and scifi == 0. So when the hash values collide, it chains them and then uses == to compare the 0 to find the matching value in the table. To avoid this problem ensure that hash(enum) != hash(int(enum)) [or whatever the base type of the enum is].
If we do this, then a plain int won't be able to look up an enum key, which would mean that int enums are not drop-in replacements for int's currently be used in enum-type contexts. I'm inclined to leave the problem as is, though, unless somebody has a use case where they are using two different enum classes in a single dictionary?
Actually, I'm not sure that works without looking at the implementation of dict. When there are multiple values in a bucket, does it compare hash values first or does it jump right to ==?
dict uses hash first -- after all, it's a hash table. :) -- ~Ethan~