How to test if an Enum member with a certain name exists? How to test if an Enum member with a certain name exists? python-3.x python-3.x

How to test if an Enum member with a certain name exists?


You could use Enum.__members__ - an ordered dictionary mapping names to members:

In [12]: 'One' in Constants.__members__Out[12]: TrueIn [13]: 'Four' in Constants.__members__Out[13]: False


I would say this falls under EAFP (Easier to ask for forgiveness than permission), a concept that is relatively unique to Python.

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

This contrasts with LBYL (Look before you leap), which is what I think you want when you say you are looking for "a more elegant way."

Look before you leap. This coding style explicitly tests for pre-conditions before making calls or lookups. This style contrasts with the EAFP approach and is characterized by the presence of many if statements.

In a multi-threaded environment, the LBYL approach can risk introducing a race condition between “the looking” and “the leaping”. For example, the code, if key in mapping: return mapping[key] can fail if another thread removes key from mapping after the test, but before the lookup. This issue can be solved with locks or by using the EAFP approach.

Therefore based on the documentation, it is actually better to use try/except blocks for your problem.

TL;DR

Use try/except blocks to catch the KeyError exception.


Could use the following to test if the name exists:

if any(x for x in Constants if x.name == "One"):  # Existselse:  # Doesn't Exist

Of use x.value to test for the enum value:

if any(x for x in Constants if x.value == 1):  # Existselse:  # Doesn't Exist