diff --git a/Lib/contextlib.py b/Lib/contextlib.py index f1b958b551af15..b1c39f2eab07e6 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -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. + return # Context may not be correct, so find the end of the chain while 1: exc_context = new_exc.__context__ @@ -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__ diff --git a/Lib/test/test_contextlib.py b/Lib/test/test_contextlib.py index e291f814edbd93..ff50c754f5b23e 100644 --- a/Lib/test/test_contextlib.py +++ b/Lib/test/test_contextlib.py @@ -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. diff --git a/Misc/NEWS.d/next/Library/2026-11-28-15-38-19.gh-issue-162738.OyAtKC.rst b/Misc/NEWS.d/next/Library/2026-11-28-15-38-19.gh-issue-162738.OyAtKC.rst new file mode 100644 index 00000000000000..ee7d69b76fb1dd --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-28-15-38-19.gh-issue-162738.OyAtKC.rst @@ -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.