可以通过获取可能成员的列表来创建枚举,我这样做是这样的:
# example_issue.py
import enum
yummy_foods = ["ham", "cheese"]
foods = enum.Enum("Foods", yummy_foods)
cheese = foods.cheese
Run Code Online (Sandbox Code Playgroud)
这看起来不错,运行良好,但 mypy 返回
example_issue.py:4: error: Enum() expects a string, tuple, list or dict literal as the second argument
example_issue.py:5: error: "Type[foods]" has no attribute "cheese"
Found 2 errors in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)
mypy 在这里做什么,为什么它不能遵循 that foodscan take any value in yummy_foods?
使用变量yummy_foods对于 mypy 的静态类型检查来说过于动态,请参阅此 GitHub 问题。
如果您更改代码以生成Enum:
foods = enum.Enum("Foods", ["ham", "cheese"])
Run Code Online (Sandbox Code Playgroud)
然后 mypy 将能够找出枚举中存在哪些属性。