Sub topic 9
Cancelling tasks safely
This chapter assumes you can create tasks with asyncio.create_task, await them, and use try/finally. Here you will learn what task.cancel() does, how to write coroutines that clean up when cancelled, and which mistakes make cancellation silently fail.
What cancellation is
Cancellation is a request. Calling task.cancel() does not stop the task immediately. It schedules a CancelledError to be raised inside the task's coroutine at the point where it is currently suspended, which is the await it is waiting on. The task can run cleanup code, and then the exception propagates out and the task ends in the cancelled state.
Three consequences follow from this:
- A task can only be cancelled at an
await. A coroutine running a long loop with noawaitnever sees the request. - The coroutine decides what happens next. It can clean up and re-raise, or it can (wrongly) swallow the exception.
cancel()returns right away. It returnsTrueif the request was made andFalseif the task was already done. You must still await the task to know it has finished.
A basic cancellation
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 bare raise is what makes the task finish as cancelled. Without it, the task would finish normally. The await task in main raises CancelledError because awaiting a cancelled task re-raises the exception in the waiter.
After the task finishes, you can check task.cancelled(). It returns True only if the task ended because of a cancellation.
CancelledError is not an ordinary exception
Since Python 3.8, CancelledError inherits from BaseException, not Exception. This is deliberate. A handler written as except Exception: does not catch it, so ordinary error handling does not accidentally block cancellation.
A bare except: and except BaseException: do catch it. Avoid both in async code, or re-raise inside them.
Cleanup with try/finally
Prefer finally (or async with) for cleanup. It runs whether the task succeeded, failed, or was cancelled, and it never needs to remember to re-raise.
import asyncio
async def worker(name):
try:
print(name, "working")
await asyncio.sleep(10)
finally:
await asyncio.sleep(0.1) # asynchronous cleanup, such as closing a connection
print(name, "closed")
async def main():
tasks = [asyncio.create_task(worker(n)) for n in "ab"]
await asyncio.sleep(0.1)
for t in tasks:
t.cancel()
results = await asyncio.gather(*tasks, return_exceptions=True)
print(results)
asyncio.run(main())Both workers print working, then a closed and b closed. The final line is [CancelledError(), CancelledError()]. Passing return_exceptions=True to gather collects the cancellations as values. Without it, the first CancelledError would propagate out of main. Awaiting the cancelled tasks matters because it gives their cleanup time to finish before the program moves on.
Cleanup code can itself await, as shown above. Keep it short, because a cancelled task that takes a long time to clean up holds up whoever is waiting for it.
The most common bug: swallowing CancelledError
Here is a task that catches the exception and carries on:
import asyncio
async def stubborn():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("ignoring cancel")
return "finished normally"
async def main():
task = asyncio.create_task(stubborn())
await asyncio.sleep(0.1)
task.cancel()
print(await task)
print("cancelled?", task.cancelled())
asyncio.run(main())The output is ignoring cancel, finished normally, and cancelled? False. The caller asked for cancellation and the task refused. This breaks tools built on cancellation, such as asyncio.timeout and TaskGroup, because they rely on the exception propagating. Catch CancelledError only to do cleanup, and then re-raise it.
A related trap is a retry loop like this:
while True:
try:
await do_work()
except BaseException: # wrong: also catches CancelledError
continueThis loop can never be cancelled. Catch Exception instead.
Cancelling a task that has not started
If you call cancel() on a task before it has run its first step, the coroutine body never executes. No except CancelledError inside the coroutine runs, because the coroutine was never entered. This is why cleanup that must always happen belongs in resources managed outside the coroutine, or in code that surrounds the awaiting call, not only in a handler at the top of the coroutine.
Cancelling groups of tasks
You rarely cancel tasks one by one in real programs. Several tools cancel for you:
| Situation | What gets cancelled |
|---|---|
| You cancel the task that is awaiting `gather(...)` | Every child awaitable still running |
| One child of a `TaskGroup` raises an exception | All sibling tasks in that group |
| An `asyncio.timeout` block expires | The task running the block, at its current `await` |
| `asyncio.run` finishes its main coroutine | All tasks still pending, before the loop closes |
The TaskGroup rule is the main reason it is called structured concurrency: no task outlives the block that created it, and a failure does not leave siblings running. The previous chapters covered the group's behavior. What matters here is that your tasks must handle cancellation correctly, because the group relies on it.
Keep references to tasks you create with create_task. The loop holds only weak references, so a task nobody references can be garbage-collected mid-run, and you cannot cancel what you cannot find.
Protecting work with asyncio.shield
Sometimes one operation must complete even if the code waiting for it is cancelled, such as writing a record to a database. asyncio.shield wraps an awaitable so that cancelling the outer waiter does not cancel the inner work.
import asyncio
async def save(record):
await asyncio.sleep(0.5)
print("saved", record)
async def handler():
inner = asyncio.create_task(save("A"))
await asyncio.shield(inner)
async def main():
task = asyncio.create_task(handler())
await asyncio.sleep(0.1)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("handler cancelled")
await asyncio.sleep(1) # give the shielded save time to finish
asyncio.run(main())The output is handler cancelled, then saved A. The handler is cancelled, but save keeps running to completion.
Rules of thumb
- Use
try/finallyorasync withfor cleanup instead of catchingCancelledError. - If you do catch
CancelledError, re-raise it after cleanup. - Never use a bare
except:orexcept BaseException:in async code without re-raising. - Await a cancelled task, with
gather(..., return_exceptions=True)for several, so its cleanup completes. - Put
awaitpoints in long loops. A loop that never yields cannot be cancelled and also blocks every other task. - Use
shieldsparingly, only for work that must survive its caller.
Exercise
A task runs try: await asyncio.sleep(10) followed by except asyncio.CancelledError: print("bye"), with no raise. You call task.cancel() and then await task. Does await task raise CancelledError? What does task.cancelled() return, and how do you fix the coroutine?
Show answer
No. The coroutine catches the exception and returns normally, so await task returns the coroutine's result and does not raise. task.cancelled() returns False. To fix it, add a bare raise after the print, or move the cleanup into a finally block so the exception propagates on its own.
Exercise
You start three tasks and cancel all of them with t.cancel() in a loop, then call await asyncio.gather(*tasks). What happens, and what change lets the program continue to the next line while still waiting for every task to finish its cleanup?
Show answer
The first CancelledError raised by a child propagates out of gather, so the next line does not run normally. Use await asyncio.gather(*tasks, return_exceptions=True). The cancellations are then returned as values in the result list, and gather waits for all tasks to finish.