键入可能值列表的提示

Chr*_*uer 14 python type-hinting

我有一个可以采用固定值列表的函数:例如

def func(mode="a"):
   if mode not in ["a", "b"]:
      raise AttributeError("not ok")
Run Code Online (Sandbox Code Playgroud)

有没有办法输入提示它只能是这两个值之一?

jon*_*rpe 27

我认为你想要一个文字类型

def func(mode = "a": Literal["a", "b"]):
    if mode not in ["a", "b"]:
        raise AttributeError("not ok")
Run Code Online (Sandbox Code Playgroud)

这是通过PEP 586在 Python 3.8 中引入的。

  • @MaiKar,这取决于您使用的 Python 版本 - 如果您需要 3.5-3.7 的向后移植,请使用“fromtyping_extensions”,如果需要 3.8 及更高版本,则需要标准库中的“fromtyping”。PyPI 也有一个“fromtypes”,不确定支持多少。 (3认同)