python
async_error
ai_generated
true
RuntimeError: This event loop is already running
ID: python/runtimeerror-event-loop
82%Fix Rate
85%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 311 | active | — | — | — |
Root Cause
Calling asyncio.run() inside an already-running loop. Common in Jupyter and web frameworks.
genericWorkarounds
-
92% success Use await directly instead of asyncio.run() when already in async context
result = await async_function()
Sources: https://docs.python.org/3/library/asyncio-task.html
-
90% success In Jupyter: use await directly (Jupyter runs its own event loop)
use await directly (Jupyter runs its own event loop)
Sources: https://docs.python.org/3/library/asyncio-runner.html
Dead Ends
Common approaches that don't work:
-
Use nest_asyncio.apply()
55% fail
Monkey-patches asyncio, can cause subtle bugs in production
-
Create new event loop in thread
65% fail
Complex, error-prone, usually unnecessary