我有一个枚举来表示一个函数的不同可能值。
class A(Enum):
NOT_FOUND = NONE
INAQUATE = NONE
POSITIVE = 1
# Some more
但是,从函数返回此枚举时,
def search_function(target = 1):
if target == 1:
return A.INAQUATE
else:
return A.POSITIVE
返回A.NOT_FOUND
,而不是A.INAQUATE
,这会使程序中断。
Python 3.7.6
>>> from enum import Enum
>>> class A(Enum):
... NOT_FOUND = None
... INAQUATE = None
... POSITIVE = 1
...
>>> def search_function(target = 1):
... if target == 1:
... return A.INAQUATE
... return A.NOT_FOUND
...
>>> search_function()
<A.NOT_FOUND: None>
有没有办法正确返回A.INAQUATE
?
答案 0 :(得分:1)
当Enum
具有重复值时,成员是完全相同的对象-只是由Enum
本身中的两个名称引用:
>>> list(A)
[<A.NOT_FOUND: None>, <A.POSITIVE: 1>]
>>> A.INAQUATE is A.NOT_FOUND
True
最简单的解决方案是给每个成员一个唯一的值。下一个最简单的解决方案是使用aenum
库 1 :
from aenum import Enum, NoAlias
class A(Enum):
#
_settings_ = NoAlias
#
NOT_FOUND = None
INAQUATE = None
POSITIVE = 1
正在使用:
>>> list(A)
[<A.INAQUATE: None>, <A.NOT_FOUND: None>, <A.POSITIVE: 1>]
>>> A.INAQUATE is A.NOT_FOUND
False
NB :使用NoAlias
枚举时,按值查找功能会丢失:
>>> A(1)
Traceback (most recent call last):
...
TypeError: NoAlias enumerations cannot be looked up by value
1 披露:我是Python stdlib Enum
,enum34
backport和Advanced Enumeration (aenum
)库的作者。