python - 如何在类似 future 的对象的 __await__ 中等待?

标签 python python-3.x async-await python-asyncio

PEP 0492添加新的 __await__ 魔术方法。实现这个方法的对象变成了future-like object,可以使用await来等待。很清楚:

import asyncio


class Waiting:
    def __await__(self):
        yield from asyncio.sleep(2)
        print('ok')

async def main():
    await Waiting()

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

好的,但是如果我想调用一些 async def 定义的函数而不是 asyncio.sleep 怎么办?我不能使用 await 因为 __await__ 不是 async 函数,我不能使用 yield from 因为原生协程需要 await 表达式:

async def new_sleep():
    await asyncio.sleep(2)

class Waiting:
    def __await__(self):
        yield from new_sleep()  # this is TypeError
        await new_sleep()  # this is SyntaxError
        print('ok')

我该如何解决?

最佳答案

使用直接 __await__() 调用:

async def new_sleep():
    await asyncio.sleep(2)

class Waiting:
    def __await__(self):
        return new_sleep().__await__()

Yury Selivanov(PEP 492 的作者)为 aioodbc library 推荐了该解决方案。

关于python - 如何在类似 future 的对象的 __await__ 中等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33409888/

相关文章:

asynchronous - Rust 显示预期的特征对象 `dyn Future` ,在将函数作为参数传递时发现不透明类型

python - 在 tf.nn.conv2d 中使用权重初始化器

python - 使 QGraphicsLineItem 拖动起来不那么繁琐

Python 多重处理和目录创建

python - 我遇到错误 "ModuleNotFoundError: No module named ' __main__.models'; '__main__' 不是一个包”

python - 通用代码的类型提示

python - 遍历列表直到找到值然后中断?

python - 无法创建循环来从网页获取所有标题

c# - web api 2 ExceptionHandlerFilter OnExceptionAsync 未触发

c# - 调试异步等待 Controller 操作