Rémi Baudoux
Rémi Baudoux

Reputation: 559

Python, disable warnings filter

How to disable the filtering of the warnings?

I would like to output several times the same warning, but a filter in the library avoids to output more than once the same warning.

import warnings

for i in range(2):
    warnings.warn("warning message")

output:

C:\Users\me\my_script.py:4: UserWarning: warning message
  warnings.warn("warning message")

The documentation is here: https://docs.python.org/2/library/warnings.html

Apparently I have to set "always" in the tuple at the entry of the filter, I don't know how to do so, and where to access this tuple.

Upvotes: 1

Views: 9447

Answers (2)

num3ri
num3ri

Reputation: 776

With python 2.7.15rc1, to disable all warnings, I used these two lines of code:

import warnings
warnings.simplefilter("ignore")

I hope it is useful

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124758

You can update warning filters with the warnings.simplefilter() and warnings.filterwarnings() functions; from the module intro:

The determination whether to issue a warning message is controlled by the warning filter, which is a sequence of matching rules and actions. Rules can be added to the filter by calling filterwarnings() and reset to its default state by calling resetwarnings().

To make all warnings repeat beyond the first issue, use

warnings.simplefilter('always')

You can expand on this by adding more details to filter on. For example, your warnings.warn() calls do not specify a category, so the default then is to use warnings.UserWarning; you could add that to the filter:

warnings.simplefilter('always', warnings.UserWarning)

etc. You can use keyword arguments too if you only want to specify some of the filter arguments, such as append=True.

Upvotes: 2

Related Questions