Skip to content
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
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,4 @@ Authors
* Oldřich Jedlička - https://github.com/oldium
* Colin Watson - https://github.com/cjwatson
* Jacob Tomlinson - https://github.com/jacobtomlinson
* fly1d - https://github.com/fly1d
5 changes: 5 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
Changelog
=========

Unreleased
~~~~~~~~~~

* Fixed traceback reconstruction for parsed frames without a function name, such as locations in formatted ``SyntaxError`` output.

3.2.2 (2025-11-12)
~~~~~~~~~~~~~~~~~~

Expand Down
2 changes: 1 addition & 1 deletion src/tblib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def as_traceback(self):
co_firstlineno=current.tb_lineno,
co_argcount=0,
co_filename=f_code.co_filename,
co_name=f_code.co_name,
co_name=f_code.co_name if f_code.co_name is not None else stub.co_name,
co_freevars=(),
co_cellvars=(),
)
Expand Down
36 changes: 36 additions & 0 deletions tests/test_tblib.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,42 @@ def func(my_arg='2'):
assert Traceback.from_dict(value).tb_next.tb_frame.f_locals == {'my_variable': 1}


def test_parse_syntax_error_traceback():
filename = '<tblib-syntax-error>'
source = 'first = 1\nsecond = 2\nif True print("invalid")\n'

try:
compile(source, filename, 'exec')
except SyntaxError as exc:
syntax_location = (exc.filename, exc.lineno)
outer_frames = [(frame.filename, frame.lineno, frame.name) for frame in traceback.extract_tb(exc.__traceback__)]
formatted = traceback.format_exc()
else:
raise AssertionError('The invalid source should raise SyntaxError')

assert syntax_location == (filename, 3)
assert outer_frames

parsed = Traceback.from_string(formatted)
parsed_frames = []
current = parsed
while current is not None:
code = current.tb_frame.f_code
parsed_frames.append((code.co_filename, current.tb_lineno, code.co_name))
current = current.tb_next

# The parser already includes the bare compiler location without a function name.
assert parsed_frames == [*outer_frames, (*syntax_location, None)]
serialized = parsed.as_dict()

reconstructed = traceback.extract_tb(parsed.as_traceback())
reconstructed_frames = [(frame.filename, frame.lineno, frame.name) for frame in reconstructed]

# Keep the exec stub's native name only where the input did not supply one.
assert reconstructed_frames == [*outer_frames, (*syntax_location, '<module>')]
assert parsed.as_dict() == serialized


def test_parse_traceback():
tb1 = Traceback.from_string(
"""
Expand Down