I want to change the floating point error handling of numpy inside of a single function.
Typical example:
JavaScript
x
13
13
1
import numpy as np
2
3
def f():
4
np.seterr(all='raise')
5
# Do some other stuff
6
7
print(np.seterr())
8
# {'divide': 'warn', 'over': 'warn', 'under': 'ignore', 'invalid': 'warn'}
9
10
f()
11
print(np.seterr())
12
# {'divide': 'raise', 'over': 'raise', 'under': 'raise', 'invalid': 'raise'}
13
I would like the call to f
to 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:
JavaScript
1
4
1
def f():
2
with numpy.errstate(all='raise'):
3
4
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:
JavaScript
1
4
1
@numpy.errstate(all='raise')
2
def f():
3
4