summaryrefslogtreecommitdiff
path: root/numpy/lib/utils.py
diff options
context:
space:
mode:
Diffstat (limited to 'numpy/lib/utils.py')
-rw-r--r--numpy/lib/utils.py96
1 files changed, 63 insertions, 33 deletions
diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py
index 97b93cace..6b112f37a 100644
--- a/numpy/lib/utils.py
+++ b/numpy/lib/utils.py
@@ -7,7 +7,9 @@ import re
import warnings
from numpy.core.numerictypes import issubclass_, issubsctype, issubdtype
+from numpy.core.overrides import set_module
from numpy.core import ndarray, ufunc, asarray
+import numpy as np
# getargspec and formatargspec were removed in Python 3.6
from numpy.compat import getargspec, formatargspec
@@ -79,7 +81,6 @@ class _Deprecate(object):
new_name = self.new_name
message = self.message
- import warnings
if old_name is None:
try:
old_name = func.__name__
@@ -149,10 +150,8 @@ def deprecate(*args, **kwargs):
Warning:
>>> olduint = np.deprecate(np.uint)
+ DeprecationWarning: `uint64` is deprecated! # may vary
>>> olduint(6)
- /usr/lib/python2.5/site-packages/numpy/lib/utils.py:114:
- DeprecationWarning: uint32 is deprecated
- warnings.warn(str1, DeprecationWarning, stacklevel=2)
6
"""
@@ -164,13 +163,6 @@ def deprecate(*args, **kwargs):
fn = args[0]
args = args[1:]
- # backward compatibility -- can be removed
- # after next release
- if 'newname' in kwargs:
- kwargs['new_name'] = kwargs.pop('newname')
- if 'oldname' in kwargs:
- kwargs['old_name'] = kwargs.pop('oldname')
-
return _Deprecate(*args, **kwargs)(fn)
else:
return _Deprecate(*args, **kwargs)
@@ -207,8 +199,8 @@ def byte_bounds(a):
>>> low, high = np.byte_bounds(I)
>>> high - low == I.size*I.itemsize
True
- >>> I = np.eye(2, dtype='G'); I.dtype
- dtype('complex192')
+ >>> I = np.eye(2); I.dtype
+ dtype('float64')
>>> low, high = np.byte_bounds(I)
>>> high - low == I.size*I.itemsize
True
@@ -269,17 +261,17 @@ def who(vardict=None):
>>> np.who()
Name Shape Bytes Type
===========================================================
- a 10 40 int32
+ a 10 80 int64
b 20 160 float64
- Upper bound on total bytes = 200
+ Upper bound on total bytes = 240
>>> d = {'x': np.arange(2.0), 'y': np.arange(3.0), 'txt': 'Some str',
... 'idx':5}
>>> np.who(d)
Name Shape Bytes Type
===========================================================
- y 3 24 float64
x 2 16 float64
+ y 3 24 float64
Upper bound on total bytes = 40
"""
@@ -338,7 +330,7 @@ def who(vardict=None):
#-----------------------------------------------------------------------------
-# NOTE: pydoc defines a help function which works simliarly to this
+# NOTE: pydoc defines a help function which works similarly to this
# except it uses a pager to take over the screen.
# combine name and arguments and split to multiple lines of width
@@ -439,6 +431,7 @@ def _info(obj, output=sys.stdout):
print("type: %s" % obj.dtype, file=output)
+@set_module('numpy')
def info(object=None, maxwidth=76, output=sys.stdout, toplevel='numpy'):
"""
Get help information for a function, class, or module.
@@ -556,7 +549,7 @@ def info(object=None, maxwidth=76, output=sys.stdout, toplevel='numpy'):
if len(arglist) > 1:
arglist[1] = "("+arglist[1]
arguments = ", ".join(arglist[1:])
- except:
+ except Exception:
pass
if len(name+arguments) > maxwidth:
@@ -644,6 +637,7 @@ def info(object=None, maxwidth=76, output=sys.stdout, toplevel='numpy'):
print(inspect.getdoc(object), file=output)
+@set_module('numpy')
def source(object, output=sys.stdout):
"""
Print or write to a file the source code for a NumPy object.
@@ -688,7 +682,7 @@ def source(object, output=sys.stdout):
try:
print("In file: %s\n" % inspect.getsourcefile(object), file=output)
print(inspect.getsource(object), file=output)
- except:
+ except Exception:
print("Not available for this object.", file=output)
@@ -701,12 +695,14 @@ _lookfor_caches = {}
# signature
_function_signature_re = re.compile(r"[a-z0-9_]+\(.*[,=].*\)", re.I)
+
+@set_module('numpy')
def lookfor(what, module=None, import_modules=True, regenerate=False,
output=None):
"""
Do a keyword search on docstrings.
- A list of of objects that matched the search is displayed,
+ A list of objects that matched the search is displayed,
sorted by relevance. All given keywords need to be found in the
docstring for it to be returned as a result, but the order does
not matter.
@@ -735,7 +731,7 @@ def lookfor(what, module=None, import_modules=True, regenerate=False,
Examples
--------
- >>> np.lookfor('binary representation')
+ >>> np.lookfor('binary representation') # doctest: +SKIP
Search results for 'binary representation'
------------------------------------------
numpy.binary_repr
@@ -917,13 +913,6 @@ def _lookfor_generate_cache(module, import_modules, regenerate):
continue
try:
- # Catch SystemExit, too
- base_exc = BaseException
- except NameError:
- # Python 2.4 doesn't have BaseException
- base_exc = Exception
-
- try:
old_stdout = sys.stdout
old_stderr = sys.stderr
try:
@@ -933,7 +922,8 @@ def _lookfor_generate_cache(module, import_modules, regenerate):
finally:
sys.stdout = old_stdout
sys.stderr = old_stderr
- except base_exc:
+ # Catch SystemExit, too
+ except BaseException:
continue
for n, v in _getmembers(item):
@@ -987,12 +977,12 @@ def _getmembers(item):
#-----------------------------------------------------------------------------
# The following SafeEval class and company are adapted from Michael Spencer's
-# ASPN Python Cookbook recipe:
-# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469
+# ASPN Python Cookbook recipe: https://code.activestate.com/recipes/364469/
+#
# Accordingly it is mostly Copyright 2006 by Michael Spencer.
# The recipe, like most of the other ASPN Python Cookbook recipes was made
# available under the Python license.
-# http://www.python.org/license
+# https://en.wikipedia.org/wiki/Python_License
# It has been modified to:
# * handle unary -/+
@@ -1112,11 +1102,51 @@ def safe_eval(source):
>>> np.safe_eval('open("/home/user/.ssh/id_dsa").read()')
Traceback (most recent call last):
...
- SyntaxError: Unsupported source construct: compiler.ast.CallFunc
+ ValueError: malformed node or string: <_ast.Call object at 0x...>
"""
# Local import to speed up numpy's import time.
import ast
return ast.literal_eval(source)
+
+
+def _median_nancheck(data, result, axis, out):
+ """
+ Utility function to check median result from data for NaN values at the end
+ and return NaN in that case. Input result can also be a MaskedArray.
+
+ Parameters
+ ----------
+ data : array
+ Input data to median function
+ result : Array or MaskedArray
+ Result of median function
+ axis : {int, sequence of int, None}, optional
+ Axis or axes along which the median was computed.
+ out : ndarray, optional
+ Output array in which to place the result.
+ Returns
+ -------
+ median : scalar or ndarray
+ Median or NaN in axes which contained NaN in the input.
+ """
+ if data.size == 0:
+ return result
+ data = np.moveaxis(data, axis, -1)
+ n = np.isnan(data[..., -1])
+ # masked NaN values are ok
+ if np.ma.isMaskedArray(n):
+ n = n.filled(False)
+ if result.ndim == 0:
+ if n == True:
+ if out is not None:
+ out[...] = data.dtype.type(np.nan)
+ result = out
+ else:
+ result = data.dtype.type(np.nan)
+ elif np.count_nonzero(n.ravel()) > 0:
+ result[n] = np.nan
+ return result
+
#-----------------------------------------------------------------------------