具有两个或多个返回参数的函数注释

Kir*_*ill 16 python type-hinting python-3.x

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

def func() -> str:
    return "ok"
Run Code Online (Sandbox Code Playgroud)

但是,当我编写带有两个或多个参数的注释时,我的PyCharm给了我SyntaxError: invalid syntax

def func() -> str, str:
    return "ok - 1", "ok - 2"
Run Code Online (Sandbox Code Playgroud)

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

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

请在您的回复中加入PEP链接(如果有)。我在PEP 484PEP 3107上寻找答案,但找不到。

gmd*_*mds 24

用途typing.Tuple

from typing import Tuple

def func() -> Tuple[str, str]:
    return 'a', 'b'
Run Code Online (Sandbox Code Playgroud)

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

print(type(func()))
Run Code Online (Sandbox Code Playgroud)

输出:

<class 'tuple'>
Run Code Online (Sandbox Code Playgroud)

除了空tuple()),括号是必要定义tuple,即该装置'a', 'b'被作为一个创建tuple,而不是被各自的值由聚集成一个return语句。

  • @kojiro我可能会误解你,但不是具有多个返回值(特别是)返回“ tuple”的函数,而不是具有单个返回值的函数,该函数也恰好是一个知道其长度的不可拆包对象和元素的类型,哪些*会*需要这样的说明符? (4认同)