Sub topic 15
Inside the machinery: Task.cancelling and Task.uncancel
This chapter assumes you know TaskGroup, asyncio.timeout, and how CancelledError works. Most code never calls Task.cancelling() or Task.uncancel() directly. They explain how timeout and TaskGroup can tell their own cancellation apart from one that comes from outside.
The problem these methods solve
Both timeout and TaskGroup cancel the task running their block by calling cancel(). The block then ends with CancelledError. The context manager has to decide:
- Did I cause this cancellation? If so, convert it into
TimeoutError, or into anExceptionGroupfor aTaskGroup. - Did someone else cancel this task? If so, let
CancelledErrorkeep propagating.
A single "was cancelled" flag can't answer this, because several parties may request cancellation of the same task.
A counter of cancellation requests
Each task keeps a count of pending cancellation requests.
| Method | Effect |
|---|---|
| `task.cancel()` | Requests cancellation and increments the count. |
| `task.cancelling()` | Returns the current count. |
| `task.uncancel()` | Decrements the count (never below zero) and returns the new value. |
CancelledError being raised does not reset the count. Only uncancel() lowers it.
import asyncio
async def worker():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
print("in handler:", asyncio.current_task().cancelling())
raise
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0)
print("before:", task.cancelling())
task.cancel()
task.cancel()
print("after two cancel calls:", task.cancelling())
try:
await task
except asyncio.CancelledError:
print("finished:", task.cancelling(), task.cancelled())
asyncio.run(main())The output is before: 0, after two cancel calls: 2, in handler: 2, and finished: 2 True. The worker receives a single CancelledError, but the count records both requests.
How timeout uses the count
When you enter asyncio.timeout, it records the task's current cancelling() value. If the deadline passes, it calls task.cancel(). When the block exits with CancelledError, it calls uncancel() and compares the result with the recorded value.
- If the count is back at or below the recorded value, the only cancellation was its own. It raises
TimeoutError. - If the count is still higher, someone else also cancelled the task.
CancelledErrorpropagates.
TaskGroup follows the same logic when one child fails and the group cancels its parent task.
import asyncio
async def main():
task = asyncio.current_task()
try:
async with asyncio.timeout(0.1):
await asyncio.sleep(1)
except TimeoutError:
print("count after timeout:", task.cancelling())
asyncio.run(main())This prints count after timeout: 0. The timeout raised the count to 1 and then lowered it again.
When you should call uncancel yourself
Call uncancel() only when you deliberately swallow a CancelledError and keep the task running. This is rare. If you catch the error and continue without calling it, the count stays raised. A later timeout or TaskGroup in that task may then misread the leftover count as an outside cancellation.
Key points
cancel()adds to the count,uncancel()subtracts, andcancelling()reads it.timeoutandTaskGroupcompare the count against a snapshot taken on entry to see whether a cancellation was theirs.- Application code rarely needs these methods. Re-raise
CancelledErrorand the machinery works.
Exercise
A task has cancelling() equal to 1 when it enters asyncio.timeout(5). Another coroutine then calls task.cancel() before the deadline. When the block exits with CancelledError, does the timeout raise TimeoutError? Why or why not?
Show answer
No. On entry the timeout recorded 1. The outside cancel() raised the count to 2. The deadline never passed, so the timeout never cancelled the task itself. When the block exits, the timeout does not claim the cancellation, because its own request was never made. CancelledError propagates. Even if the deadline had also fired, the count after uncancel() would still be above the recorded value, and the result would be the same.