8000 Merge pull request #7148 from seberg/stacklevel+tests · numpy/numpy@3dbbfd8 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3dbbfd8

Browse files
authored
Merge pull request #7148 from seberg/stacklevel+tests
ENH,TST: Bump stacklevel and add tests for warnings
2 parents 9164f23 + 68ea0c7 commit 3dbbfd8

39 files changed

+202
-90
lines changed

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ matrix:
6161
- python: 2.7
6262
env: USE_WHEEL=1
6363
- python: 3.5
64-
env: USE_WHEEL=1
64+
env: USE_WHEEL=1 RUN_FULL_TESTS=1
6565
- python: 3.5
6666
env: USE_SDIST=1
6767
- python: 2.7

doc/release/1.12.0-notes.rst

Lines changed: 13 additions & 0 deletions
< F438 /div>
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,19 @@ is regular quicksort but changing to a heapsort when not enough progress is
319319
made. This retains the good quicksort performance while changing the worst case
320320
runtime from ``O(N^2)`` to ``O(N*log(N))``.
321321

322+
stacklevel of warnings increased
323+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
324+
The stacklevel for python based warnings was increased so that most warnings
325+
will report the offending line of the user code instead of the line the
326+
warning itself is given. Passing of stacklevel is now tested to ensure that
327+
new warnings will recieve the ``stacklevel`` argument.
328+
329+
This causes warnings with the "default" or "module" filter to be shown once
330+
for every offending user code line or user module instead of only once. On
331+
python versions before 3.4, this can cause warnings to appear that were falsly
332+
ignored before, which may be surprising especially in test suits.
333+
334+
322335
Deprecations
323336
============
324337

numpy/_import_tools.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def __call__(self,*packages, **options):
166166
# 2014-10-29, 1.10
167167
warnings.warn('pkgload and PackageLoader are obsolete '
168168
'and will be removed in a future version of numpy',
169-
DeprecationWarning)
169+
DeprecationWarning, stacklevel=2)
170170
frame = self.parent_frame
171171
self.info_modules = {}
172172
if options.get('force', False):

numpy/core/_methods.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def _mean(a, axis=None, dtype=None, out=None, keepdims=False):
5656
rcount = _count_reduce_items(arr, axis)
5757
# Make this warning show up first
5858
if rcount == 0:
59-
warnings.warn("Mean of empty slice.", RuntimeWarning)
59+
warnings.warn("Mean of empty slice.", RuntimeWarning, stacklevel=2)
6060

6161
# Cast bool, unsigned int, and int to float64 by default
6262
if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
@@ -79,7 +79,8 @@ def _var(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
7979
rcount = _count_reduce_items(arr, axis)
8080
# Make this warning show up on top.
8181
if ddof >= rcount:
82-
warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning)
82+
warnings.warn("Degrees of freedom <= 0 for slice", RuntimeWarning,
83+
stacklevel=2)
8384

8485
# Cast bool, unsigned int, and int to float64 by default
8586
if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)):

numpy/core/fromnumeric.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2647,7 +2647,7 @@ def rank(a):
26472647
warnings.warn(
26482648
"`rank` is deprecated; use the `ndim` attribute or function instead. "
26492649
"To find the rank of a matrix see `numpy.linalg.matrix_rank`.",
2650-
VisibleDeprecationWarning)
2650+
VisibleDeprecationWarning, stacklevel=2)
26512651
try:
26522652
return a.ndim
26532653
except AttributeError:

numpy/core/numeric.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1181,7 +1181,8 @@ def alterdot():
11811181
11821182
"""
11831183
# 2014-08-13, 1.10
1184-
warnings.warn("alterdot no longer does anything.", DeprecationWarning)
1184+
warnings.warn("alterdot no longer does anything.",
1185+
DeprecationWarning, stacklevel=2)
11851186

11861187

11871188
def restoredot():
@@ -1205,7 +1206,8 @@ def restoredot():
12051206
12061207
"""
12071208
# 2014-08-13, 1.10
1208-
warnings.warn("restoredot no longer does anything.", DeprecationWarning)
1209+
warnings.warn("restoredot no longer does anything.",
1210+
DeprecationWarning, stacklevel=2)
12091211

