Thanks to visit codestin.com
Credit goes to github.com

Skip to content

gh-101581 Optionally prevent child tasks from being cancelled in asyncio taskgroups #101648

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

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions Lib/asyncio/taskgroups.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ class TaskGroup:

Any exceptions other than `asyncio.CancelledError` raised within
a task will cancel all remaining tasks and wait for them to exit.
You can prevent this behavior by passing `defer_errors=True` to
the constructor.
The exceptions are then combined and raised as an `ExceptionGroup`.
"""
def __init__(self):
def __init__(self, defer_errors=False):
self._entered = False
self._exiting = False
self._aborting = False
Expand All @@ -36,6 +38,7 @@ def __init__(self):
self._errors = []
self._base_error = None
self._on_completed_fut = None
self._defer_errors = defer_errors

def __repr__(self):
info = ['']
Expand Down Expand Up @@ -198,7 +201,8 @@ def _on_task_done(self, task):
return

self._errors.append(exc)
if self._is_base_error(exc) and self._base_error is None:
is_base_error = self._is_base_error(exc)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @DontPanicO, I'm trying to understand why is_base_error is needed. Please help me understand why that is preferable to self._is_base_error(exc). Thanks!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @willingc . I stored self._is_base_error(exc) result in a variable since it's used twice: once on line 205 and once on line 238

if is_base_error and self._base_error is None:
self._base_error = exc

if self._parent_task.done():
Expand Down Expand Up @@ -231,6 +235,7 @@ def _on_task_done(self, task):
# pass
# await something_else # this line has to be called
# # after TaskGroup is finished.
self._abort()
self._parent_cancel_requested = True
self._parent_task.cancel()
if not self._defer_errors or is_base_error:
self._abort()
self._parent_cancel_requested = True
self._parent_task.cancel()
Loading