Python Glossary Русский

all Python 3warningsfunction

warnings.filterwarnings()

filters

Adds a warning filter rule with conditions on message, category, module and line: fine-grained control over what to show and what to silence.

Syntax

warnings.filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False)

message is a regular expression matched against the START of the text, case-insensitively: 'old' silences "Old API" but not "very old", and a dot or a bracket in it is a metacharacter. module is also a regular expression for the start of the module name (case-sensitive). A new rule goes to the front of the list and beats earlier ones; append=True puts it at the end. The rule applies to the whole process — wrap the call in catch_warnings() for a temporary one.

Examples

import warnings
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter('always')
    warnings.filterwarnings('ignore', message='old')
    warnings.warn('Old API')
    warnings.warn('very old')
print([str(w.message) for w in caught])  # → ['very old']

See also

Open in the full glossarydocs.python.orgReport an inaccuracy