[Python-ideas] Yet another enum proposal :)

Alexandre Zani alexandre.zani at gmail.com
Sat Feb 23 00:45:32 CET 2013


On Fri, Feb 22, 2013 at 3:16 PM, Ethan Furman <ethan at stoneleaf.us> wrote:

> 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:
>

One feature of the implementation is that enum values from different enum
classes will never equal each other. It would be very weird for them to
have identical hashes.


>
> --> 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~
> ______________________________**_________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/**mailman/listinfo/python-ideas<http://mail.python.org/mailman/listinfo/python-ideas>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130222/5403a8a3/attachment.html>


More information about the Python-ideas mailing list