Thanks to visit codestin.com
Credit goes to github.com

Skip to content

ENH,TST: Bump stacklevel and add tests for warnings #7148

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Sep 2, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ matrix:
- python: 2.7
env: USE_WHEEL=1
- python: 3.5
env: USE_WHEEL=1
env: USE_WHEEL=1 RUN_FULL_TESTS=1
- python: 3.5
env: USE_SDIST=1
- python: 2.7
Expand Down
13 changes: 13 additions & 0 deletions doc/release/1.12.0-notes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,19 @@ is regular quicksort but changing to a heapsort when not enough progress is
made. This retains the good quicksort performance while changing the worst case
runtime from ``O(N^2)`` to ``O(N*log(N))``.

stacklevel of warnings increased
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The stacklevel for python based warnings was increased so that most warnings
will report the offending line of the user code instead of the line the
warning itself is given. Passing of stacklevel is now tested to ensure that
new warnings will recieve the ``stacklevel`` argument.

This causes warnings with the "default" or "module" filter to be shown once
for every offending user code line or user module instead of only once. On
python versions before 3.4, this can cause warnings to appear that were falsly
ignored before, which may be surprising especially in test suits.


Deprecations
============

Expand Down
2 changes: 1 addition & 1 deletion numpy/_import_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def __call__(self,*packages, **options):
# 2014-10-29, 1.10
warnings.warn('pkgload and PackageLoader are obsolete '
'and will be removed in a future version of numpy',
DeprecationWarning)
DeprecationWarning, stacklevel=2)
frame = self.parent_frame
self.info_modules = {}
if options.get('force', False):
Expand Down
5 changes: 3 additions & 2 deletions numpy/core/_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def _mean(a, axis=None, dtype=None, out=None, keepdims=False):
rcount = _count_reduce_items(arr, axis)
# Make this warning show up first
if rcount == 0:
warnings.warn("Mean of empty slice.", RuntimeWarning)
warnings.warn("Mean of empty slice.", RuntimeWarning, stacklevel=2)

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

# Cast bool, unsigned int, and int to float64 by default
if dtype is None and issubclass(arr.dtype.type, (nt.integer, nt.bool_)):
Expand Down
2 changes: 1 addition & 1 deletion numpy/core/fromnumeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -2647,7 +2647,7 @@ def rank(a):
warnings.warn(
"`rank` is deprecated; use the `ndim` attribute or function instead. "
"To find the rank of a matrix see `numpy.linalg.matrix_rank`.",
VisibleDeprecationWarning)
VisibleDeprecationWarning, stacklevel=2)
try:
return a.ndim
except AttributeError:
Expand Down
10 changes: 6 additions & 4 deletions numpy/core/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -1181,7 +1181,8 @@ def alterdot():

"""
# 2014-08-13, 1.10
warnings.warn("alterdot no longer does anything.", DeprecationWarning)
warnings.warn("alterdot no longer does anything.",
DeprecationWarning, stacklevel=2)


def restoredot():
Expand All @@ -1205,7 +1206,8 @@ def restoredot():

"""
# 2014-08-13, 1.10
warnings.warn("restoredot no longer does anything.", DeprecationWarning)
warnings.warn("restoredot no longer does anything.",
DeprecationWarning, stacklevel=2)


def tensordot(a, b, axes=2):
Expand Down Expand Up @@ -2260,8 +2262,8 @@ def warn_if_insufficient(width, binwdith):
if width is not None and width < binwidth:
warnings.warn(
"Insufficient bit width provided. This behavior "
"will raise an error in the future.", DeprecationWarning
)
"will raise an error in the future.", DeprecationWarning,
stacklevel=3)

if num == 0:
return '0' * (width or 1)
Expand Down
2 changes: 1 addition & 1 deletion numpy/core/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def check_complex(config, mathlibs):

try:
if os.uname()[0] == "Interix":
warnings.warn("Disabling broken complex support. See #1365")
warnings.warn("Disabling broken complex support. See #1365", stacklevel=2)
return priv, pub
except:
# os.uname not available on all platforms. blanket except ugly but safe
Expand Down
2 changes: 1 addition & 1 deletion numpy/core/setup_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def check_api_version(apiversion, codegen_dir):
)
warnings.warn(msg % (apiversion, curapi_hash, apiversion, api_hash,
__file__),
MismatchCAPIWarning)
MismatchCAPIWarning, stacklevel=2)
# Mandatory functions: if not found, fail the build
MANDATORY_FUNCS = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "fabs",
"floor", "ceil", "sqrt", "log10", "log", "exp", "asin",
Expand Down
2 changes: 1 addition & 1 deletion numpy/core/tests/test_deprecations.py
Original file line number Diff line number Diff line change
Expand Up @@ -641,7 +641,7 @@ def test_assert_deprecated(self):
lambda: None)

