python async_error ai_generated true

RuntimeError: This event loop is already running

ID: python/runtimeerror-event-loop

Also available as: JSON · Markdown
82%Fix Rate
85%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
311 active

Root Cause

Calling asyncio.run() inside an already-running loop. Common in Jupyter and web frameworks.

generic

Workarounds

  1. 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

  2. 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:

  1. Use nest_asyncio.apply() 55% fail

    Monkey-patches asyncio, can cause subtle bugs in production

  2. Create new event loop in thread 65% fail

    Complex, error-prone, usually unnecessary

Error Chain

Preceded by: