【问题标题】:Python type hinting for List with possible values具有可能值的 List 的 Python 类型提示
【发布时间】:2021-08-13 19:31:11
【问题描述】:

我有一个函数:

def foo(a, b):
  return [a, b]

我想为返回值添加类型提示,如您所见,我的函数可以返回 [srt, int][str, str][int, int] 等。

我试过了:

def foo(a, b) -> List[str, int]:
  return [a, b]

但它不起作用。

如何在列表中指定我的函数可以返回的可能值?

【问题讨论】:

    标签: python python-3.x type-hinting


    【解决方案1】:

    您可以使用Union。具体来说,Union[X, Y] 表示 X 或 Y。

    from typing import List, Union
    
    def foo(a, b) -> List[Union[str, int]]:
        return [a, b]
    

    如果您的函数可以返回包含任何元素的列表,则使用Any(表示无约束类型的特殊类型):

    from typing import Any, List
    
    def foo(a, b) -> List[Any]:
        return [a, b]
    

    【讨论】:

      猜你喜欢
      • 2019-07-03
      • 2023-02-24
      • 2021-09-13
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 2017-03-27
      • 2021-08-29
      • 2020-09-26
      相关资源
      最近更新 更多