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

Skip to content

ENH: set correct __module__ for objects in numpy's public API #12382

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 6 commits into from
Nov 15, 2018
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
11 changes: 8 additions & 3 deletions numpy/_globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ def foo(arg=np._NoValue):
"""
from __future__ import division, absolute_import, print_function


__ALL__ = [
'ModuleDeprecationWarning', 'VisibleDeprecationWarning', '_NoValue'
]
Expand All @@ -39,7 +38,9 @@ class ModuleDeprecationWarning(DeprecationWarning):
nose tester will let pass without making tests fail.

"""
pass


ModuleDeprecationWarning.__module__ = 'numpy'


class VisibleDeprecationWarning(UserWarning):
Expand All @@ -50,7 +51,10 @@ class VisibleDeprecationWarning(UserWarning):
the usage is most likely a user bug.

"""
pass


VisibleDeprecationWarning.__module__ = 'numpy'


class _NoValueType(object):
"""Special keyword value.
Expand All @@ -73,4 +77,5 @@ def __reduce__(self):
def __repr__(self):
return "<no value>"


_NoValue = _NoValueType()
178 changes: 0 additions & 178 deletions numpy/core/_add_newdocs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4552,184 +4552,6 @@ def luf(lamdaexpr, *args, **kwargs):
#
##############################################################################

add_newdoc('numpy.core.multiarray', 'bincount',
"""
bincount(x, weights=None, minlength=0)

Count number of occurrences of each value in array of non-negative ints.

The number of bins (of size 1) is one larger than the largest value in
`x`. If `minlength` is specified, there will be at least this number
of bins in the output array (though it will be longer if necessary,
depending on the contents of `x`).
Each bin gives the number of occurrences of its index value in `x`.
If `weights` is specified the input array is weighted by it, i.e. if a
value ``n`` is found at position ``i``, ``out[n] += weight[i]`` instead
of ``out[n] += 1``.

Parameters
----------
x : array_like, 1 dimension, nonnegative ints
Input array.
weights : array_like, optional
Weights, array of the same shape as `x`.
minlength : int, optional
A minimum number of bins for the output array.

.. versionadded:: 1.6.0

Returns
-------
out : ndarray of ints
The result of binning the input array.
The length of `out` is equal to ``np.amax(x)+1``.

Raises
------
ValueError
If the input is not 1-dimensional, or contains elements with negative
values, or if `minlength` is negative.
TypeError
If the type of the input is float or complex.

See Also
--------
histogram, digitize, unique

Examples
--------
>>> np.bincount(np.arange(5))
array([1, 1, 1, 1, 1])
>>> np.bincount(np.array([0, 1, 1, 3, 2, 1, 7]))
array([1, 3, 1, 1, 0, 0, 0, 1])

>>> x = np.array([0, 1, 1, 3, 2, 1, 7, 23])
>>> np.bincount(x).size == np.amax(x)+1
True

The input array needs to be of integer dtype, otherwise a
TypeError is raised:

>>> np.bincount(np.arange(5, dtype=float))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: array cannot be safely cast to required type

A possible use of ``bincount`` is to perform sums over
variable-size chunks of an array, using the ``weights`` keyword.

>>> w = np.array([0.3, 0.5, 0.2, 0.7, 1., -0.6]) # weights
>>> x = np.array([0, 1, 1, 2, 2, 2])
>>> np.bincount(x, weights=w)
array([ 0.3, 0.7, 1.1])

""")

