[Python-Dev] PEP 435 -- Adding an Enum type to the Python standard library

Barry Warsaw barry at python.org
Fri Apr 12 16:50:44 CEST 2013


On Apr 12, 2013, at 09:58 AM, R. David Murray wrote:

>> The ``Enum`` class supports iteration.  Iteration is defined as the
>> sorted order of the item values::
>> 
>>     >>> class FiveColors(Enum):
>>     ...     pink = 4
>>     ...     cyan = 5
>>     ...     green = 2
>>     ...     blue = 3
>>     ...     red = 1
>>     >>> [v.name for v in FiveColors]
>>     ['red', 'green', 'blue', 'pink', 'cyan']
>
>[...]
>
>> Ordered comparisons between enumeration values are *not* supported.  Enums
>> are
>> not integers (but see `IntEnum`_ below)::
>> 
>>     >>> Colors.red < Colors.blue
>>     Traceback (most recent call last):
>>     ...
>>     NotImplementedError
>>     >>> Colors.red <= Colors.blue
>>     Traceback (most recent call last):
>>     ...
>>     NotImplementedError
>>     >>> Colors.blue > Colors.green
>>     Traceback (most recent call last):
>>     ...
>>     NotImplementedError
>>     >>> Colors.blue >= Colors.green
>>     Traceback (most recent call last):
>>     ...
>>     NotImplementedError
>
>This is the part that I don't understand.  Enums *clearly* have an
>ordering, since the iteration order is defined and stable.  Why should
>I not be allowed to compare values from the same Enum type?  There are
>certainly use cases where that is very useful.

Nick brought this up in private email, and my response was basically that
iteration order for Enums should not be guaranteed, even if that happens to
work in the current implementation.  The reason why it works in the current
implementation is purely to provide predictable reprs.

Of course, we could sort the values for the repr and remove the sorted() call
in EnumMetaclass.__iter__() but then we would have to add it back for
IntEnums, since we *do* want to make explicit iteration order guarantees for
IntEnums, as they also have full rich comparisons.  I'm just not sure it's
worth it from an implementation point of view.

I will update the PEP to make this more clear.

>In talking to an existing internet protocol it would be natural to use
>IntEnum and this issue would not arise, but I have recently worked on
>an application that had *exactly* the above sort of enumeration used
>internally, when it would have been totally appropriate to use Enum rather
>than IntEnum.  The ap has several places where an ordered comparison
>against the enum is used to check if a code is in the error range or not.

Why Enums and not IntEnums?  Enums will not have ordered comparisons, but
IntEnums will.

-Barry


More information about the Python-Dev mailing list