首页 > 解决方案 > 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

标签: pythontypesenumsmypy

解决方案


你快到了。您正在寻找的似乎是一个自定义枚举对象,它本身是类型化的,然后键入指示该枚举使用的注释。像这样的东西:

from enum import Enum
from typing import Literal

class CustomKeyword(Enum):
   keywordOne: Literal["keyword1"] = "keyword1"
   keywordTwo: Literal["keyword2"] = "keyword2"

v: CustomKeyword = CustomKeyword.keywordOne

这不会给你预期的结果吗?


推荐阅读