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?
It is by design. See the docs at http://docs.python.org/2/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') 
                        From the warnings module documentation:
Repetitions of a particular warning for the same source location are typically suppressed.
This is by design.
I'd not use the warnings module if you want your message to be printed always; you could reset the filters (using warnings.resetwarnings(), but that's very much not recommended as you'd discard any user-configured filters too. You could add an explicit filter that always allows the message with the warnings.simplefilter() function:
warnings.simplefilter('always', UserWarning)   but I'd just write to sys.stderr directly instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With