Traceback leaks global code when `exec`:ed code raises
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Bug report
Bug description:
Details
The traceback module's various functions for inspecting an exception leaks surrounding code when used to inspect an exception originating from an exec or eval call. I discovered this using traceback.format_exception but it applies to traceback.print_exc and the other ones that call or are called by those as well.
Specifically when compiled for "exec" mode using compile, and the exec:ed code inherits the context from which exec was called.
In this example, the comment on the first line is included in the printed traceback.
# Hi, I'm in the error message
import traceback
try:
exec(compile("tuple()[0]", "s", "exec"))
except:
traceback.print_exc()
This prints:
Traceback (most recent call last):
File "<filename>", line 4, in <module>
exec(compile("tuple()[0]", "s", "exec"))
File "s", line 1, in <module>
# Hi, I'm in the error message
IndexError: tuple index out of range
It seems that whatever line number the error is on in the exec:ed code is applied to the calling file instead of the exec:ed code.
Changing line 4 in the example above to exec("tuple()[0]") avoids the issue, and no info regarding the line is printed by traceback. This behavior is in line with what python outputs when the exception is not caught:
# Hi, I'm not in the error message
exec(compile("tuple()[0]", "s", "exec"))
results in:
Traceback (most recent call last):
File "<filename>", line 2, in <module>
exec(compile("tuple()[0]", "s", "exec"))
File "s", line 1, in <module>
IndexError: tuple index out of range
Summary
Example code
# Hi, I'm in the error message
import traceback
try:
exec(compile("tuple()[0]", "s", "exec"))
except:
traceback.print_exc()
Expected behaviour
Should print the following:
Traceback (most recent call last):
File "<filename>", line 4, in <module>
exec(compile("tuple()[0]", "s", "exec"))
File "s", line 1, in <module>
IndexError: tuple index out of range
Actual behaviour
Prints this:
Traceback (most recent call last):
File "<filename>", line 4, in <module>
exec(compile("tuple()[0]", "s", "exec"))
File "s", line 1, in <module>
# Hi, I'm in the error message
IndexError: tuple index out of range
CPython versions tested on:
3.8, 3.10, 3.11, 3.12
Operating systems tested on:
Linux, Windows
Linked PRs
- gh-122126
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
首先使用 traceback.format_exception 和 traceback.print_exc 重现示例,比较编译后的 exec 代码与直接 exec,以及未捕获的异常。跟踪 traceback 渲染如何为 exec 帧使用文件名和行号;当预期输出省略调用者的源代码行时即表示完成,包括所描述的其他 traceback 函数。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- backend
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 25/100