Enumeration idioms: Values from different enumerations

Antoon Pardon apardon at forel.vub.ac.be
Fri Dec 16 08:15:36 EST 2005


> Antoon Pardon wrote:
>> Ben Finney wrote:
>> > Would it be better if every Enum instance had its own unique
>> > subclass of EnumValue, that was used to instantiate values for
>> > that enumeration?
>>
>> If you decide on keeping the current behaviour when comparing
>> values of different enumerations, I would definitely answer
>> yes.
>
> If values from different enums were to be compared for equality (and
> not raise an exception), would it still be good to have those values
> be of different types?

Yes, because people who would need a quick and dirty ordering
could then use the type of the object as a first key.

>> The only advise I have here is look at PEP 3000 that states:
>
>> Comparisons other than == and != between disparate types will raise
>> an exception unless explicitly supported by the type.
>
>> Which seem to imply that == and != should not raise an exception but
>> >, >=, <, <= should.
>
> This seems like a good guide for a policy on enumerations.
>
> How about this proposal:
>
> Enumerations (instances of Enum) contain a fixed sequence of unique,
> arbitrary values. The values within an enumeration are instances of a
> type (subclass of EnumValue), unique to that enumeration.
>
> Values from an enumeration can be compared for equality (__eq__,
> __ne__) with any other value, and will only return True for the same
> value from the same enumeration, otherwise False. Other comparison
> operations can be performed only with values from the same
> enumeration, otherwise an exception (EnumValueCompareError, subclass
> of ValueError) is raised.

Looks good to me.

> This might result in the following simplistic implementation::
>
>     class EnumValue(object):
>         # ...
>
>         def __eq__(self, other):
>             result = False
>             if self is other:
>                 result = True
>             return result
>
>         def __cmp__(self, other):
>             if isinstance(other, EnumValue):
>                 if is_same_enumeration(self, other):
>                     result = cmp(self.index, other.index)
>             else:
>                 raise EnumValueCompareError(self, other)
>             return result
>
> This gives meaning to the "equal value" comparisons, but ensures that
> other comparisons are errors.
>
> Comments so far?

Isn't there an else missing? I have the impression that if you compare
two enums from a different enumeration __cmp__ will raise UnboundLocalError.

-- 
Antoon Pardon



More information about the Python-list mailing list