On Fri, Feb 22, 2013 at 3:16 PM, Ethan Furman <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.

>>> hash(-1) == hash(-2)
True
>>> d={}
>>> d[-1] = 'm1'
>>> d[-2] = 'm2'
>>> d
{-2: 'm2', -1: 'm1'}
>>> d[-2]
'm2'
>>> del d[-2]
>>> d[-2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: -2
>>>

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]. 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 ==?

--- Bruce