python type_error ai_generated true

TypeError: 'Timeout' 对象不可等待

TypeError: 'Timeout' object is not awaitable

ID: python/asyncio-timeout-context-manager-required

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

版本兼容性

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

根因分析

在 Python 3.11+ 中,asyncio.timeout() 返回异步上下文管理器,而不是可等待对象。为 asyncio.wait_for 或旧模式编写的代码错误地 await 了它。

English

In Python 3.11+, asyncio.timeout() returns an async context manager, not an awaitable. Code written for asyncio.wait_for or older patterns mistakenly awaits it.

generic

解决方案

  1. 95% 成功率
    async with asyncio.timeout(5):
        data = await fetch()
  2. 88% 成功率
    try:
        async with asyncio.timeout(5):
            return await fetch()
    except AttributeError:
        return await asyncio.wait_for(fetch(), timeout=5)
  3. 90% 成功率
    import time
    loop = asyncio.get_running_loop()
    deadline = loop.time() + 5
    async with asyncio.timeout_at(deadline):
        await fetch()

无效尝试

常见但无效的做法:

  1. 90% 失败

    Timeout is not callable; raises TypeError: 'Timeout' object is not callable.

  2. 85% 失败

    wait_for expects an awaitable; Timeout is a context manager, not awaitable.