menu_book Course Curriculum (Python) expand_more
Cancellation handling
Learn Cancellation handling in Python with a focused explanation, a dedicated runnable example, and a relevant engineering boundary.
Cancellation handling is an atomic Python topic in Concurrency and Asynchronous Python. This lesson isolates the construct so you can see what it changes, what value or state it produces, and which surrounding rules matter.
The example below is written specifically for Cancellation handling. Run it once as shown, trace the observable result, then modify the relevant operand, argument, input, or state. Do not replace the construct with a neighboring feature: the purpose is to learn this exact behavior in context.
Topic-specific example
import asyncio
async def worker():
try: await asyncio.sleep(10)
except asyncio.CancelledError:
print("cleanup"); raise
async def main():
task=asyncio.create_task(worker()); await asyncio.sleep(0); task.cancel()
try: await task
except asyncio.CancelledError: print("cancelled")
asyncio.run(main())
Use Cancellation handling for the behavior demonstrated here, then change one input that stresses its boundary. The important result is the behavior of this exact construct, not merely that the code runs.