numpy/numpy — pull request #270 by jpaalasm (2012-05-06 09:50:06+00:00)
Title: Make errstate a decorator

It would be very useful to be able to define floating point error handling per function. For example, you may know that a particular function triggers a harmless underflow (e.g. in computing probabilities), but you would like to keep error handling strict for other functions.

This patch implements a decorator interface to errstate.

Example:

import numpy

@numpy.errstate(invalid="warn")
def test_func1(a):
numpy.sqrt(-1)

@numpy.errstate(invalid="raise")
def test_func2():
numpy.sqrt(-1)

def main():
test_func1(1)
test_func2()

main()

Example output:

test_new_errstate.py:100: RuntimeWarning: invalid value encountered in sqrt
numpy.sqrt(-1)
Traceback (most recent call last):
File "test_new_errstate.py", line 110, in
main()
File "test_new_errstate.py", line 108, in main
test_func2()
File "test_new_errstate.py", line 89, in func_with_error_handling
return func(*args, **kwargs)
File "test_new_errstate.py", line 104, in test_func2
numpy.sqrt(-1)
FloatingPointError: invalid value encountered in sqrt