我最近发现了Function Annotations在 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
我该如何以这种方式返回多个值?
最佳答案
简短的回答是否。
长的答案是是的,需要一些编码:
如果您愿意修改源代码(我不得不多次这样做),您可以采用自己的方式来完成此操作。
请记住,这只是一小段代码,我相信有一种更有效的方法可以做到这一点,但是这会给你想要的东西:
在 typed.py
文件中,找到 _check_return_type()
函数并将其更改为以下内容:
def _check_return_type(signature, return_value):
"""Check that the return value of a function matches the signature."""
annotation = signature.return_annotation
if annotation is EMPTY_ANNOTATION:
annotation = AnyType
# If the return type is a tuple of typed values, and the length is greater than 1 (to prevent the actual tuple return type)
if isinstance(annotation, tuple) and len(annotation) > 1:
for p, a in zip(return_value, annotation):
if not isinstance(p, a):
raise TypeError('Incorrect return type: {} ({} required)'.format(type(p), a))
else:
if not isinstance(return_value, annotation):
raise TypeError('Incorrect return type')
return return_value
这将按照您设置的元组的顺序检查返回的每个值。
现在,如果您不想修改原始源代码,您可以编写自己的函数并像这样调用它:
def typechecked(target):
import inspect
import functools
@functools.wraps(target)
def wrapper(*args, **kwargs):
signature = inspect.signature(target)
params = target(*args, **kwargs)
for p, a in zip(params, signature.return_annotation):
if not isinstance(p, a):
raise TypeError('Incorrect return type: {} ({} required)'.format(type(p), a))
return params
return wrapper
希望这对您有所帮助。
关于python - 如何使用注释返回多个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34422729/