Sub topic 15
Inside the machinery: Task.cancelling and Task.uncancel
This chapter explains the counter that lets asyncio.timeout and asyncio.TaskGroup tell their own cancellation requests apart from everyone else's. It assumes you know Task.cancel(), how CancelledError propagates, and how asyncio.timeout and TaskGroup are used. It needs Python 3.11 or newer. Most application code never calls the two methods described here, but you need them if you write your own cancellation-aware context manager or you deliberately swallow a cancellation.
The problem the counter solves
Task.cancel() works by throwing CancelledError into the task at its next await. The exception looks the same whoever asked for the cancellation. Consider this nesting:
asyncio.timeout()cancels the current task when its deadline expires. It then wants to turn thatCancelledErrorinto aTimeoutError.- A caller higher up, or a
TaskGroupwhose child failed, may also have cancelled the same task. In that case theCancelledErrormust keep propagating.
If the timeout converted every CancelledError it saw, it would swallow cancellation requests that belong to someone else. Python 3.11 solved this by giving each task a count of the cancellation requests it has received.
The two methods
| Method | What it does | Returns |
|---|---|---|
| `task.cancel()` | Requests cancellation and adds 1 to the task's request count | `True` if a request was scheduled, `False` if the task was already done |
| `task.cancelling()` | Reads the request count | The number of requests not yet withdrawn |
| `task.uncancel()` | Withdraws one request. It does nothing if the count is already 0 | The remaining count |
Two details matter:
- The count goes up on every
cancel()call, even when the task is already being cancelled. Three calls give a count of 3. uncancel()only changes the number. It does not stop aCancelledErrorthat is already on its way. Its job is bookkeeping: whoever took responsibility for a request says "I handled this one."
In Python 3.13 and later, uncancel() also clears the task's pending cancellation flag when the count drops to 0. This helps when the exception has not been delivered yet. On 3.11 and 3.12 you should assume it does not.
Reading the counter
The first program shows the counter around an asyncio.timeout block.
import asyncio
async def main():
task = asyncio.current_task()
try:
async with asyncio.timeout(0.1):
print("before:", task.cancelling())
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
print("during:", task.cancelling())
raise
except TimeoutError:
print("after:", task.cancelling())
asyncio.run(main())It prints before: 0, during: 1, after: 0. When the deadline passes, the timeout calls task.cancel(), so the count becomes 1. As the block exits, the timeout calls task.uncancel(), which brings the count back to 0, and raises TimeoutError. The task leaves the block in the same state it entered, which is the point of the design.
How asyncio.timeout decides
When asyncio.timeout enters, it records the current value of task.cancelling(). When the block exits with a CancelledError after the deadline fired, it calls uncancel() and compares the result with the recorded value:
- If the remaining count is at or below the recorded value, the only outstanding request was the timeout's own. The timeout raises
TimeoutError. - If the remaining count is higher, someone else also cancelled the task. The timeout lets the
CancelledErrorcontinue upward.
This is why a timeout inside a task that is being cancelled from outside does not turn into a TimeoutError. A cancelled await should look like a cancellation to the caller, and the counter keeps it that way.
TaskGroup uses the same counter
A TaskGroup has the same problem. When a child task fails, the group must interrupt the code in its own async with body, so it cancels the parent task. Later, when it raises an ExceptionGroup, it must undo that cancel. Otherwise the parent would look cancelled to code outside the group.
import asyncio
async def broken():
await asyncio.sleep(0.1)
raise ValueError("child failed")
async def main():
task = asyncio.current_task()
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(broken())
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
print("in body:", task.cancelling())
raise
except* ValueError:
print("after group:", task.cancelling())
asyncio.run(main())The output is in body: 1 and then after group: 0. The group cancels the parent once, however many children fail. At exit it calls uncancel() for that one request. If the count is still above zero at that point, an outside caller also cancelled the parent. The group then lets the cancellation propagate, with the child errors attached if there are any, instead of hiding it.
Swallowing a cancellation on purpose
Normally you re-raise CancelledError. Sometimes a task really should survive, for example a supervisor loop that catches a cancellation aimed at one unit of work and carries on. If you stop a cancellation, you also have to withdraw it from the count:
import asyncio
async def main():
task = asyncio.current_task()
task.cancel()
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
print("cancelling:", task.cancelling())
task.uncancel()
print("after uncancel:", task.cancelling())
await asyncio.sleep(0.1)
print("still running")
asyncio.run(main())The task cancels itself so the example is deterministic. The output is cancelling: 1, after uncancel: 0, still running. Without the uncancel() call, the task would keep reporting cancelling() == 1. Any timeout or TaskGroup it entered afterwards would then compare against a count that includes a dead request.
Common mistakes
- Catching
CancelledErrorand not re-raising it. The task keeps running, but the count stays at 1 and any latertimeoutblock inherits that state. Re-raise, or calluncancel()deliberately. - Calling
uncancel()from inside afinallyblock as routine cleanup. Cleanup runs on every exit path, including the paths where no cancellation happened. That drives the count away from the real number of requests. - Checking
cancelling()and treating it as a boolean "is cancelled" flag. A value of 0 does not mean noCancelledErroris in flight. In Python 3.11 and 3.12 a request that has not yet been delivered still counts, and one you have uncancelled may still be delivered. Use the count to compare against a baseline, astimeoutdoes. - Expecting
uncancel()to resurrect a finished task. If a task has already ended withCancelledError, nothing can bring it back.
A pattern for your own context managers
If you write a context manager that cancels the current task, follow the same protocol that asyncio.timeout uses:
- On entry, store
task.cancelling(). - When your condition fires, call
task.cancel(). - On exit, if you caused a cancellation and see
CancelledError, calltask.uncancel(). - Convert the error into your own exception only if the result is at or below the stored value. Otherwise re-raise the
CancelledError.
For most work you do not need to, because asyncio.timeout and asyncio.TaskGroup already implement this protocol. The asyncio.timeout documentation describes it in terms of reschedule() and when() if you need to move a deadline.
Exercise
A task enters async with asyncio.timeout(1). Before the deadline, another task calls outer.cancel() on it. Then the deadline passes while the CancelledError is still being handled. After the timeout calls uncancel() on exit, the count is higher than the value it recorded on entry. Does the caller see TimeoutError or CancelledError, and why?
Show answer
The caller sees CancelledError. The timeout recorded cancelling() on entry. The outside cancel() raised the count above that value, so after the timeout withdrew its own request the count was still above the recorded value. That shows another party also cancelled the task, so the timeout lets CancelledError propagate instead of converting it to TimeoutError.
Exercise
In the TaskGroup example, what would task.cancelling() return inside the except asyncio.CancelledError handler if two children failed at nearly the same time, and why?
Show answer
It would still return 1. The group cancels its parent task only once, no matter how many children fail, and it withdraws that one request with uncancel() when the group exits.