Python filter warnings to hide repetitions, even if the message changes

13 views Asked by At

The documentation for the warnings module states that the default action is:

print the first occurrence of matching warnings for each location (module + line number) where the warning is issued.

but it stays evasive about which part of the message defines a "match". When I run the following code, it repeats each warning that has a different message, even if the location is identical.

import warnings

for i in range(3):
    warnings.warn("Warning 1: fixed message")
    warnings.warn("Warning 2: variable message #%d" % i)
./test_repeated_warnings.py:8: UserWarning: Warning 1: fixed message
  warnings.warn("Warning 1: fixed message")
./test_repeated_warnings.py:9: UserWarning: Warning 2: variable message #0
  warnings.warn("Warning 2: variable message #%d" % i)
./test_repeated_warnings.py:9: UserWarning: Warning 2: variable message #1
  warnings.warn("Warning 2: variable message #%d" % i)
./test_repeated_warnings.py:9: UserWarning: Warning 2: variable message #2
  warnings.warn("Warning 2: variable message #%d" % i)

How do you hide repetitions of a warning for a specific location, whatever the message?

I tried to explicitly set a filter, but it did not have any effect:

warnings.filterwarnings('once', '^Warning 2.*', UserWarning)
0

There are 0 answers