python - How to type-hint an Enum of strings in Python
问题描述
I was curious how I'd type-hint an enumeration of strings, for example: ["keyword1", "keyword2"]
I'd want some variable, v, to be equal to any of these string literals. I could accomplish this with a union of literals - Union[Literal["keyword1"], Literal["keyword2"]] but it'd be make maintainability difficult if one of these keywords gets changed in the future. Ideally, I'd want to define things like this:
class Keywords(enum):
keywordOne = "keyword1"
keywordTwo = "keyword2"
v: valueOf[Keywords] = Keywords.keywordOne.value # v = "keyword1"
But I'm not sure how to accomplish something like this in MyPy
解决方案
你快到了。您正在寻找的似乎是一个自定义枚举对象,它本身是类型化的,然后键入指示该枚举使用的注释。像这样的东西:
from enum import Enum
from typing import Literal
class CustomKeyword(Enum):
keywordOne: Literal["keyword1"] = "keyword1"
keywordTwo: Literal["keyword2"] = "keyword2"
v: CustomKeyword = CustomKeyword.keywordOne
这不会给你预期的结果吗?
推荐阅读
- java - How to add data in Multiple Array lists?
- javascript - Why does the react-admin menu bar not redirect me to the correct resource view?
- javascript - Why does my functions.php keep crashing (wordpress)? - new to Javascript
- javascript - 将子进程输出传递到终端窗口,但也在变量中捕获
- r - 如何将函数参数从 for/if 循环传递到代码体?
- sql - 按计算的列标签进行的列名分组无效
- sql - SQL 函数卡住并且不会返回值
- python-3.x - 根据 Pandas 中提取的值和字符串过滤行
- python - PyCharm Unable to Install Packages
- c++ - How to include headers into my library without exposing them to users?