Skip to content

Commit

Permalink
MAINT: Remove uses of the WarningManager class.
Browse files Browse the repository at this point in the history
WarningManager was a workaround for the lack of the with statement
in Python versions < 2.6. As those versions are no longer supported
it can be removed.

Deprecation notes are added to WarningManager and WarningMessage, but
to avoid a cascade of messages in third party apps, no warnings are
raised at this time, that can be done later.

Closes #3519.
  • Loading branch information
charris committed Jul 12, 2013
1 parent a053a43 commit 05a15c8
Show file tree
Hide file tree
Showing 12 changed files with 70 additions and 150 deletions.
3 changes: 1 addition & 2 deletions numpy/core/tests/test_api.py
@@ -1,11 +1,10 @@
from __future__ import division, absolute_import, print_function

import sys
import warnings

import numpy as np
from numpy.testing import *
from numpy.testing.utils import WarningManager
import warnings
from numpy.compat import sixu

# Switch between new behaviour when NPY_RELAXED_STRIDES_CHECKING is set.
Expand Down
9 changes: 2 additions & 7 deletions numpy/core/tests/test_einsum.py
@@ -1,12 +1,11 @@
from __future__ import division, absolute_import, print_function

import sys
import warnings
from decimal import Decimal

import numpy as np
from numpy.testing import *
from numpy.testing.utils import WarningManager
import warnings

class TestEinSum(TestCase):
def test_einsum_errors(self):
Expand Down Expand Up @@ -272,9 +271,7 @@ def check_einsum_sums(self, dtype):
assert_equal(np.einsum(a, [0], b, [1]), np.outer(a, b))

# Suppress the complex warnings for the 'as f8' tests
ctx = WarningManager()
ctx.__enter__()
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore', np.ComplexWarning)

# matvec(a,b) / a.dot(b) where a is matrix, b is vector
Expand Down Expand Up @@ -379,8 +376,6 @@ def check_einsum_sums(self, dtype):
dtype='f8', casting='unsafe')
assert_equal(c, np.tensordot(a.astype('f8'), b.astype('f8'),
axes=([1,0],[0,1])).astype(dtype))
finally:
ctx.__exit__()

# logical_and(logical_and(a!=0, b!=0), c!=0)
a = np.array([1, 3, -2, 0, 12, 13, 0, 1], dtype=dtype)
Expand Down
41 changes: 17 additions & 24 deletions numpy/core/tests/test_multiarray.py
Expand Up @@ -8,7 +8,6 @@
import numpy as np
from nose import SkipTest
from numpy.core import *
from numpy.testing.utils import WarningManager
from numpy.compat import asbytes, getexception, strchar, sixu
from test_print import in_foreign_locale
from numpy.core.multiarray_tests import (
Expand Down Expand Up @@ -958,17 +957,13 @@ def test_diagonal(self):
assert_equal(b.diagonal(0, 2, 1), [[0, 3], [4, 7]])

def test_diagonal_deprecation(self):
import warnings
from numpy.testing.utils import WarningManager

def collect_warning_types(f, *args, **kwargs):
ctx = WarningManager(record=True)
warning_log = ctx.__enter__()
warnings.simplefilter("always")
try:
with warnings.catch_warnings(record=True) as log:
warnings.simplefilter("always")
f(*args, **kwargs)
finally:
ctx.__exit__()
return [w.category for w in warning_log]
return [w.category for w in log]

a = np.arange(9).reshape(3, 3)
# All the different functions raise a warning, but not an error, and
# 'a' is not modified:
Expand Down Expand Up @@ -2028,17 +2023,13 @@ def test_field_names(self):
assert_raises(ValueError, a.__getitem__, sixu('\u03e0'))

def test_field_names_deprecation(self):
import warnings
from numpy.testing.utils import WarningManager

def collect_warning_types(f, *args, **kwargs):
ctx = WarningManager(record=True)
warning_log = ctx.__enter__()
warnings.simplefilter("always")
try:
with warnings.catch_warnings(record=True) as log:
warnings.simplefilter("always")
f(*args, **kwargs)
finally:
ctx.__exit__()
return [w.category for w in warning_log]
return [w.category for w in log]

a = np.zeros((1,), dtype=[('f1', 'i4'),
('f2', 'i4'),
('f3', [('sf1', 'i4')])])
Expand Down Expand Up @@ -2500,36 +2491,38 @@ def test_simple_strict_within(self):
assert_array_equal(l, r)

class TestWarnings(object):

def test_complex_warning(self):
x = np.array([1,2])
y = np.array([1-2j,1+2j])

warn_ctx = WarningManager()
warn_ctx.__enter__()
try:
with warnings.catch_warnings():
warnings.simplefilter("error", np.ComplexWarning)
assert_raises(np.ComplexWarning, x.__setitem__, slice(None), y)
assert_equal(x, [1,2])
finally:
warn_ctx.__exit__()

class TestMinScalarType(object):

def test_usigned_shortshort(self):
dt = np.min_scalar_type(2**8-1)
wanted = np.dtype('uint8')
assert_equal(wanted, dt)

def test_usigned_short(self):
dt = np.min_scalar_type(2**16-1)
wanted = np.dtype('uint16')
assert_equal(wanted, dt)

def test_usigned_int(self):
dt = np.min_scalar_type(2**32-1)
wanted = np.dtype('uint32')
assert_equal(wanted, dt)

def test_usigned_longlong(self):
dt = np.min_scalar_type(2**63-1)
wanted = np.dtype('uint64')
assert_equal(wanted, dt)

def test_object(self):
dt = np.min_scalar_type(2**64)
wanted = np.dtype('O')
Expand Down
8 changes: 2 additions & 6 deletions numpy/core/tests/test_regression.py
Expand Up @@ -16,7 +16,7 @@
assert_almost_equal, assert_array_equal, assert_array_almost_equal,
assert_raises, assert_warns, dec
)
from numpy.testing.utils import _assert_valid_refcount, WarningManager
from numpy.testing.utils import _assert_valid_refcount
from numpy.compat import asbytes, asunicode, asbytes_nested, long, sixu

rlevel = 1
Expand Down Expand Up @@ -1545,13 +1545,9 @@ def test_complex_scalar_warning(self):
for tp in [np.csingle, np.cdouble, np.clongdouble]:
x = tp(1+2j)
assert_warns(np.ComplexWarning, float, x)
warn_ctx = WarningManager()
warn_ctx.__enter__()
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
assert_equal(float(x), float(x.real))
finally:
warn_ctx.__exit__()

def test_complex_scalar_complex_cast(self):
for tp in [np.csingle, np.cdouble, np.clongdouble]:
Expand Down
36 changes: 10 additions & 26 deletions numpy/lib/tests/test_io.py
Expand Up @@ -10,7 +10,6 @@
import gc
from io import BytesIO
from datetime import datetime
from numpy.testing.utils import WarningManager

import numpy as np
import numpy.ma as ma
Expand Down Expand Up @@ -571,14 +570,13 @@ def test_3d_shaped_dtype(self):
dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
('block', int, (2, 2, 3))])
x = np.loadtxt(c, dtype=dt)
a = np.array([('aaaa', 1.0, 8.0, [[[1, 2, 3], [4, 5, 6]],[[7, 8, 9], [10, 11, 12]]])],
dtype=dt)
a = np.array([('aaaa', 1.0, 8.0,
[[[1, 2, 3], [4, 5, 6]],[[7, 8, 9], [10, 11, 12]]])],
dtype=dt)
assert_array_equal(x, a)

def test_empty_file(self):
warn_ctx = WarningManager()
warn_ctx.__enter__()
try:
with warnings.catch_warnings():
warnings.filterwarnings("ignore",
message="loadtxt: Empty input file:")
c = TextIO()
Expand All @@ -587,8 +585,6 @@ def test_empty_file(self):
x = np.loadtxt(c, dtype=np.int64)
assert_equal(x.shape, (0,))
assert_(x.dtype == np.int64)
finally:
warn_ctx.__exit__()


def test_unused_converter(self):
Expand Down Expand Up @@ -704,16 +700,12 @@ def test_ndmin_keyword(self):
assert_(x.shape == (3,))

# Test ndmin kw with empty file.
warn_ctx = WarningManager()
warn_ctx.__enter__()
try:
with warnings.catch_warnings():
warnings.filterwarnings("ignore",
message="loadtxt: Empty input file:")
f = TextIO()
assert_(np.loadtxt(f, ndmin=2).shape == (0, 1,))
assert_(np.loadtxt(f, ndmin=1).shape == (0,))
finally:
warn_ctx.__exit__()

def test_generator_source(self):
def count():
Expand Down Expand Up @@ -841,11 +833,9 @@ def test_skip_footer(self):
assert_equal(test, ctrl)

def test_skip_footer_with_invalid(self):
warn_ctx = WarningManager()
warn_ctx.__enter__()
try:
basestr = '1 1\n2 2\n3 3\n4 4\n5 \n6 \n7 \n'
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
basestr = '1 1\n2 2\n3 3\n4 4\n5 \n6 \n7 \n'
# Footer too small to get rid of all invalid values
assert_raises(ValueError, np.genfromtxt,
TextIO(basestr), skip_footer=1)
Expand All @@ -862,9 +852,6 @@ def test_skip_footer_with_invalid(self):
assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.], [6., 6.]]))
a = np.genfromtxt(TextIO(basestr), skip_footer=3, invalid_raise=False)
assert_equal(a, np.array([[1., 1.], [3., 3.], [4., 4.]]))
finally:
warn_ctx.__exit__()


def test_header(self):
"Test retrieving a header"
Expand Down Expand Up @@ -1168,15 +1155,12 @@ def test_usecols_with_named_columns(self):

def test_empty_file(self):
"Test that an empty file raises the proper warning."
warn_ctx = WarningManager()
warn_ctx.__enter__()
try:
warnings.filterwarnings("ignore", message="genfromtxt: Empty input file:")
with warnings.catch_warnings():
warnings.filterwarnings("ignore",
message="genfromtxt: Empty input file:")
data = TextIO()
test = np.genfromtxt(data)
assert_equal(test, np.array([]))
finally:
warn_ctx.__exit__()

def test_fancy_dtype_alt(self):
"Check that a nested dtype isn't MIA"
Expand Down
8 changes: 2 additions & 6 deletions numpy/lib/utils.py
Expand Up @@ -1107,18 +1107,14 @@ def safe_eval(source):
"""
# Local imports to speed up numpy's import time.
import warnings
from numpy.testing.utils import WarningManager
warn_ctx = WarningManager()
warn_ctx.__enter__()
try:

with warnings.catch_warnings():
# compiler package is deprecated for 3.x, which is already solved here
warnings.simplefilter('ignore', DeprecationWarning)
try:
import compiler
except ImportError:
import ast as compiler
finally:
warn_ctx.__exit__()

walker = SafeEval()
try:
Expand Down
19 changes: 3 additions & 16 deletions numpy/ma/tests/test_core.py
Expand Up @@ -20,7 +20,6 @@
from numpy.ma.testutils import *
from numpy.ma.core import *
from numpy.compat import asbytes, asbytes_nested
from numpy.testing.utils import WarningManager

pi = np.pi

Expand Down Expand Up @@ -422,13 +421,9 @@ def test_topython(self):
assert_equal(1.0, float(array([[1]])))
self.assertRaises(TypeError, float, array([1, 1]))
#
warn_ctx = WarningManager()
warn_ctx.__enter__()
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
assert_(np.isnan(float(array([1], mask=[1]))))
finally:
warn_ctx.__exit__()
#
a = array([1, 2, 3], mask=[1, 0, 0])
self.assertRaises(TypeError, lambda:float(a))
Expand Down Expand Up @@ -2764,23 +2759,15 @@ def test_varstd_specialcases(self):
self.assertTrue(method(0) is masked)
self.assertTrue(method(-1) is masked)
# Using a masked array as explicit output
warn_ctx = WarningManager()
warn_ctx.__enter__()
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
_ = method(out=mout)
finally:
warn_ctx.__exit__()
self.assertTrue(mout is not masked)
assert_equal(mout.mask, True)
# Using a ndarray as explicit output
warn_ctx = WarningManager()
warn_ctx.__enter__()
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
_ = method(out=nout)
finally:
warn_ctx.__exit__()
self.assertTrue(np.isnan(nout))
#
x = array(arange(10), mask=True)
Expand Down
7 changes: 1 addition & 6 deletions numpy/ma/tests/test_mrecords.py
Expand Up @@ -21,7 +21,6 @@
from numpy.compat import asbytes, asbytes_nested
from numpy.ma.testutils import *
from numpy.ma import masked, nomask
from numpy.testing.utils import WarningManager
from numpy.ma.mrecords import MaskedRecords, mrecarray, fromarrays, \
fromtextfile, fromrecords, addfield

Expand Down Expand Up @@ -142,15 +141,11 @@ def test_set_fields(self):
rdata = data.view(MaskedRecords)
val = ma.array([10,20,30], mask=[1,0,0])
#
warn_ctx = WarningManager()
warn_ctx.__enter__()
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
rdata['num'] = val
assert_equal(rdata.num, val)
assert_equal(rdata.num.mask, [1,0,0])
finally:
warn_ctx.__exit__()

def test_set_fields_mask(self):
"Tests setting the mask of a field."
Expand Down
10 changes: 3 additions & 7 deletions numpy/random/__init__.py
Expand Up @@ -88,19 +88,15 @@
"""
from __future__ import division, absolute_import, print_function

import warnings

# To get sub-modules
from .info import __doc__, __all__

import warnings
from numpy.testing.utils import WarningManager

warn_ctx = WarningManager()
warn_ctx.__enter__()
try:
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
from .mtrand import *
finally:
warn_ctx.__exit__()

# Some aliases:
ranf = random = sample = random_sample
Expand Down

0 comments on commit 05a15c8

Please sign in to comment.