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

IPython似乎已安装但无法运行

如何从包含SPAN文本的标记中获取链接

为什么我无法在django中按月筛选事件?

以特定方式重新排列 pandas 数据框的列

Python根据条件从多行读取值

找到在指定列的另一个分组中存在重复的行.

TypeError: issubclass() arg 1 在 Flask 中导入 langchain 时必须是一个类

如何在python 3.10中将列表项(字符串类型)转换为模块函数

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

为什么最简单的流光示例会出错?

为什么 Python 枚举中的可变值是同一个对象?

如何将具有多个参数的函数传递给 python concurrent.futures.ProcessPoolExecutor.map()?

在 jupyter notebook 的单元格中使用 sudo

Python 解包运算符 (*)

创建日志(log)文件

AttributeError:LinearRegression 对象没有属性coef_

类方法和实例方法同名

计数大于Pandas groupby 中的值的项目

matplotlib - 模块sip没有属性setapi

Windows 下 Python 3.x 的 OpenCV