带有两个或多个返回参数的函数注解 [英] Function annotation with two or more return parameters

查看:24
本文介绍了带有两个或多个返回参数的函数注解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我为返回一个参数的函数编写注释时,我没有问题.

When I write an annotation for a function which returns one parameter, I have no problems.

def func() -> str:
    return "ok"

然而,当我写一个带有两个或更多参数的注解时,我的 PyCharm 给了我SyntaxError: invalid syntax.

However, when I write an annotation with two or more parameters, my PyCharm gives me SyntaxError: invalid syntax.

def func() -> str, str:
    return "ok - 1", "ok - 2"

我认为参数可以与 tuple 组合,但我认为这不是最好的方法.

I think that the parameters can be combined with a tuple, but I don't think that's the best way to do it.

我的问题是:如何正确注释具有两个或多个返回参数的函数?

My question is: how can I properly annotate a function with two or more return parameters?

请在您的回复中包含 PEP 链接(如果有).我在 PEP 484PEP 3107 却找不到.

Please include a PEP link, if any, in your response. I looked for the answer at PEP 484 and PEP 3107 and could not find it.

推荐答案

使用 typing.Tuple:

from typing import Tuple

def func() -> Tuple[str, str]:
    return 'a', 'b'

这是合适的,因为从概念上讲,您实际上是在返回一个包含这些值的 tuple.注意:

This is appropriate because, conceptually, you are actually returning a single tuple containing those values. Note:

print(type(func()))

输出:

<class 'tuple'>

除了空的 tuple (()),括号不是定义元组所必需的,这意味着'a', 'b' 被创建为一个 tuple,而不是由 return 语句将单独的值聚集在一起.

Except for the empty tuple (()), parentheses are not necessary to define a tuple, which means that 'a', 'b' is created as a tuple, rather than being separate values gathered into one by the return statement.

这篇关于带有两个或多个返回参数的函数注解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