python - 输入可能值列表的提示

标签 python type-hinting

这个问题在这里已经有了答案:





Python Typing: Given Set of Values

(2 个回答)


去年关闭。




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

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 .

关于python - 输入可能值列表的提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59874373/

相关文章:

python - 如何有效地从 numpy 数组中提取由索引给出的元素列表?

python - 寻找时间序列数据中的重复模式

python - 尽管包中包含 py.typed 标记,但 stub 文件未包含在分发中

python - Google Cloud 中的 Python 3 类型包返回错误

python - 如何使用Python3在PyCharm中编写多个签名提示

python - 允许 python 装饰器在传递的类中使用时将类作为参数

python - 为什么我在两种方式之间得到长度差异 : dict and array

python - 列表的自定义字符串表示取决于项目数 (Python)

clojure - 尽管 Clojure 中 Java 构造函数有类型提示,但仍出现反射警告

Python 3.6 通用类型提示