[Python-ideas] Yet another enum proposal :)

Alex Stewart foogod at gmail.com
Sat Feb 23 01:01:30 CET 2013


On Fri, Feb 22, 2013 at 3:45 PM, Alexandre Zani <alexandre.zani at gmail.com>wrote:

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

Actually, not really.  The only requirement in Python is that if two
objects compare equal, they need to have the same hash value, but there is
no requirement the other direction (indeed, that would be a problem in many
cases as the domain of hash values is inherently much smaller than the
domain of all possible object data, so it must be expected that you will
get hash duplication from time to time, no matter what method you use for
calculating the hashes).

In the case of pure Enums, they're just singleton object instances, so they
hash the same as any other object, which works pretty much as one would
expect.

In the case of TypeEnums, since they do compare equal to the underlying
value, they must also hash the same. However hashes are just a "hint":  Two
objects can hash the same but not compare equal, in which case they will be
considered to be different objects when used as dictionary keys, etc.
 There is actually an example of this in the examples.py I put up in github
with the reference code.  It creates a dictionary with two keys, which are
two different Enums, which both use the same int value.  Because they do
not compare equal, they are treated as different keys by Python, as I think
most people would expect..

--Alex
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130222/b6894bcf/attachment.html>


More information about the Python-ideas mailing list