From 6a599967f86a2bb3d657fe98a54a930f9934f3ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20Gr=C3=B6nholm?= Date: Mon, 17 Jan 2022 01:15:49 +0200 Subject: [PATCH] Collapse exception groups containing a single exception --- trio/_core/_run.py | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/trio/_core/_run.py b/trio/_core/_run.py index fac3a7e122..592280abf2 100644 --- a/trio/_core/_run.py +++ b/trio/_core/_run.py @@ -118,6 +118,28 @@ class IdlePrimedTypes(enum.Enum): ################################################################ +def collapse_exception_group(excgroup): + """Recursively collapse any single-exception groups into that single contained + exception. + + """ + exceptions = list(excgroup.exceptions) + modified = False + for i, exc in enumerate(exceptions): + if isinstance(exc, BaseExceptionGroup): + new_exc = collapse_exception_group(exc) + if new_exc is not exc: + modified = True + exceptions[i] = new_exc + + if len(exceptions) == 1: + return exceptions[0] + elif modified: + return excgroup.derive(exceptions) + else: + return excgroup + + @attr.s(eq=False, slots=True) class Deadlines: """A container of deadlined cancel scopes. @@ -514,8 +536,9 @@ def _close(self, exc): if matched: self.cancelled_caught = True - while isinstance(exc, BaseExceptionGroup) and len(exc.exceptions) == 1: - exc = exc.exceptions[0] + if isinstance(exc, BaseExceptionGroup): + exc = collapse_exception_group(exc) + self._cancel_status.close() with self._might_change_registered_deadline(): self._cancel_status = None