12101212

12111213
def tensordot(a, b, axes=2):
@@ -2260,8 +2262,8 @@ def warn_if_insufficient(width, binwdith):
22602262
if width is not None and width < binwidth:
22612263
warnings.warn(
22622264
"Insufficient bit width provided. This behavior "
2263-
"will raise an error in the future.", DeprecationWarning
2264-
)
2265+
"will raise an error in the future.", DeprecationWarning,
2266+
stacklevel=3)
22652267

22662268
if num == 0:
22672269
return '0' * (width or 1)

numpy/core/setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ def check_complex(config, mathlibs):
179179

180180
try:
181181
if os.uname()[0] == "Interix":
182-
warnings.warn("Disabling broken complex support. See #1365")
182+
warnings.warn("Disabling broken complex support. See #1365", stacklevel=2)
183183
return priv, pub
184184
except:
185185
# os.uname not available on all platforms. blanket except ugly but safe

numpy/core/setup_common.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ def check_api_version(apiversion, codegen_dir):
9494
)
9595
warnings.warn(msg % (apiversion, curapi_hash, apiversion, api_hash,
9696
__file__),
97-
MismatchCAPIWarning)
97+
MismatchCAPIWarning, stacklevel=2)
9898
# Mandatory functions: if not found, fail the build
9999
MANDATORY_FUNCS = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs",
100100
"floor", "ceil", "sqrt", "log10", "log", "exp", "asin",

numpy/core/tests/test_deprecations.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -641,7 +641,7 @@ def test_assert_deprecated(self):
641641
lambda: None)
642642

643643
def foo():
644-
warnings.warn("foo", category=DeprecationWarning)
644+
warnings.warn("foo", category=DeprecationWarning, stacklevel=2)
645645

646646
test_case_instance.assert_deprecated(foo)
647647
test_case_instance.tearDown()

numpy/ctypeslib.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def load_library(libname, loader_path):
119119
if ctypes.__version__ < '1.0.1':
120120
import warnings
121121
warnings.warn("All features of ctypes interface may not work " \
122-
"with ctypes < 1.0.1")
122+
"with ctypes < 1.0.1", stacklevel=2)
123123

124124
ext = os.path.splitext(libname)[1]
125125
if not ext:

numpy/distutils/command/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,7 @@ def get_output(self, body, headers=None, include_dirs=None,
431431
"use it anymore, and avoid configuration checks \n" \
432432
"involving running executable on the target machine.\n" \
433433
"+++++++++++++++++++++++++++++++++++++++++++++++++\n",
434-
DeprecationWarning)
434+
DeprecationWarning, stacklevel=2)
435435
from distutils.ccompiler import CompileError, LinkError
436436
self._check_compiler()
437437
exitcode, output = 255, ''

numpy/distutils/command/egg_info.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ def run(self):
1010
import warnings
1111
warnings.warn("`build_src` is being run, this may lead to missing "
1212
"files in your sdist! See numpy issue gh-7127 for "
13-
"details", UserWarning)
13+
"details", UserWarning, stacklevel=2)
1414

1515
# We need to ensure that build_src has been executed in order to give
1616
# setuptools' egg_info command real filenames instead of functions which

numpy/distutils/core.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -176,18 +176,21 @@ def _check_append_library(libraries, item):
176176
if item[1] is libitem[1]:
177177
return
178178
warnings.warn("[0] libraries list contains %r with"
179-
" different build_info" % (item[0],))
179+
" different build_info" % (item[0],),
180+
stacklevel=2)
180181
break
181182
else:
182183
if item==libitem[0]:
183184
warnings.warn("[1] libraries list contains %r with"
184-
" no build_info" % (item[0],))
185+
" no build_info" % (item[0],),
186+
stacklevel=2)
185187
break
186188
else:
187189
if is_sequence(item):
188190
if item[0]==libitem:
189191
warnings.warn("[2] libraries list contains %r with"
190-
" no build_info" % (item[0],))
192+
" no build_info" % (item[0],),
193+
stacklevel=2)
191194
break
192195
else:
193196
if item==libitem:
@@ -201,10 +204,12 @@ def _check_append_ext_library(libraries, lib_name, build_info):
201204
if item[1] is build_info:
202205
return
203206
warnings.warn("[3] libraries list contains %r with"
204-
" different build_info" % (lib_name,))
207+
" different build_info" % (lib_name,),
208+
stacklevel=2)
205209
break
206210
elif item==lib_name:
207211
warnings.warn("[4] libraries list contains %r with"
208-
" no build_info" % (lib_name,))
212+
" no build_info" % (lib_name,),
213+
stacklevel=2)
209214
break
210215
libraries.append((lib_name, build_info))

numpy/distutils/cpuinfo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ def __init__(self):
117117
fo = open('/proc/cpuinfo')
118118
except EnvironmentError:
119119
e = get_exception()
120-
warnings.warn(str(e), UserWarning)
120+
warnings.warn(str(e), UserWarning, stacklevel=2)
121121
else:
122122
for line in fo:
123123
name_value = [s.strip() for s in line.split(':', 1)]

numpy/distutils/extension.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def __init__ (
6363
if isinstance(self.swig_opts, basestring):
6464
import warnings
6565
msg = "swig_opts is specified as a string instead of a list"
66-
warnings.warn(msg, SyntaxWarning)
66+
warnings.warn(msg, SyntaxWarning, stacklevel=2)
6767
self.swig_opts = self.swig_opts.split()
6868

6969
# Python 2.3 distutils new features

numpy/distutils/fcompiler/gnu.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def get_flags_linker_so(self):
137137
os.environ['MACOSX_DEPLOYMENT_TARGET'] = target
138138
if target == '10.3':
139139
s = 'Env. variable MACOSX_DEPLOYMENT_TARGET set to 10.3'
140-
warnings.warn(s)
140+
warnings.warn(s, stacklevel=2)
141141

142142
opt.extend(['-undefined', 'dynamic_lookup', '-bundle'])
143143
else:

numpy/distutils/misc_util.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2206,7 +2206,7 @@ def default_config_dict(name = None, parent_name = None, local_path=None):
22062206
'deprecated default_config_dict(%r,%r,%r)'
22072207
% (name, parent_name, local_path,
22082208
name, parent_name, local_path,
2209-
))
2209+
), stacklevel=2)
22102210
c = Configuration(name, parent_name, local_path)
22112211
return c.todict()
22122212

numpy/distutils/system_info.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -573,7 +573,7 @@ def get_info(self, notfound_action=0):
573573
if notfound_action:
574574
if not self.has_info():
575575
if notfound_action == 1:
576-
warnings.warn(self.notfounderror.__doc__)
576+
warnings.warn(self.notfounderror.__doc__, stacklevel=2)
577577
elif notfound_action == 2:
578578
raise self.notfounderror(self.notfounderror.__doc__)
579579
else:
@@ -642,7 +642,7 @@ def get_paths(self, section, key):
642642
ret = []
643643
for d in dirs:
644644
if len(d) > 0 and not os.path.isdir(d):
645-
warnings.warn('Specified path %s is invalid.' % d)
645+
warnings.warn('Specified path %s is invalid.' % d, stacklevel=2)
646646
continue
647647

648648
if d not in ret:
@@ -1104,7 +1104,7 @@ def calc_info(self):
11041104
Could not find lapack library within the ATLAS installation.
11051105
*********************************************************************
11061106
"""
1107-
warnings.warn(message)
1107+
warnings.warn(message, stacklevel=2)
11081108
self.set_info(**info)
11091109
return
11101110

@@ -1135,7 +1135,7 @@ def calc_info(self):
11351135
numpy/INSTALL.txt.
11361136
*********************************************************************
11371137
""" % (lapack_lib, sz / 1024)
1138-
warnings.warn(message)
1138+
warnings.warn(message, stacklevel=2)
11391139
else:
11401140
info['language'] = 'f77'
11411141

