【问题标题】:How to specify return type in an async Python function?如何在异步 Python 函数中指定返回类型?
【发布时间】:2019-06-23 11:24:08
【问题描述】:

在 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 种类型。但为什么?在这种情况下它们应该是什么?

这个在the docs里也有说明,不过还是不明白

【问题讨论】:

    标签: python types python-asyncio mypy


    【解决方案1】:

    示例in the docs 显示了这三种类型:

    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 definition 并提供更多示例和更清晰的定义:

    Generator[YieldType, SendType, ReturnType]
    

    在你的情况下,我猜[None, None, str],因为你只关心等待值。

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多