[Python-ideas] Yet another enum proposal :)

Bruce Leban bruce at leapyear.org
Sat Feb 23 00:57:25 CET 2013


On Fri, Feb 22, 2013 at 3:16 PM, Ethan Furman <ethan at 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130222/0bc89270/attachment.html>


More information about the Python-ideas mailing list