[Python-ideas] Yet another enum proposal :)

Ethan Furman ethan at stoneleaf.us
Sat Feb 23 00:16:45 CET 2013


On 02/22/2013 11:25 AM, Alex Stewart wrote:
> Ok, so at the risk of muddying the waters even more, I've put together yet another possible way to do enums, and would
> be interested to hear comments..

Largely similar to my own implementation -- so of course I like it!  :)


> A few other notable properties:
>
>   * Enum values are hashable, so they can be used as dict keys, etc.

Problem here:  should we have our enums hash the same as the underlying value?  Consider:

--> import yaenum

--> class Color(yaenum.Enum):
...     black
...     red
...     green
...     blue
...

--> class Literature(yaenum.Enum):
...    scifi
...    fantasy
...    mystery
...    pop
...

--> Color.black
Color('black', value=0)

--> Literature.scifi
Literature('scifi', value=0)

--> black = Color.black

--> scifi = Literature.scifi

--> black == 0
True

--> hash(black)
0

--> scifi == 0
True

--> hash(scifi)
0

--> black == scifi
False

--> hash(0)
0

--> huh = dict()
--> huh[black] = 9
--> huh
{Color('black', value=0): 9}

--> huh[0]
9
--> huh[scifi]
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
KeyError: Literature('scifi', value=0)

--> huh[scifi] = 11
--> huh
{Color('black', value=0): 9, Literature('scifi', value=0): 11}

--> huh[0]
9

--> del huh[0]
--> huh[0]
11

 From a practicality standpoint the question is:  How likely is it to use different enum classes as keys?

--
~Ethan~



More information about the Python-ideas mailing list