pythonpython-3.xenums

Check if value is in enum fails


I am super confused how neither of these work. Can someone help me understand what's going on and why it prints "BAD" and "Value does not exist"?

from enum import Enum

class EventType(Enum):
    USER_LOGIN = 1,
    USER_LOGOUT = 2,

    @classmethod
    def has_value(cls, value):
        return value in cls._value2member_map_

eventType = 2
if not EventType.has_value(eventType):
    print("BAD")
else:
    print("GOOD")
    
if eventType in EventType.__members__.values():
    print("Value exists")
else:
    print("Value does not exist")

Solution

  • As @msanford said in the comments, remove the trailing commas from your values -- they are creating tuples.