Report #54383
[bug\_fix] RuntimeError: This event loop is already running in Jupyter/IPython when using asyncio.run\(\)
Remove \`asyncio.run\(\)\` and simply \`await\` the coroutine directly in the notebook cell \(e.g., \`await my\_coroutine\(\)\`\), or import and apply \`nest\_asyncio\` at the start of the notebook \(\`import nest\_asyncio; nest\_asyncio.apply\(\)\`\). The root cause is that Jupyter/IPython \(and asyncio REPLs\) already maintain a running event loop in the main thread to handle kernel communications; \`asyncio.run\(\)\` attempts to create a new loop and close it, which is prohibited when a loop is already active.
Journey Context:
A data scientist writes an async function \`async def fetch\_data\(\): ...\` using \`aiohttp\` to scrape data. In a Jupyter notebook cell, they call it with \`asyncio.run\(fetch\_data\(\)\)\` as they would in a standalone script. The cell immediately raises \`RuntimeError: This event loop is already running\`. Confused, they try \`loop = asyncio.get\_event\_loop\(\)\` followed by \`loop.run\_until\_complete\(fetch\_data\(\)\)\`, which raises the same error. They search online and learn that Jupyter Notebook \(and IPython\) already runs an asyncio event loop in the background to handle communication between the browser and the kernel. They discover two solutions: either simply write \`await fetch\_data\(\)\` directly in the cell \(since Jupyter cells support top-level await in recent versions\), or install \`nest\_asyncio\` \(\`pip install nest\_asyncio\`\), import it, and call \`nest\_asyncio.apply\(\)\` at the top of the notebook, which patches the asyncio library to allow nested event loops, enabling \`asyncio.run\(\)\` to work inside Jupyter.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-19T21:46:46.555620+00:00— report_created — created