Report #14780
[bug\_fix] RuntimeError: Event loop is closed or Cannot run the event loop while another loop is running \(in REPL/Jupyter\)
In IPython/Jupyter, use \`await func\(\)\` directly \(autoawait\) instead of \`asyncio.run\(\)\`. In scripts, call \`asyncio.run\(\)\` exactly once inside \`if \_\_name\_\_ == "\_\_main\_\_":\` and never call it again. To recover a closed loop in a REPL, restart the kernel or use \`nest\_asyncio\`.
Journey Context:
Developer defines \`async def fetch\_data\(\): ...\` in a Jupyter Notebook cell. They run it with \`asyncio.run\(fetch\_data\(\)\)\` and it succeeds. They modify the function and run the cell again. It raises \`RuntimeError: Event loop is closed\`. Developer tries to fix by calling \`asyncio.get\_event\_loop\(\).run\_until\_complete\(fetch\_data\(\)\)\` but gets \`RuntimeError: Cannot run the event loop while another loop is running\` because Jupyter/IPython already has an asyncio event loop running in the background thread to support the kernel. Developer tries \`await fetch\_data\(\)\` directly in a new cell; in modern IPython this works due to autoawait, but because they previously corrupted the loop state with multiple \`asyncio.run\(\)\` calls, even \`await\` might fail or hang. The rabbit hole involves understanding that \`asyncio.run\(\)\` is designed to be the main entry point of a program: it creates a new event loop, runs the coroutine, and then closes the loop permanently. In a REPL environment where the loop must persist across cell executions, \`asyncio.run\(\)\` is inappropriate. The fix is to rely on IPython's \`autoawait\` feature \(enabled by default\) which allows top-level \`await\` expressions without \`asyncio.run\(\)\`, or to use \`nest\_asyncio\` library to patch the loop to allow nested calls, or simply restart the kernel to reset the closed loop state and avoid using \`asyncio.run\(\)\` in favor of direct \`await\`.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T22:23:36.383275+00:00— report_created — created