Pythonプログラムにおける警告の制御方法【warningsモジュール徹底解説】
Pythonにおいて「警告」と「エラー」はまったく異なるものです。エラーが発生するとPythonプログラムは即座に終了しますが、警告は致命的ではありません。メッセージは表示されるものの、プログラムはそのまま実行を続けます。警告は、厳密には例外ではない特定の状態についてユーザーに注意を促すために発せられます。典型的な例としては、キーワード・関数・クラスなど、あるプログラミング要素の非推奨(deprecated)な使い方が検出された場合に警告が表示されます。
警告メッセージは、Python標準ライブラリの「warnings」モジュールで定義されている warn() 関数によって表示されます。Warning クラスは、組み込みクラス階層における Exception のサブクラスです。多数の組み込み警告サブクラスが用意されており、ユーザーが独自のサブクラスを定義することも可能です。
主な組み込み警告カテゴリ
| Warning | すべての警告カテゴリクラスの基底クラスです。 |
| UserWarning | warn() のデフォルトのカテゴリです。 |
| DeprecationWarning | 開発者向けに発せられる、非推奨機能に関する警告です。 |
| SyntaxWarning | 疑わしい構文に関する警告です。 |
| RuntimeWarning | 疑わしいランタイム動作に関する警告です。 |
| FutureWarning | エンドユーザー向けに発せられる、非推奨機能に関する警告です。 |
| PendingDeprecationWarning | 将来非推奨となる予定の機能に関する警告です。 |
| ImportWarning | モジュールのインポート処理中に発生する警告です。 |
| UnicodeWarning | Unicodeに関連する警告です。 |
| BytesWarning | bytesおよびbytearrayに関連する警告です。 |
| ResourceWarning | リソースの使用に関連する警告です。 |
警告の使用例
次のコードでは、非推奨となったメソッドと、将来のバージョンで非推奨になる予定のメソッドを持つクラスを定義しています。
# warningexample.py
import warnings
class WarnExample:
def __init__(self):
self.text = "Warning"
def method1(self):
warnings.warn(
"method1 is deprecated, use new_method instead",
DeprecationWarning
)
print ('method1', len(self.text))
def method2(self):
warnings.warn(
"method2 will be deprecated in version 2, use new_method instead",
PendingDeprecationWarning
)
print ('method2', len(self.text))
def new_method(self):
print ('new method', len(self.text))
if __name__=='__main__':
e = WarnExample()
e.method1()
e.method2()
e.new_method()このスクリプトをコマンドプロンプトから以下のように実行しても、端末には警告メッセージは表示されません。
E:\python37>python warningexample.py
警告を表示するには、次のように -Wd スイッチを使用します。
E:\python37>python -Wd warningexample.py warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead DeprecationWarning method1 7 warningexample.py:19: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead PendingDeprecationWarning method2 7 new method 7
同様に、以下のような対話型セッションでも警告メッセージは表示されません。
E:\python37>python >>> from warningexample import WarnExample >>> e = WarnExample() >>> e.method1() method1 7 >>> e.method2() method2 7 >>> e.new_method() new method 7
警告を確認したい場合は、-Wd オプションを付けてPythonセッションを開始します。
E:\python37>python -Wd >>> from warningexample import WarnExample >>> e=WarnExample() >>> e.method1() E:\python37\warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead DeprecationWarning method1 7 >>> e.method2() E:\python37\warningexample.py:17: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead PendingDeprecationWarning method2 7 >>> e.new_method() new method 7
警告フィルタ(Warnings Filters)
警告フィルタを使用すると、警告を無視するか、表示するか、あるいは例外として扱うか(例外を発生させるか)を制御できます。
| アクション | 意味 |
|---|---|
| error | 警告を例外に変換します。 |
| ignore | 警告を破棄します。 |
| always | 常に警告を出力します。 |
| default | 各発生場所ごとに、最初に生成されたときのみ警告を出力します。 |
| module | 各モジュールごとに、最初に生成されたときのみ警告を出力します。 |
| once | 最初に生成されたときのみ警告を出力します。 |
次の対話型セッションでは、simplefilter() 関数を使ってフィルタを「default」に設定しています。
E:\python37>python
>>> import warnings
>>> warnings.simplefilter('default')
>>> from warningexample import WarnExample
>>> e=WarnExample()
>>> e.method1()
E:\python37\warningexample.py:10: DeprecationWarning: method1 is deprecated, use new_method instead
DeprecationWarning
method1 7
>>> e.method2()
E:\python37\warningexample.py:17: PendingDeprecationWarning: method2 will be deprecated in version 2, use new_method instead
PendingDeprecationWarning
method2 7
>>> e.new_method()
new method 7また、警告を一時的に抑制したい場合は、simplefilter を「ignore」に設定します。catch_warnings() コンテキストマネージャと組み合わせると、そのブロック内でのみ設定が有効になり、ブロックを抜けると元の設定に自動的に戻るため便利です。
import warnings
def function():
warnings.warn("deprecated", DeprecationWarning)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
function()
-
【初心者向け】Pythonのissuperset()メソッドの使い方をわかりやすく解説
はじめにこの記事では、Pythonのissuperset()メソッドについて、基本的な仕組みから実際のコード例まで詳しく解説します。issuperset()は、セット(集合)に対して使用できるメソッドで、引数として渡されたセットのすべての要素が、呼び出し元のセットに含まれているかどうかを判定します。呼び出し元のセットBが、引数のセットAのすべての要素を含んでいる場合 → True を返すセットAの要素がすべてBに含まれていない場合 → False を返すつまり、「BがAの上位集合(スーパーセット)であるかどうか」を判定するためのメソッドです。基本構文B.issuperset(A)この式は、Bが
-
PythonでFloatingPointError例外をキャッチする方法【fpectlによる浮動小数点例外の捕捉】
FloatingPointErrorとはFloatingPointError は、浮動小数点例外制御(fpectl)が有効になっている環境で、浮動小数点演算がエラーとなった際に発生する例外です。この機能を利用するには、Pythonインタープリタが --with-fpectl フラグを付けてコンパイルされている必要があります。通常のビルドでは無効化されているため、利用前に環境を確認しましょう。例外を捕捉するサンプルコード次のコードでは、try-except 構文を使って FloatingPointError を捕捉し、発生した例外の種類(型)を出力しています。import math import