Enumeration idioms: Values from different enumerations

Antoon Pardon apardon at forel.vub.ac.be
Fri Dec 16 11:18:39 CET 2005

Op 2005-12-16, Ben Finney schreef <bignose at polar.local>:
> Mike Meyer <mwm at mired.org> writes:
>> Peter Hansen <peter at engcorp.com> writes:
>>> That is, [perhaps] trying to compare enumerations that should not
>>> be compared *is* an error (raising an exception) *because* the
>>> whole point of enumerations is to avoid errors in such cases.
>> Except it might not be an error. For instance, if I've got a list of
>> enum objects taken from various types (say I've got one set of enums
>> for days of the week, another for months of the year, and so on, and
>> which I use depends on whether the user wants to select days of the
>> week, months of the year, etc), it makes perfect sense to want to know
>> if a specific enum value is in the list, and the obvious way to check
>> it is with "my_value in enum_list". That won't work if you raise an
>> exception - it takes a relatively convoluted bit of code to make this
>> test.
> The 'enum' package in Cheeseshop doesn't do that. Enumerations are
> sequences (of unique arbitrary values), that can be iterated and tested
> for membership.

Sure but we do have this:

>>> from enum import Enum
>>> day = Enum('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun')
>>> col = Enum('red', 'green', 'blue')
>>> lst= [day.mon, col.red]
>>> col.blue in lst
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "enum.py", line 100, in __cmp__
    raise EnumValueCompareError(self, other)
enum.EnumValueCompareError: Not values from the same enumeration:
(EnumValue(<enum.Enum object at 0x402181ac>, 2, 'blue'),
EnumValue(<enum.Enum object at 0x4020c36c>, 0, 'mon'))

> What's being discussed here is what happens when comparing the *values*
> from the enumeration.
>> Python generally uses '==' to mean "is the same value".  To do that,
>> a simple true/false return is enough. In raising an exception,
>> you're making '==' carry an extra meaning (I'm not sure *what* that
>> is, though).
> The problem with "is the same value" as an explanation for '==' is
> that it doesn't help in cases such as::
>     >>> ShirtSize = Enum('small', 'medium', 'large')
>     >>> AppleSize = Enum('small', 'large')
> What should be the result of this comparison::
>     >>> ShirtSize.small == AppleSize.small
> Are they "the same value"? They're both "small" (and they both coerce
> to the same string value, and in this case the same integer value).
> If not, is 'False' the right way to indicate that?

I would agree 'False' is the right answer here.

Antoon Pardon

More information about the Python-list mailing list