如何测试具有特定名称的枚举成员是否存在?

2024-06-08 08:22:06 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python3.4,我想测试枚举类是否包含具有特定名称的成员。

示例:

class Constants(Enum):
    One = 1
    Two = 2
    Three = 3

print(Constants['One'])
print(Constants['Four'])

给出:

Constants.One
  File "C:\Python34\lib\enum.py", line 258, in __getitem__
    return cls._member_map_[name]
KeyError: 'Four'

我可以捕捉到KeyError,并将异常作为存在的指示,但也许有一种更优雅的方式?


Tags: 名称示例lib成员enumoneclassfile
3条回答

我认为这属于EAFP(请求宽恕比请求许可更容易),这是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.

这与LBYL(三思而后行)形成了鲜明对比,当你说你在寻找“一种更优雅的方式”时,我想这正是你想要的

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.

因此,根据文档,最好使用try/except块来解决问题。

TL;DR

使用try/except块捕获KeyError异常。

您可以使用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

可以使用以下命令测试名称是否存在:

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

使用x.value测试枚举值:

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

相关问题 更多 >