Python 类型提示枚举成员值

Python type hint enum member value

我试图限制一个枚举,使其所有成员值都只有一种类型。比如我要

class MyTypedEnum(Enum):
    MEMBER_1= 1
    MEMBER_2= 2
    ...

成为其成员值中只有 int 的枚举。

因此,当我将MyTypedEnum.MEMBER_X.value写入我的IDE时,它识别出类型确实是int

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

据我所知,Python typing spec 没有解决这个问题。

这实际上取决于您的 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 是特殊外壳枚举。

我找到了 this semi-related issue in the pyright github

here is a related PR from mypy 他们为未类型化的枚举值添加了推理功能。