Propagate Cancellation and Bound Waiting
Core idea
Calling task.cancel requests cancellation; CancelledError is delivered at a cancellation opportunity. Use try/finally to release resources, and normally let cancellation propagate. asyncio.timeout (3.11+) cancels the current task at a deadline and converts its own cancellation to TimeoutError outside the context. A timeout is cooperative, not a hard kill of blocking code.
import asyncio
async def main(): ready = asyncio.Event() async def work(): try: ready.set() await asyncio.Event().wait() finally: print('released') t=asyncio.create_task(work()) await ready.wait() t.cancel() try: await t except asyncio.CancelledError: print(t.cancelled())
asyncio.run(main())The event ensures the cleanup scope was entered. Awaiting observes cancellation.
Expected output:
releasedTrueHandle an immediate deadline
import asyncio
async def main(): try: async with asyncio.timeout(0): await asyncio.Event().wait() except TimeoutError: print('deadline')
asyncio.run(main())The deadline expires on the next loop iteration while the event remains unset. Catch outside the context.
Expected output:
deadlineCommon mistake
CancelledError subclasses BaseException, not Exception. If catching it for cleanup, re-raise after cleanup unless intentionally managing cancellation; repeated cancellation can interrupt awaited cleanup. A timed-out operation may already have side effects.
Practice
Add an explicit cleanup list to the first example. Verify it contains exactly one marker after awaiting the cancelled task.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Cancellation and timeouts
Check your understanding of cancellation and timeouts.
What is printed?
import asyncio
async def main(): try: async with asyncio.timeout(0): await asyncio.Event().wait() except TimeoutError: print('expired')
asyncio.run(main())What is printed?
import asyncio
async def main(): async def f(): return 7 async with asyncio.timeout(None): print(await f())
asyncio.run(main())Which construct reliably runs ordinary cleanup on cancellation?
Where should a timeout context’s TimeoutError be caught?