如何在 python 3.8+ 中将函数转换为协程

How to transform a function into a coroutine in python 3.8+

所述,我们可以使用 asyncio.coroutine 装饰器将函数转换为协程,如下所示:

def hello():
    print('Hello World!')

async_hello = asyncio.coroutine(hello)

但是从 python 3.8 开始不推荐使用此函数(由 async def ... 取代)。那么我们如何在没有 async def ... 的情况下在 3.8+ 中做到这一点?

定义一个只调用函数的自定义协程包装器:

from functools import wraps

def awaitify(sync_func):
    """Wrap a synchronous callable to allow ``await``'ing it"""
    @wraps(sync_func)
    async def async_func(*args, **kwargs):
        return sync_func(*args, **kwargs)
    return async_func

这可用于使任意同步函数兼容任何需要协程的地方。

def hello():
    print('Hello World!')

async_hello = awaitify(hello)
asyncio.run(async_hello())  # Hello World!