Using Python 3.4 I want to test whether an Enum class contains a member with a certain name.
Example:
class Constants(Enum): One = 1 Two = 2 Three = 3 print(Constants['One']) print(Constants['Four'])
gives:
Constants.One File "C:\Python34\lib\enum.py", line 258, in __getitem__ return cls._member_map_[name] KeyError: 'Four'
I could catch the KeyError
and take the exception as indication of existence but maybe there is a more elegant way?
toList()). contains(aString); EventNames is the name of the enum while getEvent() is what returns the associated string value of each enum member.
You could use Enum.__members__
- an ordered dictionary mapping names to members:
In [12]: 'One' in Constants.__members__ Out[12]: True In [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.
Use try
/except
blocks to catch the KeyError
exception.
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