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