Python 类型提示枚举成员值

Dze*_*i96 2 python types python-3.x

我试图限制枚举仅具有一种类型的所有成员值。例如,我想要

class MyTypedEnum(Enum):
    MEMBER_1= 1
    MEMBER_2= 2
    ...
Run Code Online (Sandbox Code Playgroud)

是一个枚举,int其成员值中只有 s。

因此,当我写入MyTypedEnum.MEMBER_X.valueIDE 时,它会识别出该类型确实是int.

编辑:这显然是一个简单的示例int,但我想在其位置使用任何类型。

jua*_*aga 5

据我所知,Python类型规范没有解决这个问题。

\n

这实际上取决于您的 IDE 和静态分析工具。如果我做:

\n
from enum import Enum\n\nclass Foo(Enum):\n    bar: int = 1\n    baz: int = 2\n\nreveal_type(Foo.bar.value)\nvalue: int = Foo.bar.value\n
Run Code Online (Sandbox Code Playgroud)\n

然后mypy就很好理解了,并给了我:

\n
(py39) Juans-MacBook-Pro:~ juan$ mypy test.py\ntest.py:6: note: Revealed type is "builtins.int"\n
Run Code Online (Sandbox Code Playgroud)\n

但是,pyright给我一个错误:

\n
(py39) Juans-MacBook-Pro:~ juan$ pyright test.py\nFound 1 source file\n/Users/juan/Coursera/test.py\n  /Users/juan/Coursera/test.py:4:16 - error: Expression of type "Literal[1]" cannot be assigned to declared type "Literal[Foo.bar]"\n  \xc2\xa0\xc2\xa0"Literal[1]" cannot be assigned to type "Literal[Foo.bar]" (reportGeneralTypeIssues)\n  /Users/juan/Coursera/test.py:5:16 - error: Expression of type "Literal[2]" cannot be assigned to declared type "Literal[Foo.baz]"\n  \xc2\xa0\xc2\xa0"Literal[2]" cannot be assigned to type "Literal[Foo.baz]" (reportGeneralTypeIssues)\n  /Users/juan/Coursera/test.py:6:13 - info: Type of "Foo.bar.value" is "int"\n2 errors, 0 warnings, 1 info\nCompleted in 0.819sec\n
Run Code Online (Sandbox Code Playgroud)\n

我想 mypy 是特殊情况的枚举。

\n

我在github中发现了这个半相关的问题pyright

\n

是一个相关的 PR,mypy他们在其中添加了针对非类型化枚举值的推理功能。

\n