Sub topic 2
Handling `CancelledError` and Cleaning Up Safely
Assume Python 3.11 or newer, async/await, try/finally, context managers, and asyncio.run. This chapter focuses on cancellation, structured concurrency, and task groups.
Handle cancellation with `finally`
Cancellation is a request to stop a task. When the task reaches its next suspension point, such as await asyncio.sleep(...), Python raises asyncio.CancelledError inside that task.
Use finally for cleanup. Cleanup might close a connection, release a lock, or remove a temporary file. Usually, let CancelledError continue to the caller. Do not silently swallow it.
import asyncio
async def worker():
try:
while True:
await asyncio.sleep(0.1)
finally:
print("releasing resources")
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0.25)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("worker stopped")
asyncio.run(main())CancelledError is not an ordinary application failure. Catch it only when you need to perform a specific action, and then re-raise it.
Structured concurrency and `TaskGroup`
Structured concurrency keeps child tasks inside the scope that created them. The parent does not finish until its children finish, fail, or are cancelled. This prevents tasks from becoming orphaned after their owner returns.
asyncio.TaskGroup provides this structure. Create tasks inside its async with block. When the block exits normally, all tasks have completed.
import asyncio
async def fetch(name, delay):
await asyncio.sleep(delay)
return f"{name} done"
async def main():
async with asyncio.TaskGroup() as group:
first = group.create_task(fetch("a", 0.2))
second = group.create_task(fetch("b", 0.1))
print(first.result(), second.result())
asyncio.run(main())Handle grouped failures
If one task raises an exception, the group cancels unfinished siblings and waits for their cleanup. It then raises an ExceptionGroup, which contains the failure or failures. Use except* to handle matching exception types.
import asyncio
async def broken():
await asyncio.sleep(0.1)
raise ValueError("bad response")
async def main():
try:
async with asyncio.TaskGroup() as group:
group.create_task(broken())
group.create_task(asyncio.sleep(10))
except* ValueError as errors:
print("handled:", errors.exceptions)
asyncio.run(main())Exercise
Why should a cancelled worker re-raise CancelledError after cleanup?
Show answer
So its parent task, TaskGroup, or timeout can observe cancellation and finish shutdown correctly.