验证值在Python枚举值中

时间:2019-01-10 10:24:59

标签: python enums

我继承了看起来像这样的代码。

class Clients(IntEnum):
    ALICE = 1
    BOB = 2
    PETER = 3
    CHERYL = 4
    LARRY = 5

if client_id == 1:
    client_info = find_info(Clients.ALICE.value)
elif client_id == 2:
    client_info = find_info(Clients.BOB.value)
elif client_id == 3:
    client_info = find_info(Clients.PETER.value)
elif client_id == 4:
    client_info = find_info(Clients.CHERYL.value)
elif client_id == 5:
    client_info = find_info(Clients.LARRY.value)
else:
    raise Exception('Unknown client_id.')

我对Python枚举没有太多经验,所以我迫切希望将其简化为以下形式(伪代码):

if client_id in dict(Clients).keys():
    client_info = find_info(client_id)
else:
    raise Exception('Unknown client_id.')

我尝试了Clients.__members__Clients.__dict__,但是它们的行为与我期望的不太一样,返回了称为mappingproxy的东西。

我可以做'ALICE' in Clients.__members__,但是值是否相等?如果没有,是否有更优雅的方式编写这段代码?

2 个答案:

答案 0 :(得分:2)

您只能在一个简单的元组(或列表)中存储值,并使用枚举允许按值访问的事实:

values = tuple(item.value for item in Clients)

if client_id in values:
    # do something with Clients(client_id)
else:
    # print message or raise exception

或者您可以使用字典将值映射到枚举成员:

mapping = dict((item.value, item) for item in Clients)

if client_id in mapping:
    # do something with mapping[client_id]
else:
    # print message or raise exception

答案 1 :(得分:1)

try:
    client_info = find_info(Clients(client_id))
except ValueError:
    # customize error message
    raise Exception('Unknown client_id.')