gotchapythonMajor
asyncio.run() cannot be called from a running event loop
Viewed 0 times
Python 3.7+ for asyncio.run()
asyncio.runevent loop runningJupyter asyncnest_asyncioRuntimeError
jupyter
Error Messages
Problem
Calling asyncio.run() inside Jupyter notebooks, or from code already running in an async context raises RuntimeError: This event loop is already running. This also happens in some frameworks like FastAPI background tasks.
Solution
Use different approaches depending on context:
# In Jupyter notebooks
await my_coroutine() # Just await directly — Jupyter has a running loop
# Or use nest_asyncio
import nest_asyncio
nest_asyncio.apply()
asyncio.run(my_coroutine()) # Now works
# In already-async code, just await
async def handler():
result = await my_coroutine() # Don't use asyncio.run()
# If you need sync-to-async bridge
import asyncio
loop = asyncio.get_event_loop()
result = loop.run_until_complete(my_coroutine())
# In Jupyter notebooks
await my_coroutine() # Just await directly — Jupyter has a running loop
# Or use nest_asyncio
import nest_asyncio
nest_asyncio.apply()
asyncio.run(my_coroutine()) # Now works
# In already-async code, just await
async def handler():
result = await my_coroutine() # Don't use asyncio.run()
# If you need sync-to-async bridge
import asyncio
loop = asyncio.get_event_loop()
result = loop.run_until_complete(my_coroutine())
Why
asyncio.run() creates a new event loop and runs until the coroutine completes. But there can only be one event loop per thread. Jupyter, some web frameworks, and other async contexts already have a running loop.
Gotchas
- nest_asyncio patches the loop to allow nesting — useful for Jupyter but can hide bugs
- In Python 3.10+, asyncio.run() creates and sets a new event loop
- loop.run_until_complete() is deprecated in favor of asyncio.run() but still works for bridging
Code Snippets
Async in Jupyter / nested event loops
# In Jupyter: just await
result = await fetch_data()
# If you must use asyncio.run:
import nest_asyncio
nest_asyncio.apply()
result = asyncio.run(fetch_data())Context
When using asyncio.run() in Jupyter or within an already-async context
Revisions (0)
No revisions yet.