Skip to content

Commit 2811031

Browse files
committed
gh-141186: Document asyncio Task cancellation propagation behavior
Clarifies that cancelling a Task awaiting another Task or Future will also cancel the awaited object. This behavior was undocumented despite being fundamental to asyncio's cancellation architecture. Changes: - Updated general Task description to mention Task cancellation propagation - Added explicit explanation in Task.cancel() method documentation - Clarified that Tasks inherit Future's cancellation behavior Addresses issue #141186 where users were unaware this cancellation propagation was intentional architectural behavior, not a side effect. The fix uses the exact wording suggested by the issue reporter and documents the _fut_waiter implementation behavior that enables the propagation down entire await chains.
1 parent d13ee0a commit 2811031

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

Doc/library/asyncio-task.rst

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1221,8 +1221,8 @@ Task Object
12211221

12221222
To cancel a running Task use the :meth:`cancel` method. Calling it
12231223
will cause the Task to throw a :exc:`CancelledError` exception into
1224-
the wrapped coroutine. If a coroutine is awaiting on a Future
1225-
object during cancellation, the Future object will be cancelled.
1224+
the wrapped coroutine. If a coroutine is awaiting on a future-like
1225+
object during cancellation, the awaited object will be cancelled.
12261226

12271227
:meth:`cancelled` can be used to check if the Task was cancelled.
12281228
The method returns ``True`` if the wrapped coroutine did not
@@ -1231,7 +1231,8 @@ Task Object
12311231

12321232
:class:`asyncio.Task` inherits from :class:`Future` all of its
12331233
APIs except :meth:`Future.set_result` and
1234-
:meth:`Future.set_exception`.
1234+
:meth:`Future.set_exception`. This includes the cancellation
1235+
behavior: Tasks can be cancelled in the same way as Futures.
12351236

12361237
An optional keyword-only *context* argument allows specifying a
12371238
custom :class:`contextvars.Context` for the *coro* to run in.
@@ -1411,6 +1412,10 @@ Task Object
14111412
the cancellation, it needs to call :meth:`Task.uncancel` in addition
14121413
to catching the exception.
14131414

1415+
If the Task being cancelled is currently awaiting a future-like
1416+
object, that awaited object will also be cancelled. This cancellation
1417+
propagates down the entire chain of awaited objects.
1418+
14141419
.. versionchanged:: 3.9
14151420
Added the *msg* parameter.
14161421

0 commit comments

Comments
 (0)