键入可能值列表的提示
Type hint for a list of possible values
我有一个可以接受固定值列表的函数:例如
def func(mode="a"):
if mode not in ["a", "b"]:
raise AttributeError("not ok")
有没有办法键入提示它只能是这两个值之一?
我想你想要一个 literal type:
def func(mode="a": Literal["a", "b"]):
if mode not in ["a", "b"]:
raise AttributeError("not ok")
这是在 Python 3.8 中通过 PEP 586 引入的。
我有一个可以接受固定值列表的函数:例如
def func(mode="a"):
if mode not in ["a", "b"]:
raise AttributeError("not ok")
有没有办法键入提示它只能是这两个值之一?
我想你想要一个 literal type:
def func(mode="a": Literal["a", "b"]):
if mode not in ["a", "b"]:
raise AttributeError("not ok")
这是在 Python 3.8 中通过 PEP 586 引入的。