Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 751
Trilarion Avatar asked Apr 22 '15 11:04

Trilarion


People also ask

How do you check if the given string is a part of an enum?

toList()). contains(aString); EventNames is the name of the enum while getEvent() is what returns the associated string value of each enum member.


2 Answers

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 
like image 82
vaultah Avatar answered Sep 25 '22 06:09

vaultah


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.

like image 37
pzp Avatar answered Sep 24 '22 06:09

pzp