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-128894: Fix TracebackException._format_syntax_error on custom SyntaxError metadata #128946

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
24 changes: 24 additions & 0 deletions Lib/test/test_traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,30 @@ def f():
' ValueError: 0\n',
])

def test_format_exception_group_syntax_error_with_custom_values(self):
# See https://github.com/python/cpython/issues/128894
for exc in [
SyntaxError('error', 'abcd'),
SyntaxError('error', [None] * 4),
SyntaxError('error', (1, 2, 3, 4)),
SyntaxError('error', (1, 2, 3, 4)),
SyntaxError('error', (1, 'a', 'b', 2)),
# with end_lineno and end_offset:
SyntaxError('error', 'abcdef'),
SyntaxError('error', [None] * 6),
SyntaxError('error', (1, 2, 3, 4, 5, 6)),
SyntaxError('error', (1, 'a', 'b', 2, 'c', 'd')),
]:
with self.subTest(exc=exc):
err = traceback.format_exception_only(exc, show_group=True)
# Should not raise an exception:
if exc.lineno is not None:
self.assertEqual(len(err), 2)
self.assertTrue(err[0].startswith(' File'))
else:
self.assertEqual(len(err), 1)
self.assertEqual(err[-1], 'SyntaxError: error\n')

@requires_subprocess()
@force_not_colorized
def test_encoded_file(self):
Expand Down
13 changes: 10 additions & 3 deletions Lib/traceback.py
Original file line number Diff line number Diff line change
Expand Up @@ -1283,7 +1283,7 @@ def _format_syntax_error(self, stype, **kwargs):
filename_suffix = ' ({})'.format(self.filename)

text = self.text
if text is not None:
if isinstance(text, str):
# text = " foo\n"
# rtext = " foo"
# ltext = "foo"
Expand All @@ -1292,10 +1292,17 @@ def _format_syntax_error(self, stype, **kwargs):
spaces = len(rtext) - len(ltext)
if self.offset is None:
yield ' {}\n'.format(ltext)
else:
elif isinstance(self.offset, int):
offset = self.offset
if self.lineno == self.end_lineno:
end_offset = self.end_offset if self.end_offset not in {None, 0} else offset
end_offset = (
self.end_offset
if (
isinstance(self.end_offset, int)
and self.end_offset != 0
)
else offset
)
else:
end_offset = len(rtext) + 1

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