场景
这要是讲函数注释的用法
没有返回值
def function(ver: str):
print(var)
单个返回值
def function(ver: str) -> dict:
a=[ver,ver,ver]
return a
多个返回值
您总是返回一个对象;使用return one, two只返回一个元组。
所以是的,-> Tuple[bool, str] 完全正确。
只有类型Tuple允许您指定元素的固定数量,每个元素都有一个不同的类型。
如果函数生成的返回值数目是固定的值,尤其是当这些值是特定的、不同的类型时,则应该始终返回元组。
from typing import Tuple
def function(ver: str) -> Tuple[str, str, bool]:
a=ver
b="BBB"
c=True
return a, b, c
A,B,C=function("hello")
print(A)
print(B)
print(C)
其他序列类型对于可变数量的元素应该有one类型规范,因此typing.Sequence在这里不合适。
另见 What's the difference between lists and tuples?
Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order.
Python 的类型提示系统遵循这一原则,目前没有语法来指定固定长度的iterable,并且在特定位置包含特定类型。
如果您必须指定任何iterable都可以,那么最好的方法是:
-> Iterable[Union[bool, str]]
此时,调用者可以期望布尔值和字符串以任意顺序,长度未知(介于0和无穷大之间)。