Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning True if a value is present in an enum; returning false if not [duplicate]

Tags:

python

enums

I apologise if I'm missing anything obvious; is there a way to see if a value is in an enum which returns True if it is, False if not? For example, if I take the following enum from the python documentation,

from enum import Enum
class Colour(Enum):
     RED = 1
     GREEN = 2
     BLUE = 3

is there any way to do the following action, or an equivalent, without an exception being raised:

colour_test = "YELLOW"
if Colour[colour_test]:
    print("In enum")
else:
    print("Not in enum")
## Output wanted - "Not in enum"
## Actual output - KeyError: "YELLOW"

I know that I can use try;except statements, but I'd prefer not to in this situation as I'd like to use this conditional with some others.

like image 910
Ace in the hole Avatar asked Dec 23 '22 16:12

Ace in the hole


2 Answers

Enums have a __members__ dict that you can check:

if colour_test in Colour.__members__:
    print("In enum")
else:
    print("Not in enum")

You can alternatively use a generalized approach with hasattr, but this returns wrong results for some non-members like "__new__":

if hasattr(Colour, colour_test):
    print("In enum")
else:
    print("Not in enum")
like image 67
Aplet123 Avatar answered May 24 '23 22:05

Aplet123


if colour_test in Colour.__members__:
    print("In enum")
else:
    print("Not in enum")
like image 20
scenox Avatar answered May 24 '23 22:05

scenox