Skip to content

bpo-44297: Make sure that line number is set correctly for call to __exit__ when handling exception in body of a with statement. #26890

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

Merged
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
31 changes: 24 additions & 7 deletions Lib/test/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -2160,18 +2160,23 @@ def test_incorrect_constructor(self):

class PEP626Tests(unittest.TestCase):

def lineno_after_raise(self, f, line):
def lineno_after_raise(self, f, *expected):
try:
f()
except Exception as ex:
t = ex.__traceback__
while t.tb_next:
t = t.tb_next
else:
self.fail("No exception raised")
lines = []
t = t.tb_next # Skip this function
while t:
frame = t.tb_frame
if line is None:
self.assertEqual(frame.f_lineno, line)
else:
self.assertEqual(frame.f_lineno-frame.f_code.co_firstlineno, line)
lines.append(
None if frame.f_lineno is None else
frame.f_lineno-frame.f_code.co_firstlineno
)
t = t.tb_next
self.assertEqual(tuple(lines), expected)

def test_lineno_after_raise_simple(self):
def simple():
Expand Down Expand Up @@ -2250,5 +2255,17 @@ def f():
f.__code__ = f.__code__.replace(co_linetable=b'\x04\x80\xff\x80')
self.lineno_after_raise(f, None)

def test_lineno_after_raise_in_with_exit(self):
class ExitFails:
def __enter__(self):
return self
def __exit__(self, *args):
raise ValueError

def after_with():
with ExitFails():
1/0
self.lineno_after_raise(after_with, 1, 1)

if __name__ == '__main__':
unittest.main()
3 changes: 1 addition & 2 deletions Python/compile.c
Original file line number Diff line number Diff line change
Expand Up @@ -5053,6 +5053,7 @@ compiler_visit_keyword(struct compiler *c, keyword_ty k)

static int
compiler_with_except_finish(struct compiler *c, basicblock * cleanup) {
c->u->u_lineno = -1;
basicblock *exit;
exit = compiler_new_block(c);
if (exit == NULL)
Expand Down Expand Up @@ -5168,7 +5169,6 @@ compiler_async_with(struct compiler *c, stmt_ty s, int pos)

/* For exceptional outcome: */
compiler_use_next_block(c, final);
c->u->u_lineno = -1;

ADDOP_JUMP(c, SETUP_CLEANUP, cleanup);
ADDOP(c, PUSH_EXC_INFO);
Expand Down Expand Up @@ -5265,7 +5265,6 @@ compiler_with(struct compiler *c, stmt_ty s, int pos)

/* For exceptional outcome: */
compiler_use_next_block(c, final);
c->u->u_lineno = -1;

ADDOP_JUMP(c, SETUP_CLEANUP, cleanup);
ADDOP(c, PUSH_EXC_INFO);
Expand Down
Loading