-
-
Notifications
You must be signed in to change notification settings - Fork 34.5k
gh-108951: add TaskGroup.cancel() #127214
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 17 commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
8ec2f60
add TaskGroup.stop()
belm0 907f1d0
📜🤖 Added by blurb_it.
blurb-it[bot] 2cfa1e6
minor doc fixes
belm0 bce1fb1
make tests more explicit
belm0 7754aad
use versionadded:: next
belm0 452042d
stop() -> cancel()
belm0 f077241
document some ways to use cancel()
belm0 8345647
fix cases of exception in task group body before/after cancel()
belm0 7235c20
add test for create_task() following cancel()
belm0 243db79
Merge branch 'main' into task_group_stop
asvetlov e36a1af
apply comment revision
belm0 5ae5ee9
expand news entry
belm0 c83d853
Remove stray quote in NEWS
gvanrossum 5bba130
Merge branch 'main' into task_group_stop
gvanrossum 1ce0b40
suppress lint error for removed doc ID terminating-a-task-group
belm0 e8617b4
move test methods back to BaseTestTaskGroup (caused by bad merge)
belm0 8710b95
add race test
belm0 2cd33e3
small doc refinements
belm0 edcd97e
fix doc lint
belm0 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -355,6 +355,33 @@ and reliable way to wait for all tasks in the group to finish. | |
|
|
||
| Passes on all *kwargs* to :meth:`loop.create_task` | ||
|
|
||
| .. method:: cancel() | ||
|
|
||
| Cancel the task group. | ||
|
|
||
| :meth:`~asyncio.Task.cancel` will be called on any tasks in the group that | ||
| aren't yet done, as well as the parent (body) of the group. This will | ||
| cause the task group context manager to exit *without* | ||
| :exc:`asyncio.CancelledError` being raised. | ||
|
|
||
| If :meth:`cancel` is called before entering the task group, the group will be | ||
| cancelled upon entry. This is useful for patterns where one piece of | ||
| code passes an unused :class:`asyncio.TaskGroup` instance to another in order to have | ||
| the ability to cancel anything run within the group. | ||
|
|
||
| :meth:`cancel` is idempotent and may be called after the task group has | ||
| already exited. | ||
|
|
||
| Ways to use :meth:`cancel`: | ||
|
|
||
| * call it from the task group body based on some condition or event | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Probably you want code examples for all of these? |
||
| * pass the task group instance to child tasks via :meth:`create_task`, allowing a child | ||
| task to conditionally cancel the entire entire group | ||
| * pass the task group instance or bound :meth:`cancel` method to some other task *before* | ||
| opening the task group, allowing remote cancellation | ||
|
gvanrossum marked this conversation as resolved.
|
||
|
|
||
| .. versionadded:: next | ||
|
|
||
| Example:: | ||
|
|
||
| async def main(): | ||
|
|
@@ -427,53 +454,6 @@ reported by :meth:`asyncio.Task.cancelling`. | |
| Improved handling of simultaneous internal and external cancellations | ||
| and correct preservation of cancellation counts. | ||
|
|
||
| Terminating a task group | ||
| ------------------------ | ||
|
|
||
| While terminating a task group is not natively supported by the standard | ||
| library, termination can be achieved by adding an exception-raising task | ||
| to the task group and ignoring the raised exception: | ||
|
|
||
| .. code-block:: python | ||
|
|
||
| import asyncio | ||
| from asyncio import TaskGroup | ||
|
|
||
| class TerminateTaskGroup(Exception): | ||
| """Exception raised to terminate a task group.""" | ||
|
|
||
| async def force_terminate_task_group(): | ||
| """Used to force termination of a task group.""" | ||
| raise TerminateTaskGroup() | ||
|
|
||
| async def job(task_id, sleep_time): | ||
| print(f'Task {task_id}: start') | ||
| await asyncio.sleep(sleep_time) | ||
| print(f'Task {task_id}: done') | ||
|
|
||
| async def main(): | ||
| try: | ||
| async with TaskGroup() as group: | ||
| # spawn some tasks | ||
| group.create_task(job(1, 0.5)) | ||
| group.create_task(job(2, 1.5)) | ||
| # sleep for 1 second | ||
| await asyncio.sleep(1) | ||
| # add an exception-raising task to force the group to terminate | ||
| group.create_task(force_terminate_task_group()) | ||
| except* TerminateTaskGroup: | ||
| pass | ||
|
|
||
| asyncio.run(main()) | ||
|
|
||
| Expected output: | ||
|
|
||
| .. code-block:: text | ||
|
|
||
| Task 1: start | ||
| Task 2: start | ||
| Task 1: done | ||
|
|
||
| Sleeping | ||
| ======== | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
|
belm0 marked this conversation as resolved.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 change: 1 addition & 0 deletions
1
Misc/NEWS.d/next/Library/2024-11-24-07-18-40.gh-issue-108951.jyKygP.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Add :meth:`~asyncio.TaskGroup.cancel` which cancels unfinished tasks and exits the group without error. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.