download

Why did cancelling this asyncio task skip cleanup or break timeout?

Python~12 minReviewed 3 Dec 2026Free · No sign-in

Question

Two coroutines run on Python 3.12 asyncio. When sync_worker is cancelled, log stays empty because cleanup never runs. When poll_worker runs inside async with asyncio.timeout(0.02):, the block returns "stopped" instead of raising TimeoutError.

  1. Explain why except Exception: misses cancellation and why returning inside except asyncio.CancelledError: breaks asyncio.timeout() and TaskGroup.
  2. Write a fixed worker that cleans up on cancellation and lets asyncio.timeout() raise TimeoutError.
"CODE · PYTHON"
import asyncio


async def sync_worker(started, log):
    try:
        started.set()
        await asyncio.sleep(5)
    except Exception:
        log.append("cleanup")


async def poll_worker():
    try:
        await asyncio.sleep(5)
    except asyncio.CancelledError:
        return "stopped"
Show hints (3)
  1. "BASE CLASS CHECK"

    Since Python 3.8, asyncio.CancelledError inherits from BaseException, not Exception. Does except Exception: catch it?

  2. "HOW TIMEOUT WORKS"

    asyncio.timeout() cancels the running task when the deadline expires, then turns the exiting CancelledError into TimeoutError.

  3. "CLEAN UP AND RAISE"

    Use try ... finally for general cleanup, or except asyncio.CancelledError: followed by a bare raise so cancellation propagates.

Show checked explanation

Since Python 3.8, asyncio.CancelledError inherits from BaseException, not Exception, so except Exception: skips cleanup in sync_worker. Meanwhile, asyncio.timeout() and TaskGroup rely on CancelledError propagating out of the coroutine. Swallowing it in poll_worker suppresses TimeoutError. Put cleanup in finally or except asyncio.CancelledError: and always re-raise.

"SOLUTION · PYTHON"
import asyncio


async def worker():
    try:
        await asyncio.sleep(5)
    except asyncio.CancelledError:
        print("cleanup on cancel")
        raise


async def main():
    try:
        async with asyncio.timeout(0.02):
            await worker()
    except TimeoutError:
        print("timed out")


asyncio.run(main())
"OUTPUT"
cleanup on cancel
timed out

Code run on CPython 3.12.10 against both starter coroutines, asyncio.timeout, TaskGroup, and asyncio.shield checks. Checked by an editor other than the author.

Walkthrough

When a task is cancelled, asyncio injects CancelledError at the task's next await point. How your handler treats that exception decides whether cleanup runs and whether structured concurrency still works:

Handler patternCleanup runs on cancel?asyncio.timeout() outcomeTaskGroup sibling cancel
except Exception:No (CancelledError is a BaseException)Raises TimeoutErrorCancels cleanly
except CancelledError: returnYesSilently succeeds, no TimeoutErrorSibling may linger or delay exit
except CancelledError: ... raiseYes (cancel only)Raises TimeoutErrorCancels cleanly
try ... finally:Yes (all exits)Raises TimeoutErrorCancels cleanly

Why sync_worker skipped cleanup. CancelledError subclasses BaseException directly so normal except Exception: error handlers do not swallow cancellations by accident. Any cleanup sitting only inside except Exception: never executes when a task is cancelled.

Why poll_worker broke asyncio.timeout(). asyncio.timeout() works by scheduling task.cancel() when time expires. On exit, its __aexit__ method checks whether CancelledError is propagating out and converts it into TimeoutError. Because poll_worker caught CancelledError and returned "stopped", __aexit__ saw no exception and let the timed-out call appear to succeed.

Why TaskGroup breaks too. When one task in an asyncio.TaskGroup raises an error, the group cancels every sibling and waits for them all to finish. A sibling that swallows CancelledError inside a retry loop or slow fallback can delay or hang shutdown.

When cleanup should run on both normal returns and cancellations, prefer try ... finally::

"PYTHON"
async def stream_worker():
    print("open")
    try:
        await asyncio.sleep(5)
    finally:
        print("close")

Only catch asyncio.CancelledError explicitly when you need cancel-specific logging or rollback, and end the block with bare raise.

Common mistakes

  • Swallowing CancelledError with except asyncio.CancelledError: pass or a bare except:. It hides asyncio.timeout() deadlines and lets cancelled TaskGroup siblings keep running.
  • Putting socket or lock release only inside except Exception:. Because CancelledError inherits from BaseException, cancelling the task skips that block and leaks the resource.
  • Expecting task.cancel() to interrupt a tight CPU loop. Cancellation only raises at an await boundary, so synchronous loops without await cannot be cancelled.
  • Forgetting to await a cancelled task after calling task.cancel(). Calling cancel() only requests cancellation; awaiting the task waits for its finally cleanup to finish.

Follow-up questions

  • "When would you ever call task.uncancel()?" Almost never in application code. task.uncancel() (added in Python 3.11) decrements the task's cancellation counter and exists for internals like asyncio.timeout() and TaskGroup. If you truly suppress an external CancelledError, you must call task.uncancel() so outer timeouts do not misread a leftover cancellation count. Prefer re-raising instead.
  • "Does asyncio.shield() stop cancellation cleanly for a critical write?" It protects the inner task from being cancelled, but the caller's await asyncio.shield(task) still raises CancelledError while the inner task keeps running detached. Create the inner task explicitly and keep a strong reference to it until done, because the event loop holds only weak references and an unreferenced task can be garbage-collected.
  • "What if cleanup inside finally needs its own await, like closing a connection?" An await inside finally can receive a second cancellation if shutdown forces another cancel. Keep async teardown short and idempotent, wrap brief network flushes with a small asyncio.timeout() if needed, and avoid starting long background jobs inside finally.

What a strong answer covers

States that CancelledError subclasses BaseException since Python 3.8, explains how swallowing it breaks asyncio.timeout() and TaskGroup, uses try ... finally or except CancelledError with bare raise, and knows uncancel() and asyncio.shield() pitfalls.

Open in interactive practice deck →

Original OfferVibe question. Python asyncio Task Cancellation · asyncio.CancelledError · asyncio.timeout · asyncio.shield.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.