Skip to content

Commit 6a59996

Browse files
committed
Collapse exception groups containing a single exception
1 parent 0c4871c commit 6a59996

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

trio/_core/_run.py

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,28 @@ class IdlePrimedTypes(enum.Enum):
118118
################################################################
119119

120120

121+
def collapse_exception_group(excgroup):
122+
"""Recursively collapse any single-exception groups into that single contained
123+
exception.
124+
125+
"""
126+
exceptions = list(excgroup.exceptions)
127+
modified = False
128+
for i, exc in enumerate(exceptions):
129+
if isinstance(exc, BaseExceptionGroup):
130+
new_exc = collapse_exception_group(exc)
131+
if new_exc is not exc:
132+
modified = True
133+
exceptions[i] = new_exc
134+
135+
if len(exceptions) == 1:
136+
return exceptions[0]
137+
elif modified:
138+
return excgroup.derive(exceptions)
139+
else:
140+
return excgroup
141+
142+
121143
@attr.s(eq=False, slots=True)
122144
class Deadlines:
123145
"""A container of deadlined cancel scopes.
@@ -514,8 +536,9 @@ def _close(self, exc):
514536
if matched:
515537
self.cancelled_caught = True
516538

517-
while isinstance(exc, BaseExceptionGroup) and len(exc.exceptions) == 1:
518-
exc = exc.exceptions[0]
539+
if isinstance(exc, BaseExceptionGroup):
540+
exc = collapse_exception_group(exc)
541+
519542
self._cancel_status.close()
520543
with self._might_change_registered_deadline():
521544
self._cancel_status = None

0 commit comments

Comments
 (0)