Suppose I want to call async code from a regular function and wait for its return. This function could be part of a library or could be far down a stack that is being iteratively converted to asyncio, so the fact that it’s using asyncio internally should be transparent to any callers. Maybe it’s called from async contexts and there already is an event loop, maybe there isn’t. What’s currently the best way to call a coroutine in these contexts?
async def fetch_something(): ...
def sync_func(): # could be called from async or sync contexts
ret = call_async(fetch_something())
...
Options I have considered for call_async:
asyncio.run() – This is wrong, according to the documentation: “This function cannot be called when another asyncio event loop is running in the same thread. […] It should be used as a main entry point for asyncio programs, and should ideally only be called once.”
asyncio.get_event_loop().run_until_complete() – This has started printing warnings when called from a synchronous context.
asyncio.new_event_loop().run_until_complete()?
Write a custom utility that calls get_running_loop() and new_event_loop() if that throws an exception?
Also, how can I handle the various housekeeping that asyncio.run() does?
You can make main() asynchronous, and then you can schedule a coroutine using asyncio.create_task(asynchronous()).
You can continue using the synchronous functions as before.
That object is awaitable, and you can wait on it from main() to get its result. I thought this was obvious.
It boils down to the simple fact that you use synchronous code to create an event loop and get results from asynchronous code. At first, I was sure this was just a request for a code sample. But here are some complete examples.
That is a new constraint; you cannot wait on an awaitable from a synchronous function. However, you can call (schedule) a coroutine from a synchronous function.