Skip to content

Commit

Permalink
Collapse exception groups containing a single exception
Browse files Browse the repository at this point in the history
  • Loading branch information
agronholm committed Jan 25, 2022
1 parent 0c4871c commit 6a59996
Showing 1 changed file with 25 additions and 2 deletions.
27 changes: 25 additions & 2 deletions trio/_core/_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 6a59996

Please sign in to comment.