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.
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")
if colour_test in Colour.__members__:
print("In enum")
else:
print("Not in enum")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With