pythonpython-3.xpython-2.7loopswarnings

Why only one warning in a loop?


I want a warning raise for each problem detected in a loop, but the warning is only raised once, the first time. For example :

import warnings

for i in range(10):
   print i
   warnings.warn('this is a warning message')

I expect :

0
UserWarning: this is a warning message
1
UserWarning: this is a warning message
2
UserWarning: this is a warning message
3
UserWarning: this is a warning message
4

but the result is :

0
__main__:4: UserWarning: this is a warning message
1
2
3
4

Why do I have only one warning? How can I get a warning for each iteration?


Solution

  • It is by design. See the docs at https://docs.python.org/3/library/warnings.html:

    Repetitions of a particular warning for the same source location are typically suppressed.

    You can override this behavior by adding a filter with the keyword "always", as in:

    import warnings
    
    warnings.simplefilter('always', UserWarning)
    for i in range(10):
        print(i)
        warnings.warn('this is a warning message')