python runtime_error ai_generated true

RuntimeError: 无法重用已 await 的协程

RuntimeError: cannot reuse already awaited coroutine

ID: python/asyncio-cannot-reuse-already-awaited-coroutine

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-04-19首次发现

版本兼容性

版本状态引入弃用备注
3.8+ active
3.9+ active
3.10+ active
3.11+ active
3.12+ active

根因分析

协程对象被 await 一次后再次 await。协程对象只能使用一次;每次调用协程函数都会产生新的协程。

English

A coroutine object was awaited once and then awaited again. Coroutine objects are single-use; each call to a coroutine function yields a fresh coroutine.

generic

解决方案

  1. 97% 成功率
    # Wrong
    c = fetch(url)
    await c
    await c
    # Right
    await fetch(url)
    await fetch(url)
  2. 92% 成功率
    task = asyncio.create_task(fetch(url))
    await task
    await task  # Tasks are awaitable multiple times

无效尝试

常见但无效的做法:

  1. 95% 失败

    The coroutine state is exhausted; send raises StopIteration immediately.

  2. 90% 失败

    The coroutine object is already closed; ensure_future raises the same error.