Enumeration idioms: Values from different enumerations
steve at REMOVETHIScyber.com.au
Sat Dec 17 00:44:00 CET 2005
On Thu, 15 Dec 2005 23:53:36 -0500, Peter Hansen wrote:
> Ben Finney wrote:
>> These are valid concerns. I can't see how to reconcile these against
>> the desire for values from different enums to fail comparison.
>> Am I alone in my tri-state view of enumeration value comparisons? Can
>> anyone else defend why values from different enumerations should not
> While I'm largely a disinterested bystander, it occurs to me that if you
> look at the reasons behind wanting enumerations in the first place, you
> might find a good reason to defend this view.
> For example, if enumerations are intended to reduce the likelihood of
> certain types of errors (where the use of typical XXXX=3 "constants"
> might be more prone to errors), then perhaps this suggests that passing
> errors silently is bad. That is, 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.
In my opinion, rather than make all enums fail equality testing, two
better solutions would be:
(1) sub-class Enum to have StrictEnum. Enum allows equality testing for
normal Pythonic behaviour. StrictEnum fails equality testing for extra B&D
(2) Expect the user to make an explicit test when they want the stricter
testing. At the moment two different enumerations have the same class, but
Ben could (perhaps) hash the enumeration values to get a unique ID that
distinguishes one enumeration from another. Or some other strategy that
would allow something like:
if value.from_same_enumeration(other) and value == other
for value and other both enums.
Of the two, I suspect that (1) is far less work for both Ben and the
people using his class, although for introspection purposes it might be
nice to have some sort of unique enumeration ID. That could even be
something as simple as a tuple of the enumeration values.
More information about the Python-list