Ian*_*Ian 5 python enums types mypy
我很好奇如何键入提示字符串枚举,例如:[“keyword1”,“keyword2”]
我希望某个变量 v 等于这些字符串文字中的任何一个。我可以通过文字的联合来完成此操作 - Union[Literal["keyword1"], Literal["keyword2"]] 但如果将来其中一个关键字发生更改,那么维护性将会变得困难。理想情况下,我想定义这样的事情:
class Keywords(enum):
keywordOne = "keyword1"
keywordTwo = "keyword2"
v: valueOf[Keywords] = Keywords.keywordOne.value # v = "keyword1"
Run Code Online (Sandbox Code Playgroud)
但我不知道如何在 MyPy 中完成这样的事情
你快到了。看起来您正在寻找的是一个自定义枚举对象,它本身是类型化的,然后类型注释来指示该枚举的使用。像这样的东西:
from enum import Enum
from typing import Literal
class CustomKeyword(Enum):
keywordOne: Literal["keyword1"] = "keyword1"
keywordTwo: Literal["keyword2"] = "keyword2"
v: CustomKeyword = CustomKeyword.keywordOne
Run Code Online (Sandbox Code Playgroud)
这不会给你预期的结果吗?