Python 3 字符串选项的类型提示

Python 3 type hint for string options

比方说,我有一个函数,其字符串参数对应于方法名称:

def func(method: str):
    if method not in ('simple_method', 'some_other_method'):
        raise ValueError('Unknown method')

我可以添加所有可能的支持选项(字符串)作为此参数的类型提示吗?例如,像这样的东西(它不起作用,因为在输入中没有 Str):

from typing import Str

def func(method: Str['simple_method', 'some_other_method']):
    ...

仅使用类型提示是不可能的,正确的方法应该是 enums,如下所示:

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

一旦您拥有包含所有可能选项的枚举,您可以提示该函数以便仅接受您的自定义枚举。更多信息 here

示例:

 from typing import NewType

 Colors = NewType('Colors', Color)