我最近发现了Python 3.x中的函数注释以及它们可能具有的用处。
我安装了typeannotations
模块,以便对参数和返回类型进行类型检查。
工作示例:
from annotation.typed import typechecked
@typechecked
def test_func(arg1: int) -> int:
return arg1
print(test_func(1))
>>> 1
以下是一个错误的示例,会引发TypeError
异常。
from annotation.typed import typechecked
@typechecked
def test_func(arg1: int) -> str:
return arg1
print(test_func(1))
>>>TypeError: Incorrect return type
然而我还没有能够弄清楚如何使用 typechecker
来返回多个值
from annotation.typed import typechecked
@typechecked
def test_func(arg1: str, arg2: str) -> (str, str):
return arg1, arg2
print(test_func('hello', 'world'))
我传入了两个
str
并返回一个包含两个str
的列表,但是它引发了异常。TypeError: Incorrect return type
我该如何以这种方式返回多个值?
-> tuple:
是否起作用? - Bhargav Rao