Skip to content

Commit d32401f

Browse files
committed
Collapse exception groups containing a single exception
1 parent 7c8ca82 commit d32401f

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

trio/_core/_run.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,28 @@ class IdlePrimedTypes(enum.Enum):
130130
################################################################
131131

132132

133+
def collapse_exception_group(excgroup):
134+
"""Recursively collapse any single-exception groups into that single contained
135+
exception.
136+
137+
"""
138+
exceptions = list(excgroup.exceptions)
139+
modified = False
140+
for i, exc in enumerate(exceptions):
141+
if isinstance(exc, BaseExceptionGroup):
142+
new_exc = collapse_exception_group(exc)
143+
if new_exc is not exc:
144+
modified = True
145+
exceptions[i] = new_exc
146+
147+
if len(exceptions) == 1:
148+
return exceptions[0]
149+
elif modified:
150+
return excgroup.derive(exceptions)
151+
else:
152+
return excgroup
153+
154+
133155
@attr.s(eq=False, slots=True)
134156
class Deadlines:
135157
"""A container of deadlined cancel scopes.
@@ -526,8 +548,11 @@ def _close(self, exc):
526548
if matched:
527549
self.cancelled_caught = True
528550

529-
while isinstance(exc, BaseExceptionGroup) and len(exc.exceptions) == 1:
530-
exc = exc.exceptions[0]
551+
if isinstance(exc, BaseExceptionGroup):
552+
print("flattening", repr(exc))
553+
exc = collapse_exception_group(exc)
554+
print(" result:", repr(exc))
555+
531556
self._cancel_status.close()
532557
with self._might_change_registered_deadline():
533558
self._cancel_status = None

0 commit comments

Comments
 (0)