python type_error ai_generated true

TypeError: 'Timeout' object is not awaitable

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
89%Confidence
0Evidence
2024-08-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.11 active — — —
3.12 active — — —

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 90% fail

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

  2. 85% fail

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