[Python-checkins] gh-92118: fix traceback of exceptions propagated from inside a contextlib.contextmanager (GH-92202)

iritkatriel webhook-mailer at python.org
Wed May 4 14:41:43 EDT 2022


https://github.com/python/cpython/commit/e61330b44f22b11a71f5bbcc17e309dd80e3e95f
commit: e61330b44f22b11a71f5bbcc17e309dd80e3e95f
branch: main
author: Irit Katriel <1055913+iritkatriel at users.noreply.github.com>
committer: iritkatriel <1055913+iritkatriel at users.noreply.github.com>
date: 2022-05-04T19:40:47+01:00
summary:

gh-92118: fix traceback of exceptions propagated from inside a contextlib.contextmanager (GH-92202)

files:
A Misc/NEWS.d/next/Library/2022-05-02-23-08-02.gh-issue-92118.9Mm9g4.rst
M Lib/contextlib.py
M Lib/test/test_contextlib.py

diff --git a/Lib/contextlib.py b/Lib/contextlib.py
index 4cff9c6a46117..625bb33b12d5f 100644
--- a/Lib/contextlib.py
+++ b/Lib/contextlib.py
@@ -161,6 +161,7 @@ def __exit__(self, typ, value, traceback):
             except RuntimeError as exc:
                 # Don't re-raise the passed in exception. (issue27122)
                 if exc is value:
+                    exc.__traceback__ = traceback
                     return False
                 # Avoid suppressing if a StopIteration exception
                 # was passed to throw() and later wrapped into a RuntimeError
@@ -172,6 +173,7 @@ def __exit__(self, typ, value, traceback):
                     isinstance(value, StopIteration)
                     and exc.__cause__ is value
                 ):
+                    exc.__traceback__ = traceback
                     return False
                 raise
             except BaseException as exc:
@@ -183,6 +185,7 @@ def __exit__(self, typ, value, traceback):
                 # and the __exit__() protocol.
                 if exc is not value:
                     raise
+                exc.__traceback__ = traceback
                 return False
             raise RuntimeError("generator didn't stop after throw()")
 
diff --git a/Lib/test/test_contextlib.py b/Lib/test/test_contextlib.py
index e238548be9e2b..bfe81173ddc0b 100644
--- a/Lib/test/test_contextlib.py
+++ b/Lib/test/test_contextlib.py
@@ -5,6 +5,7 @@
 import sys
 import tempfile
 import threading
+import traceback
 import unittest
 from contextlib import *  # Tests __all__
 from test import support
@@ -87,6 +88,32 @@ def woohoo():
                 raise ZeroDivisionError()
         self.assertEqual(state, [1, 42, 999])
 
+    def test_contextmanager_traceback(self):
+        @contextmanager
+        def f():
+            yield
+
+        try:
+            with f():
+                1/0
+        except ZeroDivisionError as e:
+            frames = traceback.extract_tb(e.__traceback__)
+
+        self.assertEqual(len(frames), 1)
+        self.assertEqual(frames[0].name, 'test_contextmanager_traceback')
+        self.assertEqual(frames[0].line, '1/0')
+
+        # Repeat with RuntimeError (which goes through a different code path)
+        try:
+            with f():
+                raise NotImplementedError(42)
+        except NotImplementedError as e:
+            frames = traceback.extract_tb(e.__traceback__)
+
+        self.assertEqual(len(frames), 1)
+        self.assertEqual(frames[0].name, 'test_contextmanager_traceback')
+        self.assertEqual(frames[0].line, 'raise NotImplementedError(42)')
+
     def test_contextmanager_no_reraise(self):
         @contextmanager
         def whee():
diff --git a/Misc/NEWS.d/next/Library/2022-05-02-23-08-02.gh-issue-92118.9Mm9g4.rst b/Misc/NEWS.d/next/Library/2022-05-02-23-08-02.gh-issue-92118.9Mm9g4.rst
new file mode 100644
index 0000000000000..b58ecdf40daf3
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2022-05-02-23-08-02.gh-issue-92118.9Mm9g4.rst
@@ -0,0 +1 @@
+Fix a 3.11 regression in :func:`~contextlib.contextmanager`, which caused it to propagate exceptions with incorrect tracebacks.



More information about the Python-checkins mailing list