Report #95088
[bug\_fix] RuntimeError: asyncio.run\(\) cannot be called from a running event loop
In environments that already manage an event loop \(Jupyter, Django, FastAPI\), use \`await\` directly on the coroutine instead of \`asyncio.run\(\)\`, or use \`asyncio.new\_event\_loop\(\)\` with \`loop.run\_until\_complete\(\)\` in a background thread.
Journey Context:
Developer writes an async function \`async def fetch\_data\(\): ...\` and wants to test it in a Jupyter Notebook. They call \`asyncio.run\(fetch\_data\(\)\)\` and get 'RuntimeError: asyncio.run\(\) cannot be called from a running event loop'. They check \`asyncio.get\_running\_loop\(\)\` and see the notebook kernel already has a loop running in the background thread. They try \`await fetch\_data\(\)\` directly in the cell and it works. Later, they move the code to a FastAPI endpoint \(which runs in a managed loop\) and try to use asyncio.run inside a sync utility function, getting the same error. They realize asyncio.run\(\) is designed only for the main entry point of a program. The fix for non-entry-point contexts is to either await directly \(if already in async context\) or manually create a new event loop for the specific thread using \`new\_event\_loop\(\)\` and \`set\_event\_loop\(\)\`.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T18:11:08.032602+00:00— report_created — created