我如何在类似未来的对象的__await__中等待? [英] How can I await inside future-like object's __await__?

查看:404
本文介绍了我如何在类似未来的对象的__await__中等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PEP 0492 添加了新的__await__魔术方法.实现此方法的对象将成为将来的对象,可以使用await等待.很明显:

PEP 0492 adds new __await__ magic method. Object that implements this method becomes future-like object and can be awaited using await. It's clear:

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表达式:

Ok, but what if I want to call some async def defined function instead of asyncio.sleep? I can't use await because __await__ is not async function, I can't use yield from because native coroutines requires await expression:

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库

The solution was recommended by Yury Selivanov (the author of PEP 492) for aioodbc library

这篇关于我如何在类似未来的对象的__await__中等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