python / python/cpython

Default `warnings.showwarning` always used when interpreter session is cleaning up

オープン
#149,211 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

stdlib type-bug
主要言語
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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

issue の再現スクリプトから始め、通常の警告パスとインタープリターのクリーンアップ動作を比較します。リンクされている PR gh-150944 を確認して提案された範囲を把握します。完了とは、クリーンアップ中にカスタム warnings.showwarning ハンドラーが一貫して尊重され、再現ケースのカバレッジがあることです。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
backend
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。