Skip to content

Commit 8345647

Browse files
committed
fix cases of exception in task group body before/after cancel()
1 parent f077241 commit 8345647

2 files changed

Lines changed: 18 additions & 4 deletions

File tree

Lib/asyncio/taskgroups.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -150,10 +150,6 @@ async def _aexit(self, et, exc):
150150
# If there are no pending cancellations left,
151151
# don't propagate CancelledError.
152152
propagate_cancellation_error = None
153-
# If Cancelled would actually be raised out of the TaskGroup,
154-
# suppress it-- this is significant when using stop().
155-
if not self._errors:
156-
return True
157153

158154
# Propagate CancelledError if there is one, except if there
159155
# are other errors -- those have priority.
@@ -184,6 +180,10 @@ async def _aexit(self, et, exc):
184180
finally:
185181
exc = None
186182

183+
# If we wanted to raise an error, it would have been done explicitly
184+
# above. Otherwise, either there is no error or we want to suppress
185+
# the original error.
186+
return True
187187

188188
def create_task(self, coro, *, name=None, context=None):
189189
"""Create a new task in this group and return it.

Lib/test/test_asyncio/test_taskgroups.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1063,6 +1063,20 @@ async def raise_exc(parent_tg: asyncio.TaskGroup):
10631063
tg.create_task(raise_exc(tg))
10641064
await asyncio.sleep(1)
10651065

1066+
async def test_taskgroup_body_cancel_before_exception(self):
1067+
with self.assertRaises(ExceptionGroup):
1068+
async with asyncio.TaskGroup() as tg:
1069+
tg.cancel()
1070+
raise RuntimeError
1071+
1072+
async def test_taskgroup_body_cancel_after_exception(self):
1073+
with self.assertRaises(ExceptionGroup):
1074+
async with asyncio.TaskGroup() as tg:
1075+
try:
1076+
raise RuntimeError
1077+
finally:
1078+
tg.cancel()
1079+
10661080

10671081
if __name__ == "__main__":
10681082
unittest.main()

0 commit comments

Comments
 (0)