Default `warnings.showwarning` always used when interpreter session is cleaning up
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Bug report
Bug description:
Hey!
I'm not sure this is a bug, exactly, or just behaviour that is not documented well (or at all, despite me looking I couldn't really find anything on it), but I recently ran into it and was scratching my head for a good hour.
The "issue" if it even is one, is that the default warnings.showwarning handler is always called when the main scope for the interpreter is getting cleaned up, even if there is a custom showwarning hook.
I noticed this by having some resource leak messages in the __del__ calls for some objects, and noticed that they only trigger the proper handler if they are triggered in any scope under the main scope, but if done so in the main scope they always use the default handler.
The following code reproduces the behaviour:
import warnings
def _warning_handler(message, category, filename, lineno, output_file, line):
warn = warnings.formatwarning(message, category, filename, lineno, line)
print(f'😺: {warn}', file = output_file)
warnings.showwarning = _warning_handler
def meow():
print(f'Warning handler is: {warnings.showwarning.__code__.co_filename}')
warnings.warn('meow')
class Cat:
def __del__(self):
print(f'Warning handler is: {warnings.showwarning.__code__.co_filename}')
warnings.warn('nya')
meow()
cat = Cat()
The output of this code is:
Warning handler is: /tmp/mvp.py
😺: /tmp/mvp.py:11: UserWarning: meow
warnings.warn('meow')
Warning handler is: /tmp/mvp.py
/tmp/mvp.py:16: UserWarning: nya
CPython versions tested on:
3.14
Operating systems tested on:
Linux
Linked PRs
- gh-150944
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 issue 中的复现脚本开始,将其正常警告路径与解释器清理行为进行比较。查看链接的 PR gh-150944,了解提议的范围;完成的标准是自定义的 warnings.showwarning 处理程序在清理过程中始终得到遵循,并为复现脚本提供覆盖。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- backend
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 25/100