Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Lib/contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,9 @@ def __exit__(self, *exc_details):
# we were actually nesting multiple with statements
frame_exc = sys.exception()
def _fix_exception_context(new_exc, old_exc):
if new_exc is old_exc:
# Re-raising the pending exception preserves its context.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment doesn't seem to be relevant.

return
# Context may not be correct, so find the end of the chain
while 1:
exc_context = new_exc.__context__
Expand Down Expand Up @@ -764,6 +767,9 @@ async def __aexit__(self, *exc_details):
# we were actually nesting multiple with statements
frame_exc = sys.exception()
def _fix_exception_context(new_exc, old_exc):
if new_exc is old_exc:
# Re-raising the pending exception preserves its context.
return
# Context may not be correct, so find the end of the chain
while 1:
exc_context = new_exc.__context__
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1170,6 +1170,25 @@ def suppress_exc(*exc_details):
self.assertIsInstance(inner_exc, ValueError)
self.assertIsInstance(inner_exc.__context__, ZeroDivisionError)

def test_exit_exception_reraise_preserves_context(self):
def reraise(exc_type, exc, tb):
raise exc

def raise_cleanup_error():
raise cleanup_error

body_error = ValueError("body")
cleanup_error = LookupError("cleanup")
with self.assertRaises(LookupError) as caught:
with self.exit_stack() as stack:
stack.push(reraise)
stack.callback(raise_cleanup_error)
raise body_error

self.assertIs(caught.exception, cleanup_error)
self.assertIs(cleanup_error.__context__, body_error)
self.assertIsNone(body_error.__context__)

def test_exit_exception_explicit_none_context(self):
# Ensure ExitStack chaining matches actual nested `with` statements
# regarding explicit __context__ = None.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Prevent :class:`contextlib.ExitStack` and :class:`contextlib.AsyncExitStack`
from creating a self-referential exception context when an exit callback
re-raises the pending exception.
Loading