python runtime_error ai_generated true

RuntimeError: cannot reuse already awaited coroutine

ID: python/asyncio-cannot-run-coroutine-already-running

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-02-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active — — —
3.9 active — — —
3.10 active — — —
3.11 active — — —
3.12 active — — —

Root Cause

A coroutine object was awaited more than once. Coroutines in Python are single-shot; reusing the same coroutine object (e.g., in a retry loop or cached in a variable) raises this error.

generic

中文

同一个协程对象被 await 了多次。Python 中的协程是一次性的;在重试循环中复用同一个协程对象或将其缓存到变量后重复 await 都会触发此错误。

Workarounds

  1. 95% success
    async def fetch(): ...
    for _ in range(3):
        await fetch()   # new coroutine each iteration
  2. 85% success
    task = asyncio.ensure_future(fetch())
    await task
    await task   # Tasks can be awaited multiple times
  3. 88% success
    from functools import partial
    make = partial(fetch, url)
    await make()
    await make()

Dead Ends

Common approaches that don't work:

  1. 95% fail

    The coroutine frame is exhausted; send raises StopIteration immediately.

  2. 90% fail

    Shallow copy shares the same frame; awaiting the copy raises the same error.