如何在异步Python函数中指定返回类型?

问题描述 投票:0回答:4

在 TypeScript 中,你会做类似的事情

async function getString(word: string): Promise<string> {
   return word;
}

如何在 Python 中做同样的事情?我尝试了以下方法:

async def get_string(word: str) -> Coroutine[str]:
    return word

并得到了这个回溯:

TypeError: Too few parameters for typing.Coroutine; actual 1, expected 3

所以

Coroutine
预计有 3 种类型。但为什么?在这种情况下它们应该是什么?

这在文档中也有指定,但我还是不明白

python types python-asyncio mypy
4个回答
12
投票

文档中的示例显示了这三种类型:

from typing import List, Coroutine c = None # type: Coroutine[List[str], str, int] ... x = c.send('hi') # type: List[str] async def bar() -> None: x = await c # type: int


    如果您发送了一个值,您会得到什么;
  1. 您可以发送什么价值;和
  2. 你会得到什么,你就在等待它。
它还链接到

生成器定义,其中包含更多示例,以及稍微更清晰的定义:

Generator[YieldType, SendType, ReturnType]


在你的情况下,我猜

[None, None, str]

,因为你只关心可等待的值。


5
投票
即使问题比较老,我认为它仍然缺少一个清晰的解释,因为对于打字稿开发人员来说,掌握这个概念可能相当令人兴奋。

async function getString(word: string): Promise<string> { return word; }
与 Python 中的打字稿不同,您通常不会显式地为协程编写返回类型,通过使用 async 关键字可以隐式知道返回类型将是协程

async def get_string(word: str) -> str: return word
长话短说:

async main(): result = get_string() #result has inferred type of Coroutine[Any, Any, str] awaited_result = await get_string() #awaited_result has inferred type of str
    

2
投票
您可以将其输入为:

async def get_string(word: str) -> str: return word
它隐含为 

Coroutine[Any, Any, <return_type>]

:

reveal_type(get_string) # Revealed type is "def (word: builtins.str) -> typing.Coroutine[Any, Any, builtins.str]"

Coroutine

采用3个类型参数的原因是因为它类似于
Generator
(其类型参数是yield、send和return类型),但TypeScript的
Promise<T>
的Python等效项是
Future[T]
 .


0
投票
您可以使用

Awaitable

 类型,因为异步函数返回可等待:

from typing import Awaitable async def get_string(word: str) -> Awaitable[str]: return word
    
© www.soinside.com 2019 - 2024. All rights reserved.