UserWarning: converting a masked element to nan

It's also possible to patch MaskedArray.__float__ so that it raises an exception, this way you would see stack trace, which would include your code. And patching could be done in your code, no need to mess with the .../ma/core.py.

Example for squeeze():

import numpy as np
from numpy import ma

def raise_me(*args, **kw):
    raise Exception('ping')

ma.MaskedArray.squeeze = raise_me

def test():
    x = np.array([(1, 1.), (2, 2.)], dtype=[('a',int), ('b', float)])
    m = x.view(ma.MaskedArray)
    m.squeeze()

def main():
    test()

main()

And output:

Traceback (most recent call last):
  File "t.py", line 19, in <module>
    main()
  File "t.py", line 17, in main
    test()
  File "t.py", line 13, in test
    m.squeeze()
  File "t.py", line 6, in raise_me
    raise Exception('ping')
Exception: ping

As you can see it shows you the line with m.squeeze().


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

Tags:

Python

Numpy