Skip to content Skip to sidebar Skip to footer

How To Isolate Enums By Making A Distinction On Type?

The following code defines two enums class Insect: BEE = 0x00 WASP = 0x01 BUMBLEBEE = 0x02 class Breakfast: HAM = 0x00 EGGS = 0x01 PANCAKES = 0x02 b = I

Solution 1:

Don't use a custom class for it. Use the stdlib's enum type, they'll do the right thing here.

fromenum import Enumclass Insect(Enum):
    ...

If you want a hard crash:

classMyEnum(Enum):

    def__eq__(self, other):
        iftype(other) isnottype(self):
            raise Exception("Don't do that")
        returnsuper().__eq__(other)

But I caution against this design, since:

  1. enum instances are often compared by identity and not equality
  2. there is little (no?) precedent in Python for equality comparisons raising errors

Solution 2:

A few notes on equality testing, why it shouldn't raise exceptions, and proper type testing.

Why shouldn't == raise exceptions?

Equality testing is used constantly throughout Python, especially in containers: list, dict, and set, to name a few, rely on equality testing to find members, return members, change members, remove members, etc. If your AppleEnum raises every time it is compared to a non-Apple it will break any container it is added to.

Correct way for custom types to fail equality tests (and other comparison tests)

def__eq__(self, other):
    ifnotisinstance(other, self.__class__):
        return NotImplented   # note:  NOT RAISE
    ... comparison here ...

NB. The above tests are already built in to the Enum type.

Proper type testing

If you really, really want to ensure you don't get a type you don't want, and an error should be the result:

var1 = ...
ifnotisinstance(var1, SomeTypeHere):
    raise SomeException

But the above code SHOULD NOT be in any rich comparison method*.


*The rich comparison methods are __eq__, __ne__, __ge__, __gt__, __le__, and __lt__.

Post a Comment for "How To Isolate Enums By Making A Distinction On Type?"