Enumeration idioms: Values from different enumerations

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Dec 16 18:31:31 EST 2005


On Fri, 16 Dec 2005 15:16:08 +1100, Ben Finney wrote:

>> As can be seen from the above, you raise an exception when one wants
>> to compare Enums from different enumarations, but it seems a bit
>> strange that different enumerations belong to the same type.
> 
> This does seem a point that could be confusing. Would it be better if
> every Enum instance had its own unique subclass of EnumValue, that was
> used to instantiate values for that enumeration?

That seems to be creating complication for its own sake.


>> I also think it would be more usefull if enums from different
>> enumerations just tested unequal.
> 
> My rationale for this is: The only purpose of an enumeration is to
> have a set of arbitrary unique values within that enumeration. The
> values make no sense in the context of a different enumeration, so I
> see three different comparison results:
> 
>     >>> Weekday.mon == Weekday.mon
>     True
>     >>> Weekday.fri == Weekday.mon
>     False
>     >>> Colour.blue == Weekday.mon
>     [...]
>     enum.EnumValueCompareError: Not values from the same enumeration
> 
> However, I'm aware that this is not how other Python types behave:
> 
>     >>> 23 == 23
>     True
>     >>> 42 == 23
>     False
>     >>> "spam" == 23
>     False
> 
> Is there a semantic difference between these cases? Is that difference
> enough to want different behaviour?

I don't believe so.

It seems reasonable to me for other comparisons such as __lt__ etc.
to fail unless the objects belong to the same enumeration. But equality
and inequality are special. Unordered objects support equality testing.

The question whether Mohammad is greater than or less than the mountain
has no answer, because we don't know how to order the two (by height? by
mass? by religious belief? by economic value? by importance to human
history?). But we can certainly answer the question is Mohammad equal to
the mountain -- the answer is certainly no, no matter how we order them.


>> Because as it is you can't put elements from different enumerations
>> in a list and check with the in operator if a specific enum value is
>> in the list.
>>
>> It could also cause problems for dictionaries, since keys in
>> dictionaries can be tested against a key giving in a subscription.
> 
> These are valid concerns. I can't see how to reconcile these against
> the desire for values from different enums to fail comparison.

Perhaps you are just being over-strict -- soon you'll be writing in Pascal
:-)

Failing order comparisons is reasonable, but why refuse to test for
equality? If you ask "is Monday equal to Blue?" the intuitive answer is
"no", not "my brain just crashed trying to evaluate the answer!".


-- 
Steven.




More information about the Python-list mailing list