【问题标题】:Type hint for a list of possible values [duplicate]键入提示以获取可能值列表 [重复]
【发布时间】:2020-05-09 11:28:30
【问题描述】:

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

def func(mode="a"):
   if mode not in ["a", "b"]:
      raise AttributeError("not ok")

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

【问题讨论】:

  • 使用枚举代替字符串?
  • @jonrsharpe 是的,但是对于这个用例来说,这是很多仪式 :) 我有一种唠叨的感觉,它现在应该是可能的,但我不记得如何

标签: python type-hinting


【解决方案1】:

我想你想要一个literal type:

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

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

【讨论】:

  • 非常感谢,我的 google fu 找到了其他任何东西,但不是那个!
  • 请注意,这需要以下导入:from typing_extensions import Literal
  • @MaiKar 取决于您使用的 Python 版本 - from typing_extensions 如果您需要 3.5-3.7 的反向端口,from typing 在 3.8 及更高版本的标准库中。还有一个来自 PyPI 的 from typing,不知道它支持多少。
  • 我有一个列表:my_list = ["a", "b", "c"],我想将此列表用作值和文字类型。但是,当我执行 Literal[my_list] 时,Literal 会抱怨。你知道我怎样才能有一个预定义列表的文字吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-11
  • 1970-01-01
  • 2020-03-12
  • 2017-05-08
相关资源
最近更新 更多