在 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 种类型。但为什么?在这种情况下它们应该是什么?
这在文档中也有指定,但我还是不明白
文档中的示例显示了这三种类型:
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
Generator[YieldType, SendType, ReturnType]
在你的情况下,我猜[None, None, str]
,因为你只关心可等待的值。
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
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]
.
Awaitable
类型,因为异步函数返回可等待:
from typing import Awaitable
async def get_string(word: str) -> Awaitable[str]:
return word