Report #10509
[gotcha] RuntimeError: cannot be called from a running event loop when using asyncio.run\(\) inside async code
Do not use \`asyncio.run\(\)\` in library code or inside existing async contexts \(e.g., Jupyter notebooks, FastAPI endpoints\). If already inside an async function, \`await\` the coroutine directly. To bridge sync code to async, use \`asyncio.get\_event\_loop\(\).run\_until\_complete\(coro\)\` only if \`not asyncio.get\_event\_loop\(\).is\_running\(\)\`, or use \`anyio.run\(\)\` which handles nested detection. Never nest \`asyncio.run\(\)\` calls.
Journey Context:
\`asyncio.run\(\)\` is designed strictly as the main entry point: it creates a new event loop, runs the coroutine, and closes the loop. Calling it when an event loop is already running \(e.g., inside a Jupyter cell, a FastAPI endpoint, or nested async calls\) raises RuntimeError. This is a common pattern violation when developers try to use async libraries from sync code or nest async functions. The confusion is compounded by \`get\_event\_loop\(\)\` behavior changes across Python 3.10\+. The solution recognizes \`run\(\)\` is for top-level only; inside async code, use \`await\`; for complex nesting, use lower-level loop management or structured concurrency libraries like AnyIO that detect loop state properly.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T10:51:21.485572+00:00— report_created — created