Sub topic 5
How task cancellation works
This chapter assumes Python 3.11 or newer, familiarity with async/await, and comfort with try/finally. It also assumes you can start a task with asyncio.create_task.
Cancellation is a request
Calling task.cancel() does not stop a task. It asks the event loop to raise asyncio.CancelledError inside the task. The error appears at the point where the task is currently suspended, which is its next await. The task then unwinds like any other exception: finally blocks run, and context managers exit.
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 loops until main cancels it. The finally block prints its message, and then the error reaches main through await task.
What cancel() returns and how to check the result
cancel() returns True if the request was made. It returns False if the task had already finished. A True result does not mean the task has stopped. Use these tools to learn what happened:
| Call | Meaning |
|---|---|
| `task.cancel()` | Request cancellation. |
| `task.cancelled()` | `True` only after the task has ended because of cancellation. |
| `task.done()` | `True` once the task has finished in any way. |
| `await task` | Raises `CancelledError` if the task ended cancelled. |
If you do not need the task's result, you still need to await it after cancelling. Awaiting waits for the cleanup to finish and prevents a "Task exception was never retrieved" style warning.
Properties that cause surprises
- Cancellation needs an await. A task that runs a long loop without awaiting cannot be cancelled until it yields to the event loop.
- CancelledError is not an Exception. It inherits from
BaseException, soexcept Exceptiondoes not catch it. A bareexcept:orexcept BaseException:does catch it, and you should avoid both. - Cancellation passes down. If a task is awaiting another task or future, cancelling the outer task cancels the inner one too.
- A task can refuse. If code catches
CancelledErrorand does not re-raise it, the task keeps running. The caller who cancelled it assumes it stopped, so this is almost always a bug.
A task that ignores cancellation
This example shows the failure mode. The task catches the error and carries on:
import asyncio
async def stubborn():
for i in range(3):
try:
await asyncio.sleep(0.2)
except asyncio.CancelledError:
print("ignored cancellation", i)
return "finished anyway"
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 task prints ignored cancellation 0, runs to the end, and returns normally. task.cancelled() is False, because the task did not end by cancellation. The next chapter covers how to handle CancelledError correctly.
Exercise
A task is suspended in await asyncio.sleep(5). You call task.cancel() and get True. Is it guaranteed that task.cancelled() becomes True? Explain.
Show answer
No. True from cancel() only means the request was scheduled. The task receives CancelledError at its await, and if its code catches the error and does not re-raise it, the task continues and cancelled() stays False. It becomes True only if the error propagates out of the task.