python - 如何使用注释返回多个值?

标签 python python-3.x annotations

我最近发现了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/

相关文章:

php - ParamConverter 可选但有效

python - 使用 Pandas 连接 CSV 文件会导致重复

python - 模块未找到错误 : No module named 'google.appengine'

python - 这个算法是否占用了太多的额外空间,成为 "in place"?

java - Spring MVC 4.1.7 警告 : No mapping found for HTTP request with URI [/user] in DispatcherServlet

annotations - 需要澄清 Resharper NotNullAttribute 的含义

Python单元测试,某些方法只运行一次

python - 广泛使用 python 的 getattr 是不好的做法吗?

Python:根据日期用不同颜色绘制分散数据

python-3.x - 确定 DataFrame 每一行的值