Returning True if a value is present in an enum; returning false if not
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Isolated
--
Chapters
00:00 Returning True If A Value Is Present In An Enum; Returning False If Not
00:35 Accepted Answer Score 8
00:58 Answer 2 Score 1
01:05 Answer 3 Score 0
01:49 Answer 4 Score 1
02:04 Thank you
--
Full question
https://stackoverflow.com/questions/6553...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #enums
#avk47
ACCEPTED ANSWER
Score 8
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")
ANSWER 2
Score 1
if colour_test in Colour.__members__:
    print("In enum")
else:
    print("Not in enum")
ANSWER 3
Score 1
The simplest thing you can do is add try.. except block where except block will catch the KeyError.
    colour_test = "YELLOW"
    try:
         if Colour[colour_test]:
             print("In enum")
    except KeyError:
        print("Not in enum")
ANSWER 4
Score 0
getattr with the default argument would probably be the easiest way:
gotten = getattr(Colour, "GREEN", None)
if gotten is None:
    # Not in the enum
else:
    # gotten is in the enum
gotten will be None (or whatever you put as the third argument to getattr) if it doesn't exist.
Or, with := to make it a little more succint:
if gotten := getattr(Colour, "GREEN", None):
    # The string is in the enum
else:
    # Not in the enum
@Aplet's suggestion of hasattr is likely more appropriate here in retrospect. I like getattr with a None third argument because a lot of the time, if I'm checking if something has an attribute, I also want to use that attribute after the check. Use hasattr if you only care about whether or not it's there, but getattr is nice if you also want to use the value post-lookup.