Skip to content

Commit fe0d9e2

Browse files
authored
bpo-45249: Fix caret location when end_offset is set to 0 (GH-28855)
1 parent 5afa0a4 commit fe0d9e2

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
@@ -55,6 +55,9 @@ def syntax_error_with_caret_non_ascii(self):
5555
def syntax_error_bad_indentation2(self):
5656
compile(" print(2)", "?", "exec")
5757

58+
def tokenizer_error_with_caret_range(self):
59+
compile("blech ( ", "?", "exec")
60+
5861
def test_caret(self):
5962
err = self.get_exception_format(self.syntax_error_with_caret,
6063
SyntaxError)
@@ -85,6 +88,13 @@ def test_caret(self):
8588
self.assertEqual(err[1].find("y"), err[2].find("^")) # in the right place
8689
self.assertEqual(err[2].count("^"), len("y for y in range(30)"))
8790

91+
err = self.get_exception_format(self.tokenizer_error_with_caret_range,
92+
SyntaxError)
93+
self.assertIn("^", err[2]) # third line has caret
94+
self.assertEqual(err[2].count('\n'), 1) # and no additional newline
95+
self.assertEqual(err[1].find("("), err[2].find("^")) # in the right place
96+
self.assertEqual(err[2].count("^"), 1)
97+
8898
def test_nocaret(self):
8999
exc = SyntaxError("error", ("x.py", 23, None, "bad syntax"))
90100
err = traceback.format_exception_only(SyntaxError, exc)

Lib/traceback.py

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

782782
if self.offset is not None:
783783
offset = self.offset
784-
end_offset = self.end_offset if self.end_offset is not None else offset
784+
end_offset = self.end_offset if self.end_offset not in {None, 0} else offset
785785
if offset == end_offset or end_offset == -1:
786786
end_offset = offset + 1
787787

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)