Skip to content Skip to sidebar Skip to footer

Test Calling A Python Coroutine (async Def) From A Regular Function

Let's say I have some asyncio coroutine which fetches some data and returns it. Like this: async def fetch_data(*args): result = await some_io() return result Basically this c

Solution 1:

You will need to create an event loop to run your coroutine:

import asyncio

async def async_func():
    return "hello"

loop = asyncio.get_event_loop()
result = loop.run_until_complete(async_func())
loop.close()

print(result)

Or as a function:

def run_coroutine(f, *args, **kwargs):
    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(f(*args, **kwargs))
    loop.close()
    return result

Use like this:

print(run_coroutine(async_func))

Or:

assert"expected" == run_coroutine(fetch_data, "param1", param2="foo")

Post a Comment for "Test Calling A Python Coroutine (async Def) From A Regular Function"