Question

While numpy.seterr allows customization of what happens when a floating point exception happens, for example calling a specific callback, it does not seem to provide information about the specific values that triggered the exception.

Reusing one of the examples from the docs:

def err_handler(type, flag):
    print "Floating point error (%s), with flag %s" % (type, flag)
saved_handler = np.seterrcall(err_handler)
save_err = np.seterr(all='call')
np.array([1, 2, 3]) / 0.0

Floating point error (divide by zero), with flag 1
array([ Inf,  Inf,  Inf])

it would be nice if the err_handler callback could print something like:

Floating point error (divide by zero), with flag 1.  
Attempted operation: array([1, 2, 3]) / 0.0.

Any help in achieving this would be appreciated!

Was it helpful?

Solution

How about use traceback to print the stack?

import numpy as np

def err_handler(type, flag):
    import traceback
    traceback.print_stack(limit=2)
    print "Floating point error (%s), with flag %s" % (type, flag)

saved_handler = np.seterrcall(err_handler)
save_err = np.seterr(all='call')
a = np.array([1, 2, 3]) 
b = 0.0
a / b
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top