In Python 3.6 and aenum 2.0 https://pypi.python.org/pypi/aenum12 (which is compatible with 2.7 and 3.0+) a new method has been added: _missing_
2.
该方法在之前调用ValueError
引发是为了让自定义代码有机会尝试找到枚举成员by value。不幸的是,这使得它不适合您的用例——按名称查找。
Fortunately, aenum
has the extra option of defining a _missing_name_
method3 which will be called when name lookup fails.
您上面的代码应如下所示:
from aenum import Enum
class Label(Enum):
RedApple = 1
GreenApple = 2
@classmethod
def _missing_name_(cls, name):
for member in cls:
if member.name.lower() == name.lower():
return member
并在使用中:
>>> Label['redapple']
<Label.RedApple: 1>
如果卡住使用 3.6 stdlib(或想要与其保持兼容),您可以 (ab)使用_missing_
but:
- 你必须做
Label('redapple')
相反(圆括号,而不是方括号),并且
- 您将反对枚举的设计(“redapple”是名称,而不是值)
1 Disclosure: I am the author of the Python stdlib Enum https://docs.python.org/3/library/enum.html, the enum34 backport https://pypi.python.org/pypi/enum34, and the Advanced Enumeration (aenum) https://pypi.python.org/pypi/aenum library.
2 enum34 https://pypi.python.org/pypi/enum34 does not have these improvements as it is only being maintained for bug fixes.
3 _missing_value_
is preferred in aenum
as it is more explicit about what it is checking, but it falls back to _missing_
for compatibility with the stdlib.
4 aenum v2.0.2 has a bug where _missing_
is called for both values and names if _missing_name_
has not been overridden -- this is fixed in v2.0.3+.