【问题标题】:Python 3 type hint for string options [duplicate]字符串选项的 Python 3 类型提示 [重复]
【发布时间】:2020-01-26 14:47:57
【问题描述】:

假设我有一个函数,其字符串参数对应于方法名称:

def func(method: str):
    if method not in ('simple_method', 'some_other_method'):
        raise ValueError('Unknown method')

我可以添加所有可能支持的选项(字符串)作为该参数的类型提示吗?例如,像这样的东西(由于没有输入 Str ,所以不起作用):

from typing import Str

def func(method: Str['simple_method', 'some_other_method']):
    ...

【问题讨论】:

  • 您可能的方法名称似乎是enum,所以您可以查看stackoverflow.com/questions/52624736/…
  • 重要的是,开发人员从不遵循提示:P
  • typing.Literal 这将允许你指定def func(method: Literal['simple_method', 'some_other_method']): ... 你可以像这样得到它from typing import Literal

标签: python type-hinting


【解决方案1】:

仅靠类型提示是不可能的,正确的方法应该是enums,如下所示:

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

一旦你有一个包含所有可能选择的枚举,你可以提示函数以便只接受你的自定义枚举。更多信息here

例子:

 from typing import NewType

 Colors = NewType('Colors', Color)

【讨论】:

  • 作为同时使用提示和枚举的人,枚举对于单个函数的简单选项来说可能是多余的。
猜你喜欢
  • 2020-01-26
  • 2015-08-15
  • 2013-10-12
  • 1970-01-01
  • 2020-09-02
  • 1970-01-01
  • 2016-08-29
  • 2015-08-10
相关资源
最近更新 更多