我试图限制枚举仅具有一种类型的所有成员值。比如我想要
class MyTypedEnum(Enum):
MEMBER_1= 1
MEMBER_2= 2
...
成为其成员值中仅包含
int
的枚举。
因此,当我将
MyTypedEnum.MEMBER_X.value
写入 IDE 时,它会识别出该类型确实是 int
。
编辑:这显然是一个带有
int
的简单示例,但我想在其位置使用任何类型。
据我所知,Python 打字规范没有解决这个问题。
这实际上取决于您的 IDE 和静态分析工具。如果我这样做:
from enum import Enum
class Foo(Enum):
bar: int = 1
baz: int = 2
reveal_type(Foo.bar.value)
value: int = Foo.bar.value
然后
mypy
就很好理解了,并给了我:
(py39) Juans-MacBook-Pro:~ juan$ mypy test.py
test.py:6: note: Revealed type is "builtins.int"
但是,
pyright
给了我一个错误:
(py39) Juans-MacBook-Pro:~ juan$ pyright test.py
Found 1 source file
/Users/juan/Coursera/test.py
/Users/juan/Coursera/test.py:4:16 - error: Expression of type "Literal[1]" cannot be assigned to declared type "Literal[Foo.bar]"
"Literal[1]" cannot be assigned to type "Literal[Foo.bar]" (reportGeneralTypeIssues)
/Users/juan/Coursera/test.py:5:16 - error: Expression of type "Literal[2]" cannot be assigned to declared type "Literal[Foo.baz]"
"Literal[2]" cannot be assigned to type "Literal[Foo.baz]" (reportGeneralTypeIssues)
/Users/juan/Coursera/test.py:6:13 - info: Type of "Foo.bar.value" is "int"
2 errors, 0 warnings, 1 info
Completed in 0.819sec
我想 mypy 是特殊大小写的枚举。
我在pyright
github中发现了这个半相关问题。
并且 这是来自
mypy
的相关 PR,他们为无类型枚举值添加了推理功能。