python runtime_error ai_generated true

RuntimeWarning: 协程 'fetch_data' 从未被 await

RuntimeWarning: coroutine 'fetch_data' was never awaited

ID: python/coroutine-never-awaited

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

版本兼容性

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

根因分析

调用了一个协程函数但没有 await 或 asyncio.create_task,因此创建了协程对象并在未运行的情况下被垃圾回收。

English

A coroutine function was called without await or asyncio.create_task, so the coroutine object was created and garbage collected without running.

generic

解决方案

  1. 95% 成功率
    Await the coroutine in an async context:
    
    async def main():
        data = await fetch_data()
  2. 90% 成功率
    If you intentionally want fire-and-forget, schedule it:
    
    asyncio.create_task(fetch_data())
  3. 88% 成功率
    Enable -W error::RuntimeWarning in tests to catch this at CI time.

无效尝试

常见但无效的做法:

  1. 90% 失败

    Hides the symptom; the async work silently never runs.

  2. 85% 失败

    Raises 'asyncio.run() cannot be called from a running event loop'.

  3. 70% 失败

    Breaks other callers and loses concurrency.