Back
+20 XP
Concept

Task Cancellation Cascades & asyncio.CancelledError

Calling `task.cancel()` injects an `asyncio.CancelledError` into the coroutine's suspended frame. In modern Python, `CancelledError` inherits from `BaseException` to stop generic `except Exception:` blocks from accidentally swallowing cancellations 🛑💀.

python
import asyncio

async def resilient_worker():
    try:
        await asyncio.sleep(5)
    except asyncio.CancelledError:
        # Free resources before propagating:
        print("Tearing down database connection... 🛡️")
        raise

async def main():
    task = asyncio.create_task(resilient_worker())
    await asyncio.sleep(0.01)

    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("Task cancellation confirmed 🏁")

asyncio.run(main())

# 19. Task Cancellation Cascades & asyncio.CancelledError Cancellation in asynchronous systems is not an instantaneous kill switch. It is a polite request injected into a coroutine frame as an exception at the next `await` suspension point 🛑. ```python import asyncio async def worker(): try: await asyncio.sleep(10) except asyncio.CancelledError: print("Interrupted! Releasing locks...") raise # Always re-raise unless deliberately shielding! ``` ### The Cancellation Contract 1. **BaseException Inheritance**: Prior to Python 3.8, lazy developers wrote `except Exception:` and broke loop shutdown because `CancelledError` was silently swallowed. Today, it subclasses `BaseException` 🛡️. 2. **Re-raising Requirement**: If you catch `CancelledError` to flush a file or close a socket, you MUST re-raise it (or let it bubble). Returning a value suppresses cancellation and marks the task as completed normally. 3. **`asyncio.shield()`**: When an operation (like writing an audit log) must NEVER be interrupted mid-flight, wrap the coroutine with `asyncio.shield(coro)` to protect it from parent cancellation cascades 🛡️. --- ### Interactive Pop-Quiz 🧠 #### Why does `asyncio.CancelledError` inherit from `BaseException` rather than `Exception`? - [ ] To prevent standard `except Exception:` handlers from silently swallowing task cancellations 🛑 - [ ] Because it is handled directly by the CPython bytecode evaluator in C - [ ] To allow the Linux kernel signal handlers to terminate the process - [ ] Because it must execute outside of the Python GIL context --- ### Practical Challenge 🎯 Create a coroutine `cancellable_job()` that enters `try: await asyncio.sleep(10)` and catches `asyncio.CancelledError`. Set a cleanup flag `cleaned = True`, re-raise the error. In `main()`, spawn the task, cancel it, catch the error on `await task`, and print `'CLEANUP_OK'` if the cleanup was reached. <details> <summary>Solution</summary> ```python import asyncio cleaned = False async def cancellable_job(): global cleaned try: await asyncio.sleep(10) except asyncio.CancelledError: cleaned = True raise async def main(): task = asyncio.create_task(cancellable_job()) await asyncio.sleep(0.01) task.cancel() try: await task except asyncio.CancelledError: pass if cleaned: print("CLEANUP_OK") asyncio.run(main()) ``` </details>

Checkpoint

Why does `asyncio.CancelledError` inherit from `BaseException` rather than `Exception`? 🧠

Practice

Create a coroutine `cancellable_job()` that enters `try: await asyncio.sleep(10)` and catches `asyncio.CancelledError`. Set a cleanup flag `cleaned = True`, re-raise the error. In `main()`, spawn the task, cancel it, catch the error on `await task`, and print `'CLEANUP_OK'` if the cleanup was reached. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks