繁体   English   中英

Python 类型提示列表与可能的值

[英]Python type hinting for List with possible values

我有一个 function:

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

我想为返回值添加类型提示,例如,您可以看到我的 function 可以返回[srt, int][str, str][int, int]等。

我试过了:

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

但它不起作用。

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

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

from typing import List, Union

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

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

from typing import Any, List

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM