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-3.x相关问答推荐

如何在输入正确的用户名和密码时添加按钮?

按长度和字母数字对Pandas 数据帧列进行排序

如何从选定的html内容中获取所需的文本

在BaseHTTPRequestHandler中填充和返回列表

使用Python抓取sofascore以获取有关球队阵容和投票的信息

将值从函数传递到标签

txt 文件与不同的分隔符到整数列表

在 python pandas 中设置条件和分配新值

从日志(log)文件中查找延迟最低的用户

pip install mysqlclient 失败为 mysqlclient 运行 setup.py bdist_wheel ... 错误

TypeError:JSON 对象必须是 str,而不是 'dict'

如何为 Python 中的线程设置异步事件循环?

全局捕获快速 api 中的异常

sys.stdin.readline() 读取时没有提示,返回 'nothing in between'

作为函数对象属性的 __kwdefaults__ 有什么用?

TypeError: write() 参数必须是 str,而不是字节(Python 3 vs Python 2)

同步调用协程

通过字典有效地替换Pandas 系列中的值

在 Visual Studio Code 中调试 Scrapy 项目

如何在不更改任何默认值的情况下在 Ubuntu 上为 python 3.8 安装 pip?