python >= 3.5 才支持hint
最基本的形式
def foo(a: int, b: float) -> float:
return a + b
print(foo(1, 2))
如果是参数可能是多种形式,输出也是多个返回值
from typing import Union, Tuple
def foo(a: Union[int, float], b: Union[int, float]) -> Tuple[Union[int, float], float]:
return a + b, float(a)
print(foo(1, 2))
列表中为某种类型的变量
from typing import Union, Tuple, List
def foo(a: List[Union[str, int]]) -> str:
sum = ""
for i in a:
if isinstance(i, int):
sum += str(i)
else:
sum += i
return sum
print(foo([1, "+", 1, "=", 2]))
迭代器形式
from typing import Iterator
def fib(n: int) -> Iterator[int]:
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
参考:
https://www.jianshu.com/p/0227232239b5
https://blog.csdn.net/chuchus/article/details/77891128
https://stackoverflow.com/questions/33945261/how-to-specify-multiple-return-types-using-type-hints/33945518
https://stackoverflow.com/questions/40181344/how-to-annotate-types-of-multiple-return-values