python type_error ai_generated true

TypeError: 'async with' received an object from __aenter__ that does not implement __await__: Timeout

ID: python/asyncio-timeout-context-manager-not-async

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-11-15First Seen

Version Compatibility

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

Root Cause

Code uses async with asyncio.timeout() on a Python version where asyncio.timeout exists only as a plain context manager (or on an older version where it does not exist at all), or a custom Timeout object is returned instead of a coroutine.

generic

中文

在 asyncio.timeout 仅作为普通上下文管理器存在的 Python 版本上使用 async with asyncio.timeout()(或在根本不支持它的旧版本上),或返回了自定义 Timeout 对象而非协程。

Workarounds

  1. 92% success
    try:
        result = await asyncio.wait_for(coro(), timeout=5.0)
    except asyncio.TimeoutError:
        result = None
  2. 88% success
    async with asyncio.timeout(5.0):
        await coro()
    # note: 'async with', but NOT 'async with await'

Dead Ends

Common approaches that don't work:

  1. 90% fail

    asyncio.timeout is not a coroutine; awaiting it raises TypeError.

  2. 80% fail

    Does not actually cancel the inner coroutine, so the timeout never triggers.