def foo():
warnings.warn("foo", category=DeprecationWarning)
warnings.warn("foo", category=DeprecationWarning, stacklevel=2)

test_case_instance.assert_deprecated(foo)
test_case_instance.tearDown()
Expand Down
2 changes: 1 addition & 1 deletion numpy/ctypeslib.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def load_library(libname, loader_path):
if ctypes.__version__ < '1.0.1':
import warnings
warnings.warn("All features of ctypes interface may not work " \
"with ctypes < 1.0.1")
"with ctypes < 1.0.1", stacklevel=2)

ext = os.path.splitext(libname)[1]
if not ext:
Expand Down
2 changes: 1 addition & 1 deletion numpy/distutils/command/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,7 @@ def get_output(self, body, headers=None, include_dirs=None,
"use it anymore, and avoid configuration checks \n" \
"involving running executable on the target machine.\n" \
"+++++++++++++++++++++++++++++++++++++++++++++++++\n",
DeprecationWarning)
DeprecationWarning, stacklevel=2)
from distutils.ccompiler import CompileError, LinkError
self._check_compiler()
exitcode, output = 255, ''
Expand Down
2 changes: 1 addition & 1 deletion numpy/distutils/command/egg_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def run(self):
import warnings
warnings.warn("`build_src` is being run, this may lead to missing "
"files in your sdist! See numpy issue gh-7127 for "
"details", UserWarning)
"details", UserWarning, stacklevel=2)

# We need to ensure that build_src has been executed in order to give
# setuptools' egg_info command real filenames instead of functions which
Expand Down
15 changes: 10 additions & 5 deletions numpy/distutils/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,18 +176,21 @@ def _check_append_library(libraries, item):
if item[1] is libitem[1]:
return
warnings.warn("[0] libraries list contains %r with"
" different build_info" % (item[0],))
" different build_info" % (item[0],),
stacklevel=2)
break
else:
if item==libitem[0]:
warnings.warn("[1] libraries list contains %r with"
" no build_info" % (item[0],))
" no build_info" % (item[0],),
stacklevel=2)
break
else:
if is_sequence(item):
if item[0]==libitem:
warnings.warn("[2] libraries list contains %r with"
" no build_info" % (item[0],))
" no build_info" % (item[0],),
stacklevel=2)
break
else:
if item==libitem:
Expand All @@ -201,10 +204,12 @@ def _check_append_ext_library(libraries, lib_name, build_info):
if item[1] is build_info:
return
warnings.warn("[3] libraries list contains %r with"
" different build_info" % (lib_name,))
" different build_info" % (lib_name,),
stacklevel=2)
break
elif item==lib_name:
warnings.warn("[4] libraries list contains %r with"
" no build_info" % (lib_name,))
" no build_info" % (lib_name,),
stacklevel=2)
break
libraries.append((lib_name, build_info))
2 changes: 1 addition & 1 deletion numpy/distutils/cpuinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def __init__(self):
fo = open('/proc/cpuinfo')
except EnvironmentError:
e = get_exception()
warnings.warn(str(e), UserWarning)
warnings.warn(str(e), UserWarning, stacklevel=2)
else:
for line in fo:
name_value = [s.strip() for s in line.split(':', 1)]
Expand Down
2 changes: 1 addition & 1 deletion numpy/distutils/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def __init__ (
if isinstance(self.swig_opts, basestring):
import warnings
msg = "swig_opts is specified as a string instead of a list"
warnings.warn(msg, SyntaxWarning)
warnings.warn(msg, SyntaxWarning, stacklevel=2)
self.swig_opts = self.swig_opts.split()

# Python 2.3 distutils new features
Expand Down
2 changes: 1 addition & 1 deletion numpy/distutils/fcompiler/gnu.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ def get_flags_linker_so(self):
os.environ['MACOSX_DEPLOYMENT_TARGET'] = target
if target == '10.3':
s = 'Env. variable MACOSX_DEPLOYMENT_TARGET set to 10.3'
warnings.warn(s)
warnings.warn(s, stacklevel=2)

opt.extend(['-undefined', 'dynamic_lookup', '-bundle'])
else:
Expand Down
2 changes: 1 addition & 1 deletion numpy/distutils/misc_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2206,7 +2206,7 @@ def default_config_dict(name = None, parent_name = None, local_path=None):
'deprecated default_config_dict(%r,%r,%r)'
% (name, parent_name, local_path,
name, parent_name, local_path,
))
), stacklevel=2)
c = Configuration(name, parent_name, local_path)
return c.todict()

