Executing a python script (way to long to include here) I wrote leads to a warning message. I don’t know at which line in my code this gets raised. How can I get this information?
Furthermore, what does this mean exactly? In fact, I didn’t know I was using a masked array of some sort?
/usr/lib/pymodules/python2.7/numpy/ma/core.py:3785: UserWarning: Warning: converting a masked element to nan.
warnings.warn("Warning: converting a masked element to nan.")
Advertisement
Answer
You can use the warnings module to convert warnings to exceptions. The simplest method is called simplefilter. Here’s an example; the code that generates the warning is in func2b(), so there is a nontrival traceback.
import warnings
def func1():
print("func1")
def func2():
func2b()
print("func2")
def func2b():
warnings.warn("uh oh")
def func3():
print("func3")
if __name__ == "__main__":
# Comment the following line to see the default behavior.
warnings.simplefilter('error', UserWarning)
func1()
func2()
func3()
When the line containing the call to simplefilter is commented out, the output is
func1
warning_to_exception.py:13: UserWarning: uh oh
warnings.warn("uh oh")
func2
func3
With that line included, you get a traceback:
func1
Traceback (most recent call last):
File "warning_to_exception.py", line 23, in <module>
func2()
File "warning_to_exception.py", line 9, in func2
func2b()
File "warning_to_exception.py", line 13, in func2b
warnings.warn("uh oh")
UserWarning: uh oh