I want to change the floating point error handling of numpy inside of a single function.
Typical example:
import numpy as np
def f():
np.seterr(all='raise')
# Do some other stuff
print(np.seterr())
# {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
f()
print(np.seterr())
# {'divide': 'raise', 'over': 'raise', 'under': 'raise', 'invalid': 'raise'}
I would like the call to fto not change the output of np.seterr(), I have no idea how to do this.
Thanks for any help !
Advertisement
Answer
Use the numpy.errstate context manager to change floating-point error handling temporarily:
def f():
with numpy.errstate(all='raise'):
...
Be aware that while this is a temporary change, it is still global across threads and coroutines. As of the time of this writing, NumPy doesn’t offer an option for thread-local or contextvars-based error settings.
As of NumPy 1.17, it is also possible to use numpy.errstate as a function decorator, with the same effect as wrapping the whole body in a with numpy.errstate(...): block:
@numpy.errstate(all='raise')
def f():
...