How to get around “RuntimeError: This event loop is already running”

Vyshali Enukonda
2 min readApr 29, 2020

--

Hey Pythonistas,

Before we start, let’s all agree that asyncio is a complex beast. Anyway, here’s my story.

So I was working on a Python library at work which was great until one fine day my users started complaining about this issue when they try to use the library in their Jupyter notebook environments. I started digging into it and the first thing I noticed was what was rightly conveyed by the “Runtime Error”. The event loop was indeed already running:

After a little more research I found that the ipython kernel itself runs on an event loop, and as of Tornado 5.0, it’s using the asyncio event loop. Asyncio does not allow its event loop to be nested. So if you are in an environment where the event loop is already running such as a WebServer, a GUI application or a Jupyter notebook in this case, it’s impossible to run tasks and wait for the result(it so happens that my library tries to do that).

I quickly provided a work around for our users to downgrade their tornado version to 4.5.3.

This worked fine as an interim solution but we did have considerably sized user base who were keen on using newer versions of tornado and we definitely wanted to make our library work without forcing them to downgrade tornado.

The solution was to use nest-asyncio. This package patches “asyncio” and allows nested usage “loop.run_until_complete”. I have simply patched the event loop in my package’s “__init__.py” and rest was magic.

Hope this helps!!

Cheers!!

--

--