python runtime_error ai_generated true

asyncio.exceptions.CancelledError:

ID: python/asyncio-cancellederror

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

Version Compatibility

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

Root Cause

A task was cancelled (e.g. by asyncio.wait_for timeout or an outer cancellation), and the CancelledError propagated up through user code without being re-raised after cleanup.

generic

中文

任务被取消(例如由 asyncio.wait_for 超时或外部取消触发),CancelledError 在用户代码中传播,未在清理后重新抛出。

Workarounds

  1. 95% success
    Run cleanup then re-raise:
    
    try:
        await work()
    except asyncio.CancelledError:
        await cleanup()
        raise
  2. 90% success
    Use contextlib.suppress(asyncio.CancelledError) only around cleanup awaits, never around the main work.
  3. 85% success
    Use asyncio.shield() around critical sections that must not be cancelled.

Dead Ends

Common approaches that don't work:

  1. 90% fail

    In 3.8+ CancelledError inherits from BaseException, so this doesn't catch it anyway; and catching it silently breaks cancellation semantics.

  2. 85% fail

    Swallows cancellation, leaving parent tasks hanging and breaking structured concurrency.

  3. 80% fail

    Re-cancelling without re-raising still doesn't propagate cancellation up the stack.