Skip to content

Commit 5df35fa

Browse files
bpo-45249: Fix caret location when end_offset is set to 0 (GH-28855)
(cherry picked from commit fe0d9e2) Co-authored-by: Pablo Galindo Salgado <[email protected]>
1 parent 855d624 commit 5df35fa

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

Lib/test/test_traceback.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,9 @@ def syntax_error_with_caret_non_ascii(self):
5151
def syntax_error_bad_indentation2(self):
5252
compile(" print(2)", "?", "exec")
5353

54+
def tokenizer_error_with_caret_range(self):
55+
compile("blech ( ", "?", "exec")
56+
5457
def test_caret(self):
5558
err = self.get_exception_format(self.syntax_error_with_caret,
5659
SyntaxError)
@@ -81,6 +84,13 @@ def test_caret(self):
8184
self.assertEqual(err[1].find("y"), err[2].find("^")) # in the right place
8285
self.assertEqual(err[2].count("^"), len("y for y in range(30)"))
8386

87+
err = self.get_exception_format(self.tokenizer_error_with_caret_range,
88+
SyntaxError)
89+
self.assertIn("^", err[2]) # third line has caret
90+
self.assertEqual(err[2].count('\n'), 1) # and no additional newline
91+
self.assertEqual(err[1].find("("), err[2].find("^")) # in the right place
92+
self.assertEqual(err[2].count("^"), 1)
93+
8494
def test_nocaret(self):
8595
exc = SyntaxError("error", ("x.py", 23, None, "bad syntax"))
8696
err = traceback.format_exception_only(SyntaxError, exc)

Lib/traceback.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -633,7 +633,7 @@ def _format_syntax_error(self, stype):
633633

634634
if self.offset is not None:
635635
offset = self.offset
636-
end_offset = self.end_offset if self.end_offset is not None else offset
636+
end_offset = self.end_offset if self.end_offset not in {None, 0} else offset
637637
if offset == end_offset or end_offset == -1:
638638
end_offset = offset + 1
639639

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix the behaviour of :func:`traceback.print_exc` when displaying the caret
2+
when the ``end_offset`` in the exception is set to 0. Patch by Pablo Galindo

0 commit comments

Comments
 (0)