Why did cancelling this asyncio task skip cleanup or break timeout?
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.
- Explain why
except Exception:misses cancellation and why returning insideexcept asyncio.CancelledError:breaksasyncio.timeout()andTaskGroup. - Write a fixed
workerthat cleans up on cancellation and letsasyncio.timeout()raiseTimeoutError.
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)
- "BASE CLASS CHECK"
Since Python 3.8,
asyncio.CancelledErrorinherits fromBaseException, notException. Doesexcept Exception:catch it? - "HOW TIMEOUT WORKS"
asyncio.timeout()cancels the running task when the deadline expires, then turns the exitingCancelledErrorintoTimeoutError. - "CLEAN UP AND RAISE"
Use
try ... finallyfor general cleanup, orexcept asyncio.CancelledError:followed by a bareraiseso 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.
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())
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 pattern | Cleanup runs on cancel? | asyncio.timeout() outcome | TaskGroup sibling cancel |
|---|---|---|---|
except Exception: | No (CancelledError is a BaseException) | Raises TimeoutError | Cancels cleanly |
except CancelledError: return | Yes | Silently succeeds, no TimeoutError | Sibling may linger or delay exit |
except CancelledError: ... raise | Yes (cancel only) | Raises TimeoutError | Cancels cleanly |
try ... finally: | Yes (all exits) | Raises TimeoutError | Cancels 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::
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
CancelledErrorwithexcept asyncio.CancelledError: passor a bareexcept:. It hidesasyncio.timeout()deadlines and lets cancelledTaskGroupsiblings keep running. - Putting socket or lock release only inside
except Exception:. BecauseCancelledErrorinherits fromBaseException, cancelling the task skips that block and leaks the resource. - Expecting
task.cancel()to interrupt a tight CPU loop. Cancellation only raises at anawaitboundary, so synchronous loops withoutawaitcannot be cancelled. - Forgetting to
awaita cancelled task after callingtask.cancel(). Callingcancel()only requests cancellation; awaiting the task waits for itsfinallycleanup 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 likeasyncio.timeout()andTaskGroup. If you truly suppress an externalCancelledError, you must calltask.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'sawait asyncio.shield(task)still raisesCancelledErrorwhile 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
finallyneeds its ownawait, like closing a connection?" Anawaitinsidefinallycan receive a second cancellation if shutdown forces another cancel. Keep async teardown short and idempotent, wrap brief network flushes with a smallasyncio.timeout()if needed, and avoid starting long background jobs insidefinally.
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 →