Suppressing, Ignoring Warnings in Python: Reference and Examples

Suppressing, Ignoring Warnings in Python: Reference and Examples

Last updated:
Table of Contents

Examples use Python 3.6+ unless otherwise specified

Suppress warnings

In order to disable all warnings in the current script/notebook just use filterwarnings:

# at the top of the file, before other imports
import warnings

warnings.filterwarnings('ignore')

# no warnings will be printed from now on

Suppress warnings matching text

To disable warnings whose message match some given text:

import warnings

warnings.filterwarnings('ignore', message='foo bar')

# no warnings whose text match 'foo bar' will be printed from now on

Suppress warnings of type

You can also suppress warnings of a given type only, using category= parameter:

import warnings

warnings.simplefilter(action='ignore', category=FutureWarning)
# no warnings of type FutureWarning will be printed from now on

Suppress warnings in block

To disable warnings from being raised in a given block or in a specific function only, use warnings.catch_warnings() together with a simplefilter in a with block:

import warnings

with warnings.catch_warnings():
    # this will suppress all warnings in this block
    warnings.simplefilter("ignore")

    function_that_raises_warnings()

Re-enable warnings

To enable warnings again, use filterwarnings('default')

import warnings

# if warnings have been suppressed, they are now re-enabled
warnings.filterwarnings('default')

Filterwarnings example

See above: Suppress warnings