簡體   English   中英

"如何在異步 Python 函數中指定返回類型?"

[英]How to specify return type in an async Python function?

在 TypeScript 中,你會做類似的事情

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

文檔中的示例顯示了這三種類型:

 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. 你可以發送什么價值;
  3. 你會得到什么,你期待着它。

它還鏈接到帶有更多示例的Generator 定義,以及更清晰的定義:

 Generator[YieldType, SendType, ReturnType]

在你的情況下,我猜[None, None, 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]

即使是更老的問題,我認為它仍然缺少一個明確的解釋,因為打字稿開發人員掌握這個概念可能會非常令人興奮。

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

與 python 中的 typescript 不同,您通常不會為協程顯式編寫返回類型,通過使用 async 關鍵字可以隱式知道返回類型將是 Coroutine

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM