Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 4 commits into from
May 4, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
1 change: 1 addition & 0 deletions Lib/contextlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,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()")

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 @@ -5,6 +5,7 @@
import sys
import tempfile
import threading
import traceback
import unittest
from contextlib import * # Tests __all__
from test import support
Expand Down Expand Up @@ -87,6 +88,24 @@ def woohoo():
raise ZeroDivisionError()
self.assertEqual(state, [1, 42, 999])

def test_contextmanager_traceback(self):
@contextmanager
def f():
try:
yield
finally:
pass
iritkatriel marked this conversation as resolved.
Show resolved Hide resolved

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')

def test_contextmanager_no_reraise(self):
@contextmanager
def whee():
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix a 3.11 regression in :func:`~contextlib.contextmanager`, which caused it to propagate exceptions with incorrect tracebacks.