Sub topic 6
Handling CancelledError and cleaning up safely
This chapter assumes Python 3.11 or newer, and that you know asyncio.create_task, Task.cancel(), and try/finally. It covers what happens inside a task once it is cancelled, how to run cleanup code, and how to avoid hiding a cancellation request.
What CancelledError is
Task.cancel() does not stop a task directly. It asks the event loop to raise asyncio.CancelledError inside the task at the point where the task is suspended, which is the await it is currently waiting on. From there it behaves like any exception. It travels up through the task's frames, runs finally blocks, and ends the task if nothing stops it.
Since Python 3.8, CancelledError inherits from BaseException, not Exception. This is deliberate. Cancellation is a control signal, not a failure, so ordinary error handling should not catch it by accident.
| Handler | Catches CancelledError? |
|---|---|
| `except Exception:` | No |
| `except asyncio.CancelledError:` | Yes |
| `except BaseException:` | Yes |
| bare `except:` | Yes |
| `finally:` | Runs, but does not stop the exception |
Cleaning up with finally
For most code, finally is the right tool. It runs whether the task finishes normally, fails, or is cancelled.
import asyncio
async def worker():
try:
while True:
await asyncio.sleep(0.1)
finally:
print("worker: releasing resources")
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0.35)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("worker was cancelled")
asyncio.run(main())The worker prints its cleanup message first. After that, await task re-raises CancelledError in main, which catches it. The task ends in the "cancelled" state, and task.cancelled() returns True.
The sequence below shows the order of events.
Awaiting inside cleanup
Cleanup often needs to be asynchronous, for example closing a connection or flushing a buffer. You can await inside a finally block, even while a CancelledError is propagating.
import asyncio
class Connection:
async def close(self):
await asyncio.sleep(0.05)
print("connection closed")
async def worker():
conn = Connection()
try:
while True:
await asyncio.sleep(0.1)
finally:
await conn.close()
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0.25)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("worker was cancelled")
asyncio.run(main())This works because one cancel() call raises CancelledError once. It does not make every later await fail. There are two limits to keep in mind:
- A second
cancel()during cleanup interrupts theawait conn.close()with a newCancelledError, and the rest of the cleanup is skipped. - Cleanup that can hang, such as a network close with no timeout, can keep the task alive after cancellation was requested.
Keep cleanup short and bounded. If a cleanup step might block, give it its own deadline with asyncio.timeout, which a later chapter covers.
Catching CancelledError and re-raising
Sometimes you need to react only to cancellation, for example to log it or save partial state. Catch it, do the work, and re-raise.
import asyncio
async def worker():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("worker: cancel received, saving state")
await asyncio.sleep(0.05)
raise
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0.1)
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
print("cancelled:", task.cancelled())
asyncio.run(main())The output ends with cancelled: True. A bare raise re-raises the same exception object, so the task ends cancelled.
The swallowing bug
If you catch CancelledError and do not re-raise it, the task treats cancellation as handled. It carries on or returns normally, and the code that requested the cancellation is never told.
import asyncio
async def bad_worker():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("ignoring cancellation")
async def main():
try:
async with asyncio.timeout(0.2):
await bad_worker()
except TimeoutError:
print("timed out")
else:
print("no TimeoutError: the deadline was hidden")
asyncio.run(main())The timeout fires and cancels the task, but bad_worker swallows the CancelledError. The async with block then exits normally, so asyncio.timeout has no CancelledError to convert into TimeoutError. The caller sees a normal return, and the run takes about 0.2 seconds instead of failing.
TaskGroup has the same problem. It cancels sibling tasks when one fails, and a sibling that swallows the signal keeps running and delays the group from finishing.
A linter will not catch most swallowing bugs. Review any except clause that can catch CancelledError, and check that it ends in raise or that you have a documented reason for it not to.
Cancelling a task you own versus being cancelled
Code that cancels a child task often wraps the await in except CancelledError:
task.cancel()
try:
await task
except asyncio.CancelledError:
passThis is fine when you cancelled task and nothing else is going on. It has a gap, though. If the code running this snippet is itself cancelled while it waits at await task, the same handler swallows that cancellation too. The Task.cancelling and Task.uncancel chapter explains how to tell the two cases apart. For now, treat this pattern as acceptable only for short-lived cleanup in code you control.
Edge cases
- Cancelled before it starts. A task that is cancelled before its first step never runs its body. Its
try/finallyblocks do not execute, because they were never entered. Acquire resources inside thetry, or in the caller, and do not assume the first line of the coroutine will run. - Already finished.
cancel()on a finished task does nothing and returnsFalse. - Cancel messages.
task.cancel(msg="shutting down")attaches a message to theCancelledError. This helps when logging why something was cancelled. - Cancellation only happens at an await. A task in a tight loop with no
awaitcannot be cancelled until it next suspends. - Returning a value does not help. A task cancelled at an
awaitthat you handle by returning a value is no longer reported as cancelled.task.cancelled()isFalse, and its result is that value.
Exercise
A coroutine wraps its body in try: ... except BaseException: log("failed"), with no re-raise. A caller cancels it inside asyncio.timeout(1). What does the caller see, and how should the handler be fixed?
Show answer
The handler catches CancelledError because it inherits from BaseException, and does not re-raise it. The coroutine returns normally, so asyncio.timeout never sees a CancelledError and raises no TimeoutError. The caller sees a normal return. The fix is to catch Exception instead, or to add raise at the end of the BaseException handler.
Exercise
Write a coroutine poller() that loops with await asyncio.sleep(0.1). When cancelled, it must print "flushing", await a 0.05-second sleep to simulate a flush, then end as a cancelled task. How can you check that it ended as cancelled?
Show answer
Use try: while True: await asyncio.sleep(0.1) with except asyncio.CancelledError: print("flushing"); await asyncio.sleep(0.05); raise. A finally block with the same two lines also works. After awaiting the task in a try/except asyncio.CancelledError, task.cancelled() returns True.