将枚举转换为 Python 中的列表

Convert an enum to a list in Python

我有一个这样定义的枚举:

def make_enum(**enums):
    return type('Enum', (), enums)

an_enum = make_enum(first=1, second=2)

稍后我想检查一下,我在函数中用作参数的值是否是 an_enum 的一部分。通常我会这样做

assert 1 in to_list(an_enum)

如何将枚举对象 an_enum 转换为列表?如果那不可能,我如何检查值 "is part of the enum"?

How can I convert the enum object an_enum to a list?

>>> [name for name in dir(an_enum) if not name.startswith('_')]
['first', 'second']

How can I check if a value "is part of the enum"?

>>> getattr(an_enum, 'first')
1
>>> getattr(an_enum, '1')
Traceback [...] 
AttributeError: type object 'Enum' has no attribute '1'

我不确定你为什么要像你这样定义枚举,有支持的功能方法可以做到这一点:

en_enum = Enum('Numbers', {'first': 1, 'second': 2})

如果这符合您的需要,您可以这样做

>>> en_enum(1)
<Numbers.first: 1>

>>> en_enum(3)
ValueError: 3 is not a valid Numbers

实际上不是会员检查,但你不需要任何特殊的methods/transformers

Python 的 Enum 对象对每个 Enum 成员都有内置的 enumerable.nameenumerable.value 属性。

an_enum = Enum('AnEnum', {'first': 1, 'second': 2})


[el.value for el in an_enum]
# returns: [1, 2]

[el.name for el in an_enum]
# returns: ['first', 'second']

Sidenode:小心assert。如果有人使用 python -O 运行您的脚本,断言永远不会失败。

检查一个值是否是枚举的一部分:

if 1 in [el.value for el in an_enum]:
    pass