3

I want to define multiple strings for an enum variable and compare the variable either against a string or an enum type. I am currently doing the following:

from enum import Enum


class Ordinal(str, Enum):
    NORTH = ['north', 'NORTH', 'n']
    SOUTH = ['south', 'SOUTH', 's']


input_by_user_1 = 'n'
input_by_user_2 = Ordinal.NORTH
print(input_by_user_1 in Ordinal.NORTH)  #True
print(input_by_user_2 in Ordinal.NORTH)  #True
print(input_by_user_1 == Ordinal.NORTH)  #False
print(input_by_user_2 == Ordinal.NORTH)  #True

However, I do not find the in key word nice to understand. I would rather prefer the option using == but this does not work because I defined a list. Is there a better way to do that?

Solution:

The answer was to use the MultiValueEnum class. Then I can use the following code:

from aenum import MultiValueEnum


class Ordinal(MultiValueEnum):
    NORTH = 'north', 'NORTH', 'n'
    SOUTH = 'south', 'SOUTH', 's'


input_by_user_1 = 'n'
input_by_user_2 = Ordinal.NORTH
print(Ordinal(input_by_user_1) == Ordinal.NORTH)  #True
print(Ordinal(input_by_user_2) == Ordinal.NORTH)  #True
David Zanger
  • 333
  • 1
  • 3
  • 8

1 Answers1

-1

You can override the equality operator!

from enum import Enum

class Ordinal(str, Enum):
    NORTH = ['north', 'NORTH', 'n']
    SOUTH = ['south', 'SOUTH', 's']
    
    def __eq__(self, other):
        return other in self.__dict__['_value_']