@@ -1420,7 +1420,7 @@ def get_atlas_version(**config):
14201420
when building extension libraries that use ATLAS.
14211421
Make sure that -lgfortran is used for C++ extensions.
14221422
*****************************************************
1423-
""")
1423+
""", stacklevel=2)
14241424
dict_append(info, language='f90',
14251425
define_macros=[('ATLAS_REQUIRES_GFORTRAN', None)])
14261426
except Exception: # failed to get version from file -- maybe on Windows
@@ -1531,7 +1531,7 @@ def calc_info(self):
15311531
info = atlas_info
15321532

15331533
else:
1534-
warnings.warn(AtlasNotFoundError.__doc__)
1534+
warnings.warn(AtlasNotFoundError.__doc__, stacklevel=2)
15351535
need_blas = 1
15361536
need_lapack = 1
15371537
dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)])
@@ -1542,10 +1542,10 @@ def calc_info(self):
15421542
if lapack_info:
15431543
dict_append(info, **lapack_info)
15441544
else:
1545-
warnings.warn(LapackNotFoundError.__doc__)
1545+
warnings.warn(LapackNotFoundError.__doc__, stacklevel=2)
15461546
lapack_src_info = get_info('lapack_src')
15471547
if not lapack_src_info:
1548-
warnings.warn(LapackSrcNotFoundError.__doc__)
1548+
warnings.warn(LapackSrcNotFoundError.__doc__, stacklevel=2)
15491549
return
15501550
dict_append(info, libraries=[('flapack_src', lapack_src_info)])
15511551

@@ -1554,10 +1554,10 @@ def calc_info(self):
15541554
if blas_info:
15551555
dict_append(info, **blas_info)
15561556
else:
1557-
warnings.warn(BlasNotFoundError.__doc__)
1557+
warnings.warn(BlasNotFoundError.__doc__, stacklevel=2)
15581558
blas_src_info = get_info('blas_src')
15591559
if not blas_src_info:
1560-
warnings.warn(BlasSrcNotFoundError.__doc__)
1560+
warnings.warn(BlasSrcNotFoundError.__doc__, stacklevel=2)
15611561
return
15621562
dict_append(info, libraries=[('fblas_src', blas_src_info)])
15631563

@@ -1634,7 +1634,7 @@ def calc_info(self):
16341634
if atlas_info:
16351635
info = atlas_info
16361636
else:
1637-
warnings.warn(AtlasNotFoundError.__doc__)
1637+
warnings.warn(AtlasNotFoundError.__doc__, stacklevel=2)
16381638
need_blas = 1
16391639
dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)])
16401640

@@ -1643,10 +1643,10 @@ def calc_info(self):
16431643
if blas_info:
16441644
dict_append(info, **blas_info)
16451645
else:
1646-
warnings.warn(BlasNotFoundError.__doc__)
1646+
warnings.warn(BlasNotFoundError.__doc__, stacklevel=2)
16471647
blas_src_info = get_info('blas_src')
16481648
if not blas_src_info:
1649-
warnings.warn(BlasSrcNotFoundError.__doc__)
1649+
warnings.warn(BlasSrcNotFoundError.__doc__, stacklevel=2)
16501650
return
16511651
dict_append(info, libraries=[('fblas_src', blas_src_info)])
16521652

numpy/lib/format.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -556,7 +556,7 @@ def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None):
556556
# this warning can be removed when 1.9 has aged enough
557557
if version != (2, 0) and used_ver == (2, 0):
558558
warnings.warn("Stored array in format 2.0. It can only be"
559-
"read by NumPy >= 1.9", UserWarning)
559+
"read by NumPy >= 1.9", UserWarning, stacklevel=2)
560560

561561
if array.itemsize == 0:
562562
buffersize = 0
@@ -759,7 +759,7 @@ def open_memmap(filename, mode='r+', dtype=None, shape=None,
759759
# this warning can be removed when 1.9 has aged enough
760760
if version != (2, 0) and used_ver == (2, 0):
761761
warnings.warn("Stored array in format 2.0. It can only be"
762-
"read by NumPy >= 1.9", UserWarning)
762+
"read by NumPy >= 1.9", UserWarning, stacklevel=2)
763763
offset = fp.tell()
764764
finally:
765765
fp.close()

0 commit comments

Comments
 (0)
0