【问题标题】:How do I access the return value from an async function in Python?如何从 Python 中的异步函数访问返回值?
【发布时间】:2017-09-29 16:38:56
【问题描述】:

如果我尝试在 Python 中运行以下代码,则会收到以下错误:

async def foo():
    yield 1

async def bar():
    x = await foo()
b=bar()
b.send(None)

TypeError: object async_generator can't be used in 'await' expression

另一方面,以下代码有效(并引发了 StopIteration,但这是意料之中的):

async def foo():
    pass

async def bar():
    await foo()
b=bar()
b.send(None)

为什么这不起作用?

如果我将foo 替换为:

@coroutine
def foo():
    yield 1

这里的问题是这看起来很奇怪,我很确定这不是获得这种行为的推荐方式。然后在大多数语言中,您只需要 async 和 await,而不是 @coroutine!

【问题讨论】:

    标签: python asynchronous


    【解决方案1】:

    我在这里假设您使用的是 asyncio 库。
    我认为出于与async def 函数的兼容性原因,建议使用装饰器@coroutine

    虽然没有严格执行。

    asyncio.coroutine documentation

    还有

    @asyncio.coroutine 标记基于生成器的协程的装饰器。这个 允许生成器使用 yield from 来调用 async def 协程,并且 还 使生成器能够被 async def 协程调用,例如 使用等待表达式的实例

    不需要自己装饰 async def 协程。

    【讨论】:

      猜你喜欢
      • 2015-09-14
      • 2021-03-04
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2018-01-03
      • 1970-01-01
      相关资源
      最近更新 更多