Expand Down
26 changes: 13 additions & 13 deletions numpy/distutils/system_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,7 @@ def get_info(self, notfound_action=0):
if notfound_action:
if not self.has_info():
if notfound_action == 1:
warnings.warn(self.notfounderror.__doc__)
warnings.warn(self.notfounderror.__doc__, stacklevel=2)
elif notfound_action == 2:
raise self.notfounderror(self.notfounderror.__doc__)
else:
Expand Down Expand Up @@ -642,7 +642,7 @@ def get_paths(self, section, key):
ret = []
for d in dirs:
if len(d) > 0 and not os.path.isdir(d):
warnings.warn('Specified path %s is invalid.' % d)
warnings.warn('Specified path %s is invalid.' % d, stacklevel=2)
continue

if d not in ret:
Expand Down Expand Up @@ -1104,7 +1104,7 @@ def calc_info(self):
Could not find lapack library within the ATLAS installation.
*********************************************************************
"""
warnings.warn(message)
warnings.warn(message, stacklevel=2)
self.set_info(**info)
return

Expand Down Expand Up @@ -1135,7 +1135,7 @@ def calc_info(self):
numpy/INSTALL.txt.
*********************************************************************
""" % (lapack_lib, sz / 1024)
warnings.warn(message)
warnings.warn(message, stacklevel=2)
else:
info['language'] = 'f77'

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

else:
warnings.warn(AtlasNotFoundError.__doc__)
warnings.warn(AtlasNotFoundError.__doc__, stacklevel=2)
need_blas = 1
need_lapack = 1
dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)])
Expand All @@ -1542,10 +1542,10 @@ def calc_info(self):
if lapack_info:
dict_append(info, **lapack_info)
else:
warnings.warn(LapackNotFoundError.__doc__)
warnings.warn(LapackNotFoundError.__doc__, stacklevel=2)
lapack_src_info = get_info('lapack_src')
if not lapack_src_info:
warnings.warn(LapackSrcNotFoundError.__doc__)
warnings.warn(LapackSrcNotFoundError.__doc__, stacklevel=2)
return
dict_append(info, libraries=[('flapack_src', lapack_src_info)])

Expand All @@ -1554,10 +1554,10 @@ def calc_info(self):
if blas_info:
dict_append(info, **blas_info)
else:
warnings.warn(BlasNotFoundError.__doc__)
warnings.warn(BlasNotFoundError.__doc__, stacklevel=2)
blas_src_info = get_info('blas_src')
if not blas_src_info:
warnings.warn(BlasSrcNotFoundError.__doc__)
warnings.warn(BlasSrcNotFoundError.__doc__, stacklevel=2)
return
dict_append(info, libraries=[('fblas_src', blas_src_info)])

Expand Down Expand Up @@ -1634,7 +1634,7 @@ def calc_info(self):
if atlas_info:
info = atlas_info
else:
warnings.warn(AtlasNotFoundError.__doc__)
warnings.warn(AtlasNotFoundError.__doc__, stacklevel=2)
need_blas = 1
dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)])

Expand All @@ -1643,10 +1643,10 @@ def calc_info(self):
if blas_info:
dict_append(info, **blas_info)
else:
warnings.warn(BlasNotFoundError.__doc__)
warnings.warn(BlasNotFoundError.__doc__, stacklevel=2)
blas_src_info = get_info('blas_src')
if not blas_src_info:
warnings.warn(BlasSrcNotFoundError.__doc__)
warnings.warn(BlasSrcNotFoundError.__doc__, stacklevel=2)
return
dict_append(info, libraries=[('fblas_src', blas_src_info)])

Expand Down
4 changes: 2 additions & 2 deletions numpy/lib/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -556,7 +556,7 @@ def write_array(fp, array, version=None, allow_pickle=True, pickle_kwargs=None):
# this warning can be removed when 1.9 has aged enough
if version != (2, 0) and used_ver == (2, 0):
warnings.warn("Stored array in format 2.0. It can only be"
"read by NumPy >= 1.9", UserWarning)
"read by NumPy >= 1.9", UserWarning, stacklevel=2)

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