Nesting asyncio to run multiple event loops in Python

Nesting asyncio to run multiple event loops in Python
Photo by thebugadi ㅤ / Unsplash

Python does not support running multiple or nesting event loops. But while working with frameworks or libraries like FastAPI and Celery, we might need to run multiple event loops at the same time.

In such cases, we are often greeted with errors like:

  • Cannot run the event loop while another loop is running
  • This event loop is already running

My scenario was something like this:


To avoid such issue, the workaround is to:

  1. Create a new event loop
  2. Run async function in that event loop
  3. Close the loop after the task is complete.

This can be done using nest_asyncio package. To use it, install the package:

pip install nest_asyncio

Then, import and apply the patch in the function where the event loop needs to be patched:

import nest_asyncio
...
def sync_func():
    ...
    loop = asyncio.get_event_loop()
    nest_asyncio.apply(loop)
    
    # call async function with this loop
    loop.run_until_complete(async_func())
    ...

That's it. You can call the async functions now.