Python Glossary Русский

all Python 3warningsfunction

warnings.simplefilter()

filters

Adds a filter rule by warning category: 'error', 'ignore', 'always', 'default', 'module' or 'once' — with no conditions on the message.

Syntax

warnings.simplefilter(action, category=Warning, lineno=0, append=False)

Filters are what decide whether the user sees a warning: by default Python hides DeprecationWarning outside __main__, PendingDeprecationWarning, ImportWarning and ResourceWarning, and shows the rest once per code location. simplefilter('error') turns warnings into exceptions — the way tests catch deprecated calls; 'ignore' silences them. From outside, without editing code, the -W error::DeprecationWarning option or the PYTHONWARNINGS variable does the same; a rule added in code goes to the front of the list and overrides them. The change is global — make temporary ones inside catch_warnings().

Examples

import warnings
warnings.simplefilter('error', DeprecationWarning)
try:
    warnings.warn('функция устарела', DeprecationWarning)
except DeprecationWarning as e:
    print('исключение:', e)  # → исключение: функция устарела
import warnings
with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter('once')
    for _ in range(3):
        warnings.warn('медленный путь')
print(len(caught))  # → 1

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy