简体   繁体   中英

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

As stated in this question , we can turn a function into a coroutine using the asyncio.coroutine decorator to turn a function into a coroutine like so:

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

async_hello = asyncio.coroutine(hello)

However this function is deprecated as of python 3.8 (replaced by async def... ). So how can we do this in 3.8+ without async def... ?

Define a custom coroutine wrapper that merely calls the function:

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

This can be used to make an arbitrary synchronous function compatible wherever a coroutine is expected.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM