Skip to content

Commit 26bb120

Browse files
committed
FIX: Safer warning registry manipulation when checking for overflows
1 parent 6952c1f commit 26bb120

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

nibabel/volumeutils.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from __future__ import division, print_function
1111

1212
import sys
13+
import re
1314
import warnings
1415
import gzip
1516
from collections import OrderedDict
@@ -41,6 +42,13 @@
4142
#: file-like classes known to hold compressed data
4243
COMPRESSED_FILE_LIKES = (gzip.GzipFile, BZ2File)
4344

45+
_OVERFLOW_FILTER = (
46+
'ignore',
47+
re.compile(r'.*overflow.*', re.IGNORECASE | re.UNICODE),
48+
RuntimeWarning,
49+
re.compile(r'', re.UNICODE),
50+
0)
51+
4452

4553
class Recoder(object):
4654
''' class to return canonical code(s) from code or aliases
@@ -1334,7 +1342,9 @@ def _ftype4scaled_finite(tst_arr, slope, inter, direction='read',
13341342
tst_arr = np.atleast_1d(tst_arr)
13351343
slope = np.atleast_1d(slope)
13361344
inter = np.atleast_1d(inter)
1337-
warnings.filterwarnings('ignore', '.*overflow.*', RuntimeWarning)
1345+
warnings.filters.insert(0, _OVERFLOW_FILTER)
1346+
getattr(warnings, '_filters_mutated', lambda: None)() # PY2
1347+
# warnings._filters_mutated() # PY3
13381348
try:
13391349
for ftype in OK_FLOATS[def_ind:]:
13401350
tst_trans = tst_arr.copy()
@@ -1353,7 +1363,12 @@ def _ftype4scaled_finite(tst_arr, slope, inter, direction='read',
13531363
if np.all(np.isfinite(tst_trans)):
13541364
return ftype
13551365
finally:
1356-
warnings.filters.pop(0)
1366+
try:
1367+
warnings.filters.remove(_OVERFLOW_FILTER)
1368+
getattr(warnings, '_filters_mutated', lambda: None)() # PY2
1369+
# warnings._filters_mutated() # PY3
1370+
except ValueError:
1371+
pass
13571372
raise ValueError('Overflow using highest floating point type')
13581373

13591374

0 commit comments

Comments
 (0)