add_newdoc('numpy.core.multiarray', 'ravel_multi_index',
"""
ravel_multi_index(multi_index, dims, mode='raise', order='C')

Converts a tuple of index arrays into an array of flat
indices, applying boundary modes to the multi-index.

Parameters
----------
multi_index : tuple of array_like
A tuple of integer arrays, one array for each dimension.
dims : tuple of ints
The shape of array into which the indices from ``multi_index`` apply.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices are handled. Can specify
either one mode or a tuple of modes, one mode per index.

* 'raise' -- raise an error (default)
* 'wrap' -- wrap around
* 'clip' -- clip to the range

In 'clip' mode, a negative index which would normally
wrap will clip to 0 instead.
order : {'C', 'F'}, optional
Determines whether the multi-index should be viewed as
indexing in row-major (C-style) or column-major
(Fortran-style) order.

Returns
-------
raveled_indices : ndarray
An array of indices into the flattened version of an array
of dimensions ``dims``.

See Also
--------
unravel_index

Notes
-----
.. versionadded:: 1.6.0

Examples
--------
>>> arr = np.array([[3,6,6],[4,5,1]])
>>> np.ravel_multi_index(arr, (7,6))
array([22, 41, 37])
>>> np.ravel_multi_index(arr, (7,6), order='F')
array([31, 41, 13])
>>> np.ravel_multi_index(arr, (4,6), mode='clip')
array([22, 23, 19])
>>> np.ravel_multi_index(arr, (4,4), mode=('clip','wrap'))
array([12, 13, 13])

>>> np.ravel_multi_index((3,1,4,1), (6,7,8,9))
1621
""")

add_newdoc('numpy.core.multiarray', 'unravel_index',
"""
unravel_index(indices, shape, order='C')

Converts a flat index or array of flat indices into a tuple
of coordinate arrays.

Parameters
----------
indices : array_like
An integer array whose elements are indices into the flattened
version of an array of dimensions ``shape``. Before version 1.6.0,
this function accepted just one index value.
shape : tuple of ints
The shape of the array to use for unraveling ``indices``.

.. versionchanged:: 1.16.0
Renamed from ``dims`` to ``shape``.

order : {'C', 'F'}, optional
Determines whether the indices should be viewed as indexing in
row-major (C-style) or column-major (Fortran-style) order.

.. versionadded:: 1.6.0

Returns
-------
unraveled_coords : tuple of ndarray
Each array in the tuple has the same shape as the ``indices``
array.

See Also
--------
ravel_multi_index

Examples
--------
>>> np.unravel_index([22, 41, 37], (7,6))
(array([3, 6, 6]), array([4, 5, 1]))
>>> np.unravel_index([31, 41, 13], (7,6), order='F')
(array([3, 6, 6]), array([4, 5, 1]))

>>> np.unravel_index(1621, (6,7,8,9))
(3, 1, 4, 1)

""")

