Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 888
Covich Avatar asked Mar 26 '14 12:03

Covich


2 Answers

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') 
like image 158
Selcuk Avatar answered Oct 01 '22 17:10

Selcuk


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.

like image 20
Martijn Pieters Avatar answered Oct 01 '22 17:10

Martijn Pieters