Sub topic 9
Cancelling tasks safely
This chapter assumes you can create tasks with asyncio.create_task, and that you know try/except/finally and how await suspends a coroutine.
How cancellation works
Calling task.cancel() does not stop a task immediately. It asks the event loop to raise asyncio.CancelledError inside the task at the point where it is currently suspended on an await. The task can then run cleanup code. If the exception propagates out of the coroutine, the task ends in the cancelled state.
Cleaning up and re-raising
import asyncio
async def worker():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("cleaning up")
raise
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0.1)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("worker cancelled")
asyncio.run(main())The output is cleaning up followed by worker cancelled. The worker prints, then re-raises. The caller sees the exception when it awaits the task.
Rules for safe cancellation
- Re-raise
CancelledError. If you catch it and do not re-raise, the task looks like it finished normally. Callers waiting on it, and tools such asTaskGroupandasyncio.timeout, may then behave incorrectly. - Prefer
finallyfor cleanup. Afinallyblock runs on success, on errors, and on cancellation, so you do not need a separateexceptclause. - Never use a bare
except:orexcept BaseException:without re-raising. Since Python 3.8,CancelledErrorinherits fromBaseException, soexcept Exception:does not catch it. That is intentional. - Keep cleanup short. If cleanup awaits something slow, a second
cancel()can interrupt it.
import asyncio
async def worker():
try:
await asyncio.sleep(10)
finally:
print("released resource")
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0.1)
task.cancel()
await asyncio.gather(task, return_exceptions=True)
print("cancelled:", task.cancelled())
asyncio.run(main())Here return_exceptions=True makes gather return the CancelledError as a value instead of raising it. Afterwards task.cancelled() returns True.
Protecting work with shield
Sometimes an operation must finish even if its caller is cancelled, such as committing a database transaction. asyncio.shield(awaitable) lets the outer await be cancelled while the inner work keeps running.
import asyncio
async def commit():
await asyncio.sleep(0.5)
print("committed")
async def main():
inner = asyncio.create_task(commit())
outer = asyncio.create_task(asyncio.shield(inner))
await asyncio.sleep(0.1)
outer.cancel()
await asyncio.sleep(1)
asyncio.run(main())committed still prints, even though outer was cancelled. Keep a reference to inner, because the shield does not keep it alive on its own.
Cancellation in groups
When one task in a TaskGroup fails, the group cancels its remaining tasks and then raises an ExceptionGroup. Cancellation is the normal way a group shuts down siblings, so every task you write should tolerate it.
Exercise
A coroutine catches asyncio.CancelledError, prints a message, and does not re-raise. What state does its task end in, and why is that a problem?
Show answer
The task ends as finished normally, not cancelled, so task.cancelled() is False. Code that awaits it, and mechanisms such as TaskGroup and asyncio.timeout that rely on cancellation propagating, may not see that cancellation happened. Re-raise the exception, or use finally for cleanup.