add_newdoc('numpy.core.multiarray', 'add_docstring',
"""
add_docstring(obj, docstring)
Expand Down
3 changes: 3 additions & 0 deletions numpy/core/_internal.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import sys

from numpy.compat import unicode
from numpy.core.overrides import set_module
from .multiarray import dtype, array, ndarray
try:
import ctypes
Expand Down Expand Up @@ -718,9 +719,11 @@ def _lcm(a, b):
return a // _gcd(a, b) * b

# Exception used in shares_memory()
@set_module('numpy')
class TooHardError(RuntimeError):
pass

@set_module('numpy')
class AxisError(ValueError, IndexError):
""" Axis supplied was invalid. """
def __init__(self, axis, ndim=None, msg_prefix=None):
Expand Down
10 changes: 9 additions & 1 deletion numpy/core/arrayprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
from .numeric import concatenate, asarray, errstate
from .numerictypes import (longlong, intc, int_, float_, complex_, bool_,
flexible)
from .overrides import array_function_dispatch
from .overrides import array_function_dispatch, set_module
import warnings
import contextlib

Expand Down Expand Up @@ -89,6 +89,8 @@ def _make_options_dict(precision=None, threshold=None, edgeitems=None,

return options


@set_module('numpy')
def set_printoptions(precision=None, threshold=None, edgeitems=None,
linewidth=None, suppress=None, nanstr=None, infstr=None,
formatter=None, sign=None, floatmode=None, **kwarg):
Expand Down Expand Up @@ -250,6 +252,7 @@ def set_printoptions(precision=None, threshold=None, edgeitems=None,
set_legacy_print_mode(0)


@set_module('numpy')
def get_printoptions():
"""
Return the current print options.
Expand Down Expand Up @@ -279,6 +282,7 @@ def get_printoptions():
return _format_options.copy()


@set_module('numpy')
@contextlib.contextmanager
def printoptions(*args, **kwargs):
"""Context manager for setting print options.
Expand Down Expand Up @@ -976,6 +980,8 @@ def __init__(self, *args, **kwargs):
DeprecationWarning, stacklevel=2)
super(LongFloatFormat, self).__init__(*args, **kwargs)


@set_module('numpy')
def format_float_scientific(x, precision=None, unique=True, trim='k',
sign=False, pad_left=None, exp_digits=None):
"""
Expand Down Expand Up @@ -1043,6 +1049,8 @@ def format_float_scientific(x, precision=None, unique=True, trim='k',
trim=trim, sign=sign, pad_left=pad_left,
exp_digits=exp_digits)


@set_module('numpy')
def format_float_positional(x, precision=None, unique=True,
fractional=True, trim='k', sign=False,
pad_left=None, pad_right=None):
Expand Down
2 changes: 2 additions & 0 deletions numpy/core/defchararray.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from .numeric import ndarray, compare_chararrays
from .numeric import array as narray
from numpy.core.multiarray import _vec_string
from numpy.core.overrides import set_module
from numpy.core import overrides
from numpy.compat import asbytes, long
import numpy
Expand Down Expand Up @@ -1820,6 +1821,7 @@ def isdecimal(a):
return _vec_string(a, bool_, 'isdecimal')


@set_module('numpy')
class chararray(ndarray):
"""
chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0,
Expand Down
4 changes: 4 additions & 0 deletions numpy/core/function_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from .numeric import (result_type, NaN, shares_memory, MAY_SHARE_BOUNDS,
TooHardError,asanyarray)
from numpy.core.multiarray import add_docstring
from numpy.core.overrides import set_module

__all__ = ['logspace', 'linspace', 'geomspace']

Expand All @@ -23,6 +24,7 @@ def _index_deprecate(i, stacklevel=2):
return i


@set_module('numpy')
def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
"""
Return evenly spaced numbers over a specified interval.
Expand Down Expand Up @@ -154,6 +156,7 @@ def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
return y.astype(dtype, copy=False)


@set_module('numpy')
def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None):
"""
Return numbers spaced evenly on a log scale.
Expand Down Expand Up @@ -238,6 +241,7 @@ def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None):
return _nx.power(base, y).astype(dtype)


@set_module('numpy')
def geomspace(start, stop, num=50, endpoint=True, dtype=None):
"""
Return numbers spaced evenly on a log scale (a geometric progression).
Expand Down
3 changes: 3 additions & 0 deletions numpy/core/getlimits.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import warnings

from .machar import MachAr
from .overrides import set_module
from . import numeric
from . import numerictypes as ntypes
from .numeric import array, inf
Expand Down Expand Up @@ -289,6 +290,7 @@ def _discovered_machar(ftype):
params['title'])


@set_module('numpy')
class finfo(object):
"""
finfo(dtype)
Expand Down Expand Up @@ -439,6 +441,7 @@ def __repr__(self):
" max=%(_str_max)s, dtype=%(dtype)s)") % d)


@set_module('numpy')
class iinfo(object):
"""
iinfo(type)
Expand Down
2 changes: 2 additions & 0 deletions numpy/core/machar.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@

from numpy.core.fromnumeric import any
from numpy.core.numeric import errstate
from numpy.core.overrides import set_module

# Need to speed this up...especially for longfloat

@set_module('numpy')
class MachAr(object):
"""
Diagnosing machine parameters.
Expand Down
3 changes: 3 additions & 0 deletions numpy/core/memmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from numpy.compat import (
long, basestring, os_fspath, contextlib_nullcontext, is_pathlib_path
)
from numpy.core.overrides import set_module

__all__ = ['memmap']

Expand All @@ -19,6 +20,8 @@
"write":"w+"
}


@set_module('numpy')
class memmap(ndarray):
"""Create a memory-map to an array stored in a *binary* file on disk.

Expand Down
Loading