Skip to content

Commit 7f6e80a

Browse files
[3.13] gh-128894: Fix TracebackException._format_syntax_error on custom SyntaxError metadata (GH-128946) (#129178)
1 parent a379749 commit 7f6e80a

File tree

3 files changed

+36
-3
lines changed

3 files changed

+36
-3
lines changed

Lib/test/test_traceback.py

+24
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,30 @@ def f():
376376
' ValueError: 0\n',
377377
])
378378

379+
def test_format_exception_group_syntax_error_with_custom_values(self):
380+
# See https://github.com/python/cpython/issues/128894
381+
for exc in [
382+
SyntaxError('error', 'abcd'),
383+
SyntaxError('error', [None] * 4),
384+
SyntaxError('error', (1, 2, 3, 4)),
385+
SyntaxError('error', (1, 2, 3, 4)),
386+
SyntaxError('error', (1, 'a', 'b', 2)),
387+
# with end_lineno and end_offset:
388+
SyntaxError('error', 'abcdef'),
389+
SyntaxError('error', [None] * 6),
390+
SyntaxError('error', (1, 2, 3, 4, 5, 6)),
391+
SyntaxError('error', (1, 'a', 'b', 2, 'c', 'd')),
392+
]:
393+
with self.subTest(exc=exc):
394+
err = traceback.format_exception_only(exc, show_group=True)
395+
# Should not raise an exception:
396+
if exc.lineno is not None:
397+
self.assertEqual(len(err), 2)
398+
self.assertTrue(err[0].startswith(' File'))
399+
else:
400+
self.assertEqual(len(err), 1)
401+
self.assertEqual(err[-1], 'SyntaxError: error\n')
402+
379403
@requires_subprocess()
380404
@force_not_colorized
381405
def test_encoded_file(self):

Lib/traceback.py

+10-3
Original file line numberDiff line numberDiff line change
@@ -1283,7 +1283,7 @@ def _format_syntax_error(self, stype, **kwargs):
12831283
filename_suffix = ' ({})'.format(self.filename)
12841284

12851285
text = self.text
1286-
if text is not None:
1286+
if isinstance(text, str):
12871287
# text = " foo\n"
12881288
# rtext = " foo"
12891289
# ltext = "foo"
@@ -1292,10 +1292,17 @@ def _format_syntax_error(self, stype, **kwargs):
12921292
spaces = len(rtext) - len(ltext)
12931293
if self.offset is None:
12941294
yield ' {}\n'.format(ltext)
1295-
else:
1295+
elif isinstance(self.offset, int):
12961296
offset = self.offset
12971297
if self.lineno == self.end_lineno:
1298-
end_offset = self.end_offset if self.end_offset not in {None, 0} else offset
1298+
end_offset = (
1299+
self.end_offset
1300+
if (
1301+
isinstance(self.end_offset, int)
1302+
and self.end_offset != 0
1303+
)
1304+
else offset
1305+
)
12991306
else:
13001307
end_offset = len(rtext) + 1
13011308

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix ``traceback.TracebackException._format_syntax_error`` not to fail on
2+
exceptions with custom metadata.

0 commit comments

Comments
 (0)