diff options
author | Charles Harris <charlesr.harris@gmail.com> | 2013-07-11 16:49:04 -0600 |
---|---|---|
committer | Charles Harris <charlesr.harris@gmail.com> | 2013-07-11 16:49:04 -0600 |
commit | 2f1174dee44e901b7d028beb86f4a8ea324bd74f (patch) | |
tree | 8f09dc2bd35e2631f5821fe2e998f6ea46e254b8 /numpy/core | |
parent | 49a587cd786242b05fcfd22d5cda961d733b68d4 (diff) | |
download | numpy-2f1174dee44e901b7d028beb86f4a8ea324bd74f.tar.gz |
MAINT: Use np.errstate context manager.
Now that Python < 2.6 is no longer supported we can use the errstate
context manager in places where constructs like
```
old = seterr(invalid='ignore')
try:
blah
finally:
seterr(**old)
```
were used.
Diffstat (limited to 'numpy/core')
-rw-r--r-- | numpy/core/arrayprint.py | 12 | ||||
-rw-r--r-- | numpy/core/machar.py | 7 | ||||
-rw-r--r-- | numpy/core/numeric.py | 11 | ||||
-rw-r--r-- | numpy/core/tests/test_half.py | 11 | ||||
-rw-r--r-- | numpy/core/tests/test_machar.py | 7 | ||||
-rw-r--r-- | numpy/core/tests/test_numeric.py | 16 | ||||
-rw-r--r-- | numpy/core/tests/test_regression.py | 20 | ||||
-rw-r--r-- | numpy/core/tests/test_scalarmath.py | 5 | ||||
-rw-r--r-- | numpy/core/tests/test_umath.py | 83 | ||||
-rw-r--r-- | numpy/core/tests/test_umath_complex.py | 68 |
10 files changed, 65 insertions, 175 deletions
diff --git a/numpy/core/arrayprint.py b/numpy/core/arrayprint.py index a0f2cfa63..ad6a5d074 100644 --- a/numpy/core/arrayprint.py +++ b/numpy/core/arrayprint.py @@ -546,8 +546,8 @@ class FloatFormat(object): def fillFormat(self, data): from . import numeric as _nc - errstate = _nc.seterr(all='ignore') - try: + + with _nc.errstate(all='ignore'): special = isnan(data) | isinf(data) valid = not_equal(data, 0) & ~special non_zero = absolute(data.compress(valid)) @@ -562,8 +562,6 @@ class FloatFormat(object): if not self.suppress_small and (min_val < 0.0001 or max_val/min_val > 1000.): self.exp_format = True - finally: - _nc.seterr(**errstate) if self.exp_format: self.large_exponent = 0 < min_val < 1e-99 or max_val >= 1e100 @@ -599,8 +597,8 @@ class FloatFormat(object): def __call__(self, x, strip_zeros=True): from . import numeric as _nc - err = _nc.seterr(invalid='ignore') - try: + + with _nc.errstate(invalid='ignore'): if isnan(x): if self.sign: return self.special_fmt % ('+' + _nan_str,) @@ -614,8 +612,6 @@ class FloatFormat(object): return self.special_fmt % (_inf_str,) else: return self.special_fmt % ('-' + _inf_str,) - finally: - _nc.seterr(**err) s = self.format % x if self.large_exponent: diff --git a/numpy/core/machar.py b/numpy/core/machar.py index 85eb6b625..9eb4430a6 100644 --- a/numpy/core/machar.py +++ b/numpy/core/machar.py @@ -10,7 +10,7 @@ from __future__ import division, absolute_import, print_function __all__ = ['MachAr'] from numpy.core.fromnumeric import any -from numpy.core.numeric import seterr +from numpy.core.numeric import errstate # Need to speed this up...especially for longfloat @@ -107,11 +107,8 @@ class MachAr(object): """ # We ignore all errors here because we are purposely triggering # underflow to detect the properties of the runninng arch. - saverrstate = seterr(under='ignore') - try: + with errstate(under='ignore'): self._do_init(float_conv, int_conv, float_to_float, float_to_str, title) - finally: - seterr(**saverrstate) def _do_init(self, float_conv, int_conv, float_to_float, float_to_str, title): max_iterN = 10000 diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index 13ee89744..9ae1af654 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -2125,8 +2125,7 @@ def allclose(a, b, rtol=1.e-5, atol=1.e-8): y = y[~xinf] # ignore invalid fpe's - with warnings.catch_warnings(): - warnings.simplefilter("ignore") + with errstate(invalid='ignore'): r = all(less_equal(abs(x-y), atol + rtol * abs(y))) return r @@ -2191,11 +2190,8 @@ def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False): array([True, True]) """ def within_tol(x, y, atol, rtol): - err = seterr(invalid='ignore') - try: + with errstate(invalid='ignore'): result = less_equal(abs(x-y), atol + rtol * abs(y)) - finally: - seterr(**err) if isscalar(a) and isscalar(b): result = bool(result) return result @@ -2705,15 +2701,18 @@ class errstate(object): def __init__(self, **kwargs): self.call = kwargs.pop('call',_Unspecified) self.kwargs = kwargs + def __enter__(self): self.oldstate = seterr(**self.kwargs) if self.call is not _Unspecified: self.oldcall = seterrcall(self.call) + def __exit__(self, *exc_info): seterr(**self.oldstate) if self.call is not _Unspecified: seterrcall(self.oldcall) + def _setdef(): defval = [UFUNC_BUFSIZE_DEFAULT, ERR_DEFAULT2, None] umath.seterrobj(defval) diff --git a/numpy/core/tests/test_half.py b/numpy/core/tests/test_half.py index 223a6f551..e5f2eaf9b 100644 --- a/numpy/core/tests/test_half.py +++ b/numpy/core/tests/test_half.py @@ -71,8 +71,7 @@ class TestHalf(TestCase): assert_equal(i_int,j) def test_nans_infs(self): - oldsettings = np.seterr(all='ignore') - try: + with np.errstate(all='ignore'): # Check some of the ufuncs assert_equal(np.isnan(self.all_f16), np.isnan(self.all_f32)) assert_equal(np.isinf(self.all_f16), np.isinf(self.all_f32)) @@ -100,9 +99,6 @@ class TestHalf(TestCase): assert_(not (self.all_f16 >= nan).any()) assert_(not (nan >= self.all_f16).any()) - finally: - np.seterr(**oldsettings) - def test_half_values(self): """Confirms a small number of known half values""" @@ -363,8 +359,7 @@ class TestHalf(TestCase): @dec.skipif(platform.machine() == "armv5tel", "See gh-413.") def test_half_fpe(self): - oldsettings = np.seterr(all='raise') - try: + with np.errstate(all='raise'): sx16 = np.array((1e-4,),dtype=float16) bx16 = np.array((1e4,),dtype=float16) sy16 = float16(1e-4) @@ -426,8 +421,6 @@ class TestHalf(TestCase): float16(-2**-14)/float16(2**10) float16(2**-14+2**-23)/float16(2) float16(-2**-14-2**-23)/float16(2) - finally: - np.seterr(**oldsettings) def test_half_array_interface(self): """Test that half is compatible with __array_interface__""" diff --git a/numpy/core/tests/test_machar.py b/numpy/core/tests/test_machar.py index 120d51339..8d858c28b 100644 --- a/numpy/core/tests/test_machar.py +++ b/numpy/core/tests/test_machar.py @@ -4,7 +4,7 @@ from numpy.testing import * from numpy.core.machar import MachAr import numpy.core.numerictypes as ntypes -from numpy import seterr, array +from numpy import errstate, array class TestMachAr(TestCase): def _run_machar_highprec(self): @@ -19,14 +19,11 @@ class TestMachAr(TestCase): def test_underlow(self): """Regression testing for #759: instanciating MachAr for dtype = np.float96 raises spurious warning.""" - serrstate = seterr(all='raise') - try: + with errstate(all='raise'): try: self._run_machar_highprec() except FloatingPointError as e: self.fail("Caught %s exception, should not have been raised." % e) - finally: - seterr(**serrstate) if __name__ == "__main__": diff --git a/numpy/core/tests/test_numeric.py b/numpy/core/tests/test_numeric.py index 751722ffb..1be0f4105 100644 --- a/numpy/core/tests/test_numeric.py +++ b/numpy/core/tests/test_numeric.py @@ -351,8 +351,8 @@ class TestSeterr(TestCase): )) def test_set(self): - err = seterr() - try: + with np.errstate(): + err = seterr() old = seterr(divide='print') self.assertTrue(err == old) new = seterr() @@ -362,13 +362,10 @@ class TestSeterr(TestCase): self.assertTrue(new['divide'] == 'print') seterr(**old) self.assertTrue(geterr() == old) - finally: - seterr(**err) @dec.skipif(platform.machine() == "armv5tel", "See gh-413.") def test_divide_err(self): - err = seterr(divide='raise') - try: + with errstate(divide='raise'): try: array([1.]) / array([0.]) except FloatingPointError: @@ -377,8 +374,6 @@ class TestSeterr(TestCase): self.fail() seterr(divide='ignore') array([1.]) / array([0.]) - finally: - seterr(**err) class TestFloatExceptions(TestCase): @@ -407,8 +402,7 @@ class TestFloatExceptions(TestCase): @dec.knownfailureif(True, "See ticket 1755") def test_floating_exceptions(self): # Test basic arithmetic function errors - oldsettings = np.seterr(all='raise') - try: + with np.errstate(all='raise'): # Test for all real and complex float types for typecode in np.typecodes['AllFloat']: ftype = np.obj2sctype(typecode) @@ -459,8 +453,6 @@ class TestFloatExceptions(TestCase): lambda a,b:a+b, ftype(np.inf), ftype(-np.inf)) self.assert_raises_fpe(invalid, lambda a,b:a*b, ftype(0), ftype(np.inf)) - finally: - np.seterr(**oldsettings) class TestTypes(TestCase): def check_promotion_cases(self, promote_func): diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py index 6dfee51d8..492b08cb9 100644 --- a/numpy/core/tests/test_regression.py +++ b/numpy/core/tests/test_regression.py @@ -655,11 +655,8 @@ class TestRegression(TestCase): def test_array_str_64bit(self, level=rlevel): """Ticket #501""" s = np.array([1, np.nan],dtype=np.float64) - errstate = np.seterr(all='raise') - try: + with np.errstate(all='raise'): sstr = np.array_str(s) - finally: - np.seterr(**errstate) def test_frompyfunc_endian(self, level=rlevel): """Ticket #503""" @@ -1120,14 +1117,11 @@ class TestRegression(TestCase): def test_sign_for_complex_nan(self, level=rlevel): """Ticket 794.""" - olderr = np.seterr(invalid='ignore') - try: + with np.errstate(invalid='ignore'): C = np.array([-np.inf, -2+1j, 0, 2-1j, np.inf, np.nan]) have = np.sign(C) want = np.array([-1+0j, -1+0j, 0+0j, 1+0j, 1+0j, np.nan]) assert_equal(have, want) - finally: - np.seterr(**olderr) def test_for_equal_names(self, level=rlevel): """Ticket #674""" @@ -1169,8 +1163,7 @@ class TestRegression(TestCase): def test_errobj_reference_leak(self, level=rlevel): """Ticket #955""" - old_err = np.seterr(all="ignore") - try: + with np.errstate(all="ignore"): z = int(0) p = np.int32(-1) @@ -1180,8 +1173,6 @@ class TestRegression(TestCase): gc.collect() n_after = len(gc.get_objects()) assert_(n_before >= n_after, (n_before, n_after)) - finally: - np.seterr(**old_err) def test_void_scalar_with_titles(self, level=rlevel): """No ticket""" @@ -1415,12 +1406,9 @@ class TestRegression(TestCase): min = np.array([np.iinfo(t).min]) min //= -1 - old_err = np.seterr(divide="ignore") - try: + with np.errstate(divide="ignore"): for t in (np.int8, np.int16, np.int32, np.int64, np.int, np.long): test_type(t) - finally: - np.seterr(**old_err) def test_buffer_hashlib(self): try: diff --git a/numpy/core/tests/test_scalarmath.py b/numpy/core/tests/test_scalarmath.py index 952a89999..3e1aaef3b 100644 --- a/numpy/core/tests/test_scalarmath.py +++ b/numpy/core/tests/test_scalarmath.py @@ -110,8 +110,7 @@ class TestPower(TestCase): class TestComplexDivision(TestCase): def test_zero_division(self): - err = np.seterr(all="ignore") - try: + with np.errstate(all="ignore"): for t in [np.complex64, np.complex128]: a = t(0.0) b = t(1.0) @@ -126,8 +125,6 @@ class TestComplexDivision(TestCase): assert_(np.isnan(b/a)) b = t(0.) assert_(np.isnan(b/a)) - finally: - np.seterr(**err) class TestConversion(TestCase): diff --git a/numpy/core/tests/test_umath.py b/numpy/core/tests/test_umath.py index c58a0d3f5..c2304a748 100644 --- a/numpy/core/tests/test_umath.py +++ b/numpy/core/tests/test_umath.py @@ -60,8 +60,7 @@ class TestDivision(TestCase): assert_almost_equal(y/x, [1, 1], err_msg=msg) def test_zero_division_complex(self): - err = np.seterr(invalid="ignore", divide="ignore") - try: + with np.errstate(invalid="ignore", divide="ignore"): x = np.array([0.0], dtype=np.complex128) y = 1.0/x assert_(np.isinf(y)[0]) @@ -73,8 +72,6 @@ class TestDivision(TestCase): assert_(np.isinf(y)[0]) y = 0.0/x assert_(np.isnan(y)[0]) - finally: - np.seterr(**err) def test_floor_division_complex(self): # check that implementation is correct @@ -140,14 +137,11 @@ class TestPower(TestCase): assert_array_equal(x.imag, y.imag) for z in [complex(0, np.inf), complex(1, np.inf)]: - err = np.seterr(invalid="ignore") z = np.array([z], dtype=np.complex_) - try: + with np.errstate(invalid="ignore"): assert_complex_equal(z**1, z) assert_complex_equal(z**2, z*z) assert_complex_equal(z**3, z*z*z) - finally: - np.seterr(**err) def test_power_zero(self): # ticket #1271 @@ -221,19 +215,16 @@ class TestLogAddExp2(_FilterInvalids): assert_almost_equal(np.logaddexp2(logxf, logyf), logzf) def test_inf(self) : - err = np.seterr(invalid='ignore') inf = np.inf x = [inf, -inf, inf, -inf, inf, 1, -inf, 1] y = [inf, inf, -inf, -inf, 1, inf, 1, -inf] z = [inf, inf, inf, -inf, inf, inf, 1, 1] - try: + with np.errstate(invalid='ignore'): for dt in ['f','d','g'] : logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) assert_equal(np.logaddexp2(logxf, logyf), logzf) - finally: - np.seterr(**err) def test_nan(self): assert_(np.isnan(np.logaddexp2(np.nan, np.inf))) @@ -287,19 +278,16 @@ class TestLogAddExp(_FilterInvalids): assert_almost_equal(np.logaddexp(logxf, logyf), logzf) def test_inf(self) : - err = np.seterr(invalid='ignore') inf = np.inf x = [inf, -inf, inf, -inf, inf, 1, -inf, 1] y = [inf, inf, -inf, -inf, 1, inf, 1, -inf] z = [inf, inf, inf, -inf, inf, inf, 1, 1] - try: + with np.errstate(invalid='ignore'): for dt in ['f','d','g'] : logxf = np.array(x, dtype=dt) logyf = np.array(y, dtype=dt) logzf = np.array(z, dtype=dt) assert_equal(np.logaddexp(logxf, logyf), logzf) - finally: - np.seterr(**err) def test_nan(self): assert_(np.isnan(np.logaddexp(np.nan, np.inf))) @@ -328,19 +316,15 @@ class TestHypot(TestCase, object): def assert_hypot_isnan(x, y): - err = np.seterr(invalid='ignore') - try: - assert_(np.isnan(ncu.hypot(x, y)), "hypot(%s, %s) is %s, not nan" % (x, y, ncu.hypot(x, y))) - finally: - np.seterr(**err) + with np.errstate(invalid='ignore'): + assert_(np.isnan(ncu.hypot(x, y)), + "hypot(%s, %s) is %s, not nan" % (x, y, ncu.hypot(x, y))) def assert_hypot_isinf(x, y): - err = np.seterr(invalid='ignore') - try: - assert_(np.isinf(ncu.hypot(x, y)), "hypot(%s, %s) is %s, not inf" % (x, y, ncu.hypot(x, y))) - finally: - np.seterr(**err) + with np.errstate(invalid='ignore'): + assert_(np.isinf(ncu.hypot(x, y)), + "hypot(%s, %s) is %s, not inf" % (x, y, ncu.hypot(x, y))) class TestHypotSpecialValues(TestCase): @@ -465,14 +449,11 @@ class TestLdexp(TestCase): def test_ldexp_overflow(self): # silence warning emitted on overflow - err = np.seterr(over="ignore") - try: + with np.errstate(over="ignore"): imax = np.iinfo(np.dtype('l')).max imin = np.iinfo(np.dtype('l')).min assert_equal(ncu.ldexp(2., imax), np.inf) assert_equal(ncu.ldexp(2., imin), 0) - finally: - np.seterr(**err) class TestMaximum(_FilterInvalids): @@ -676,15 +657,12 @@ class TestSign(TestCase): out = np.zeros(a.shape) tgt = np.array([1., -1., np.nan, 0.0, 1.0, -1.0]) - olderr = np.seterr(invalid='ignore') - try: + with np.errstate(invalid='ignore'): res = ncu.sign(a) assert_equal(res, tgt) res = ncu.sign(a, out) assert_equal(res, tgt) assert_equal(out, tgt) - finally: - np.seterr(**olderr) class TestMinMax(TestCase): @@ -719,19 +697,17 @@ class TestAbsolute(TestCase): assert_equal(out, tgt, err_msg=msg) self.assertTrue((out >= 0).all()) - prev = np.geterr() # will throw invalid flag depending on compiler optimizations - np.seterr(invalid='ignore') - for v in [np.nan, -np.inf, np.inf]: - for i in range(inp.size): - d = np.arange(inp.size, dtype=dt) - inp[:] = -d - inp[i] = v - d[i] = -v if v == -np.inf else v - assert_array_equal(np.abs(inp), d, err_msg=msg) - np.abs(inp, out=out) - assert_array_equal(out, d, err_msg=msg) - np.seterr(invalid=prev['invalid']) + with np.errstate(invalid='ignore'): + for v in [np.nan, -np.inf, np.inf]: + for i in range(inp.size): + d = np.arange(inp.size, dtype=dt) + inp[:] = -d + inp[i] = v + d[i] = -v if v == -np.inf else v + assert_array_equal(np.abs(inp), d, err_msg=msg) + np.abs(inp, out=out) + assert_array_equal(out, d, err_msg=msg) class TestSpecialMethods(TestCase): @@ -1164,12 +1140,9 @@ def _check_branch_cut(f, x0, dx, re_sign=1, im_sign=-1, sig_zero_ok=False, def test_copysign(): assert_(np.copysign(1, -1) == -1) - old_err = np.seterr(divide="ignore") - try: + with np.errstate(divide="ignore"): assert_(1 / np.copysign(0, -1) < 0) assert_(1 / np.copysign(0, 1) > 0) - finally: - np.seterr(**old_err) assert_(np.signbit(np.copysign(np.nan, -1))) assert_(not np.signbit(np.copysign(np.nan, 1))) @@ -1196,19 +1169,16 @@ def test_nextafterl(): return _test_nextafter(np.longdouble) def _test_spacing(t): - err = np.seterr(invalid='ignore') one = t(1) eps = np.finfo(t).eps nan = t(np.nan) inf = t(np.inf) - try: + with np.errstate(invalid='ignore'): assert_(np.spacing(one) == eps) assert_(np.isnan(np.spacing(nan))) assert_(np.isnan(np.spacing(inf))) assert_(np.isnan(np.spacing(-inf))) assert_(np.spacing(t(1e30)) != 0) - finally: - np.seterr(**err) def test_spacing(): return _test_spacing(np.float64) @@ -1299,8 +1269,7 @@ def test_complex_nan_comparisons(): fins = [complex(1, 0), complex(-1, 0), complex(0, 1), complex(0, -1), complex(1, 1), complex(-1, -1), complex(0, 0)] - olderr = np.seterr(invalid='ignore') - try: + with np.errstate(invalid='ignore'): for x in nans + fins: x = np.array([x]) for y in nans + fins: @@ -1314,8 +1283,6 @@ def test_complex_nan_comparisons(): assert_equal(x <= y, False, err_msg="%r <= %r" % (x, y)) assert_equal(x >= y, False, err_msg="%r >= %r" % (x, y)) assert_equal(x == y, False, err_msg="%r == %r" % (x, y)) - finally: - np.seterr(**olderr) if __name__ == "__main__": diff --git a/numpy/core/tests/test_umath_complex.py b/numpy/core/tests/test_umath_complex.py index f9681ff07..ebf805c6d 100644 --- a/numpy/core/tests/test_umath_complex.py +++ b/numpy/core/tests/test_umath_complex.py @@ -14,12 +14,9 @@ import numpy as np # At least on Windows the results of many complex functions are not conforming # to the C99 standard. See ticket 1574. # Ditto for Solaris (ticket 1642) and OS X on PowerPC. -olderr = np.seterr(all='ignore') -try: +with np.errstate(all='ignore'): functions_seem_flaky = ((np.exp(complex(np.inf, 0)).imag != 0) or (np.log(complex(np.NZERO, 0)).imag != np.pi)) -finally: - np.seterr(**olderr) # TODO: replace with a check on whether platform-provided C99 funcs are used skip_complex_tests = (not sys.platform.startswith('linux') or functions_seem_flaky) @@ -78,52 +75,40 @@ class TestCexp(object): # cexp(-inf + inf i) is +-0 +- 0i (signs unspecified) def _check_ninf_inf(dummy): msgform = "cexp(-inf, inf) is (%f, %f), expected (+-0, +-0)" - err = np.seterr(invalid='ignore') - try: + with np.errstate(invalid='ignore'): z = f(np.array(np.complex(-np.inf, np.inf))) if z.real != 0 or z.imag != 0: raise AssertionError(msgform %(z.real, z.imag)) - finally: - np.seterr(**err) yield _check_ninf_inf, None # cexp(inf + inf i) is +-inf + NaNi and raised invalid FPU ex. def _check_inf_inf(dummy): msgform = "cexp(inf, inf) is (%f, %f), expected (+-inf, nan)" - err = np.seterr(invalid='ignore') - try: + with np.errstate(invalid='ignore'): z = f(np.array(np.complex(np.inf, np.inf))) if not np.isinf(z.real) or not np.isnan(z.imag): raise AssertionError(msgform % (z.real, z.imag)) - finally: - np.seterr(**err) yield _check_inf_inf, None # cexp(-inf + nan i) is +-0 +- 0i def _check_ninf_nan(dummy): msgform = "cexp(-inf, nan) is (%f, %f), expected (+-0, +-0)" - err = np.seterr(invalid='ignore') - try: + with np.errstate(invalid='ignore'): z = f(np.array(np.complex(-np.inf, np.nan))) if z.real != 0 or z.imag != 0: raise AssertionError(msgform % (z.real, z.imag)) - finally: - np.seterr(**err) yield _check_ninf_nan, None # cexp(inf + nan i) is +-inf + nan def _check_inf_nan(dummy): msgform = "cexp(-inf, nan) is (%f, %f), expected (+-inf, nan)" - err = np.seterr(invalid='ignore') - try: + with np.errstate(invalid='ignore'): z = f(np.array(np.complex(np.inf, np.nan))) if not np.isinf(z.real) or not np.isnan(z.imag): raise AssertionError(msgform % (z.real, z.imag)) - finally: - np.seterr(**err) yield _check_inf_nan, None @@ -164,30 +149,24 @@ class TestClog(TestCase): # clog(-0 + i0) returns -inf + i pi and raises the 'divide-by-zero' # floating-point exception. - err = np.seterr(divide='raise') - try: + with np.errstate(divide='raise'): x = np.array([np.NZERO], dtype=np.complex) y = np.complex(-np.inf, np.pi) self.assertRaises(FloatingPointError, np.log, x) - np.seterr(divide='ignore') + with np.errstate(divide='ignore'): assert_almost_equal(np.log(x), y) - finally: - np.seterr(**err) xl.append(x) yl.append(y) # clog(+0 + i0) returns -inf + i0 and raises the 'divide-by-zero' # floating-point exception. - err = np.seterr(divide='raise') - try: + with np.errstate(divide='raise'): x = np.array([0], dtype=np.complex) y = np.complex(-np.inf, 0) self.assertRaises(FloatingPointError, np.log, x) - np.seterr(divide='ignore') + with np.errstate(divide='ignore'): assert_almost_equal(np.log(x), y) - finally: - np.seterr(**err) xl.append(x) yl.append(y) @@ -206,27 +185,21 @@ class TestClog(TestCase): # clog(x + iNaN) returns NaN + iNaN and optionally raises the # 'invalid' floating- point exception, for finite x. - err = np.seterr(invalid='raise') - try: + with np.errstate(invalid='raise'): x = np.array([complex(1., np.nan)], dtype=np.complex) y = np.complex(np.nan, np.nan) #self.assertRaises(FloatingPointError, np.log, x) - np.seterr(invalid='ignore') + with np.errstate(invalid='ignore'): assert_almost_equal(np.log(x), y) - finally: - np.seterr(**err) xl.append(x) yl.append(y) - err = np.seterr(invalid='raise') - try: + with np.errstate(invalid='raise'): x = np.array([np.inf + 1j * np.nan], dtype=np.complex) #self.assertRaises(FloatingPointError, np.log, x) - np.seterr(invalid='ignore') + with np.errstate(invalid='ignore'): assert_almost_equal(np.log(x), y) - finally: - np.seterr(**err) xl.append(x) yl.append(y) @@ -296,12 +269,9 @@ class TestClog(TestCase): # clog(conj(z)) = conj(clog(z)). xa = np.array(xl, dtype=np.complex) ya = np.array(yl, dtype=np.complex) - err = np.seterr(divide='ignore') - try: + with np.errstate(divide='ignore'): for i in range(len(xa)): assert_almost_equal(np.log(np.conj(xa[i])), np.conj(np.log(xa[i]))) - finally: - np.seterr(**err) class TestCsqrt(object): @@ -362,12 +332,9 @@ class TestCsqrt(object): msgform = "csqrt(-inf, nan) is (%f, %f), expected (nan, +-inf)" z = np.sqrt(np.array(np.complex(-np.inf, np.nan))) #Fixme: ugly workaround for isinf bug. - err = np.seterr(invalid='ignore') - try: + with np.errstate(invalid='ignore'): if not (np.isnan(z.real) and np.isinf(z.imag)): raise AssertionError(msgform % (z.real, z.imag)) - finally: - np.seterr(**err) yield _check_ninf_nan, None @@ -558,16 +525,13 @@ def check_real_value(f, x1, y1, x, exact=True): assert_almost_equal(f(z1), x) def check_complex_value(f, x1, y1, x2, y2, exact=True): - err = np.seterr(invalid='ignore') z1 = np.array([complex(x1, y1)]) z2 = np.complex(x2, y2) - try: + with np.errstate(invalid='ignore'): if exact: assert_equal(f(z1), z2) else: assert_almost_equal(f(z1), z2) - finally: - np.seterr(**err) if __name__ == "__main__": run_module_suite() |