使用类型检查来检查字符串是否仅具有某些值

Use type checking to check that string is of certain values only

假设我有一个 python 函数 def func_AB(param1: str)param1 只能取值 AB。如果它采用任何其他字符串值,则会出现错误。

发生这种情况时,是否可以使用 python 类型检查来给出错误?目前,我使用 assert 检查 param1 是否包含有效的字符串值。

我正在使用 python 3.8.5

您正在寻找 Literal

from typing import Literal

def func_AB(param1: Literal['A', 'B']):
    ...