C
C
centum2021-06-21 11:01:08
Python
centum, 2021-06-21 11:01:08

Python: How to call an async function from a synchronous one with an active event loop?

There is a function call stack:

[main async func0] -> [sync func1] -> [sync func2] -> [async func3]


How to call async func3 from func2 if func1 knows nothing about async?
func2 is passed to func1 as an interface implementation.

If you do this:
from asgiref.sync import async_to_sync

def func2():
  result = async_to_sync(func3)()

then we get an error:
RuntimeError: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly.

But I can't call directly via await, because func1 knows nothing about async.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-06-21
@centum

Wrap the asynchronous callback in a synchronous wrapper (maybe a lambda) that calls asyncio.create_task() on the target coroutine, and pass this wrapper as a callback.
If you're in control of func2, it's even easier, put a call to create_task() there.
Now, if you need to wait for the result of the execution, then it will be more difficult - but you can shove the processing of the result into the asynchronous part.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question