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

Skip to content

MAINT: Python API cleanup nitpicks #24959

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 1 commit into from
Oct 20, 2023
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
101 changes: 47 additions & 54 deletions numpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,55 +120,50 @@

from . import _core
from ._core import (
_no_nep50_warning, memmap, iinfo, finfo, recarray,
False_, ScalarType, True_, abs, absolute, add, all, allclose, alltrue,
False_, ScalarType, True_, _get_promotion_state, _no_nep50_warning,
_set_promotion_state, abs, absolute, add, all, allclose, alltrue,
amax, amin, any, arange, arccos, arccosh, arcsin, arcsinh, arctan,
arctan2, arctanh, argmax, argmin, argpartition, argsort, argwhere,
around, array, array2string, array_equal, array_equiv, array_repr,
array_str, asanyarray, asarray, ascontiguousarray, asfortranarray,
atleast_1d, atleast_2d, atleast_3d, base_repr, binary_repr,
bitwise_and, bitwise_count, bitwise_not, bitwise_or, bitwise_xor, block,
bool_, broadcast, busday_count, busday_offset, busdaycalendar, byte, bytes_,
can_cast, cbrt, cdouble, ceil, character, choose, clip, clongdouble,
complexfloating, compress, concatenate, conj, conjugate, convolve,
copysign, copyto, correlate, cos, cosh, count_nonzero, cross, csingle,
cumprod, cumproduct, cumsum, datetime64, datetime_as_string,
datetime_data, deg2rad, degrees, diagonal, divide, divmod, dot,
double, dtype, e, einsum, einsum_path, empty, empty_like, equal,
errstate, euler_gamma, exp, exp2, expm1, fabs,
flatiter, flatnonzero, flexible, sctypeDict,
float_power, floating, floor, floor_divide, fmax, fmin, fmod,
format_float_positional, format_float_scientific,
frexp, from_dlpack, frombuffer, fromfile, fromfunction, fromiter,
frompyfunc, fromstring, full, full_like, gcd, generic, geomspace,
get_printoptions, getbufsize, geterr, geterrcall, greater,
greater_equal, half, heaviside, hstack, hypot, identity, iinfo,
indices, inexact, inf, inner, int_,
intc, integer, invert, is_busday, isclose, isfinite, isfortran,
isinf, isnan, isnat, isscalar, issubdtype, lcm, ldexp,
left_shift, less, less_equal, lexsort, linspace, little_endian, log,
log10, log1p, log2, logaddexp, logaddexp2, logical_and, logical_not,
logical_or, logical_xor, logspace, longdouble,
longlong, matmul, max, maximum,
may_share_memory, mean, min, min_scalar_type, minimum, mod,
modf, moveaxis, multiply, nan, ndarray, ndim, nditer,
negative, nested_iters, newaxis, nextafter, nonzero, not_equal,
number, object_, ones, ones_like, outer, partition,
pi, positive, power, printoptions, prod, product, promote_types,
ptp, put, putmask, rad2deg, radians, ravel, reciprocal,
record, remainder, repeat, require, reshape, resize, result_type,
right_shift, rint, roll, rollaxis, round,
searchsorted, set_printoptions, long, ulong,
setbufsize, seterr, seterrcall, shape,
shares_memory, short, sign, signbit, signedinteger, sin, single,
sinh, size, sometrue, sort, spacing, sqrt, square,
squeeze, stack, std, str_, subtract, sum, swapaxes, take,
tan, tanh, tensordot, timedelta64, trace, transpose,
true_divide, trunc, typecodes, ubyte, ufunc, uint, uintc, ulonglong,
unsignedinteger, ushort, var, vdot, void, vstack, where,
zeros, zeros_like, _get_promotion_state, _set_promotion_state,
int8, int16, int32, int64, intp, uint8, uint16, uint32, uint64, uintp,
float16, float32, float64, complex64, complex128
atleast_1d, atleast_2d, atleast_3d, base_repr, binary_repr,
bitwise_and, bitwise_count, bitwise_not, bitwise_or, bitwise_xor,
block, bool_, broadcast, busday_count, busday_offset, busdaycalendar,
byte, bytes_, can_cast, cbrt, cdouble, ceil, character, choose, clip,
clongdouble, complex128, complex64, complexfloating, compress,
concatenate, conj, conjugate, convolve, copysign, copyto, correlate,
cos, cosh, count_nonzero, cross, csingle, cumprod, cumproduct, cumsum,
datetime64, datetime_as_string, datetime_data, deg2rad, degrees,
diagonal, divide, divmod, dot, double, dtype, e, einsum, einsum_path,
empty, empty_like, equal, errstate, euler_gamma, exp, exp2, expm1,
fabs, finfo, flatiter, flatnonzero, flexible, float16, float32,
float64, float_power, floating, floor, floor_divide, fmax, fmin, fmod,
format_float_positional, format_float_scientific, frexp, from_dlpack,
frombuffer, fromfile, fromfunction, fromiter, frompyfunc, fromstring,
full, full_like, gcd, generic, geomspace, get_printoptions,
getbufsize, geterr, geterrcall, greater, greater_equal, half,
heaviside, hstack, hypot, identity, iinfo, iinfo, indices, inexact,
inf, inner, int16, int32, int64, int8, int_, intc, integer, intp,
invert, is_busday, isclose, isfinite, isfortran, isinf, isnan, isnat,
isscalar, issubdtype, lcm, ldexp, left_shift, less, less_equal,
lexsort, linspace, little_endian, log, log10, log1p, log2, logaddexp,
logaddexp2, logical_and, logical_not, logical_or, logical_xor,
logspace, long, longdouble, longlong, matmul, max, maximum,
may_share_memory, mean, memmap, min, min_scalar_type, minimum, mod,
modf, moveaxis, multiply, nan, ndarray, ndim, nditer, negative,
nested_iters, newaxis, nextafter, nonzero, not_equal, number, object_,
ones, ones_like, outer, partition, pi, positive, power, printoptions,
prod, product, promote_types, ptp, put, putmask, rad2deg, radians,
ravel, recarray, reciprocal, record, remainder, repeat, require,
reshape, resize, result_type, right_shift, rint, roll, rollaxis,
round, sctypeDict, searchsorted, set_printoptions, setbufsize, seterr,
seterrcall, shape, shares_memory, short, sign, signbit, signedinteger,
sin, single, sinh, size, sometrue, sort, spacing, sqrt, square,
squeeze, stack, std, str_, subtract, sum, swapaxes, take, tan, tanh,
tensordot, timedelta64, trace, transpose, true_divide, trunc,
typecodes, ubyte, ufunc, uint, uint16, uint32, uint64, uint8, uintc,
uintp, ulong, ulonglong, unsignedinteger, ushort, var, vdot, void,
vstack, where, zeros, zeros_like
)

# NOTE: It's still under discussion whether these aliases
Expand All @@ -181,7 +176,7 @@
del ta

from . import lib
from .lib import emath
from .lib import scimath as emath
from .lib._histograms_impl import (
histogram, histogram_bin_edges, histogramdd
)
Expand Down Expand Up @@ -294,8 +289,10 @@
_core.getlimits._register_known_types()

__all__ = list(
__numpy_submodules__ | set(_core.__all__) | set(lib.__all__) |
set(_mat.__all__) | set(lib._histograms_impl.__all__) |
__numpy_submodules__ |
set(_core.__all__) |
set(_mat.__all__) |
set(lib._histograms_impl.__all__) |
set(lib._nanfunctions_impl.__all__) |
set(lib._function_base_impl.__all__) |
set(lib._twodim_base_impl.__all__) |
Expand All @@ -309,7 +306,7 @@
set(lib._polynomial_impl.__all__) |
set(lib._npyio_impl.__all__) |
set(lib._index_tricks_impl.__all__) |
{"show_config", "__version__"}
{"emath", "show_config", "__version__"}
)

# Filter out Cython harmless warnings
Expand Down Expand Up @@ -405,17 +402,13 @@ def __getattr__(attr):
"{!r}".format(__name__, attr))

def __dir__():
# TODO: move away from using `globals` to a statically defined
# list. With `globals`, when running in a testing context
# a bunch of random names fall into global scope, such as
# `conftest` or `distutils`.
public_symbols = (
globals().keys() | __numpy_submodules__
)
public_symbols -= {
"matrixlib", "matlib", "tests", "conftest", "version",
"compat", "distutils", "array_api"
}
}
return list(public_symbols)

# Pytest testing
Expand Down
2 changes: 1 addition & 1 deletion numpy/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ from numpy._core.shape_base import (
)

from numpy.lib import (
emath as emath,
scimath as emath,
)

from numpy.lib._arraypad_impl import (
Expand Down
44 changes: 28 additions & 16 deletions numpy/lib/__init__.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
"""
**Note:** almost all functions in the ``numpy.lib`` namespace
are also present in the main ``numpy`` namespace. Please use the
functions as ``np.<funcname>`` where possible.

``numpy.lib`` is mostly a space for implementing functions that don't
belong in core or in another NumPy submodule with a clear purpose
(e.g. ``random``, ``fft``, ``linalg``, ``ma``).

Most contains basic functions that are used by several submodules and are
useful to have in the main name-space.
``numpy.lib``'s private submodules contain basic functions that are used by
other public modules and are useful to have in the main name-space.

"""

# Public submodules
# Note: recfunctions and (maybe) format are public too, but not imported
from . import array_utils
from . import introspect
from . import mixins
from . import scimath as emath
from . import npyio
from . import scimath
from . import stride_tricks

# Private submodules
# load module names. See https://github.com/networkx/networkx/issues/5838
Expand All @@ -25,27 +25,28 @@
from . import _function_base_impl
from . import _stride_tricks_impl
from . import _shape_base_impl
from . import stride_tricks
from . import _twodim_base_impl
from . import _ufunclike_impl
from . import _histograms_impl
from . import _utils_impl
from . import _arraysetops_impl
from . import _polynomial_impl
from . import _npyio_impl
from . import npyio
from . import arrayterator
from . import introspect
from . import _arrayterator_impl
from . import _arraypad_impl
from . import array_utils
from . import _version

from .arrayterator import Arrayterator
# numpy.lib namespace members
from ._arrayterator_impl import Arrayterator
from ._version import NumpyVersion
from numpy._core._multiarray_umath import add_docstring, tracemalloc_domain
from numpy._core.function_base import add_newdoc

__all__ = ['emath']
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Searching on github I don't find any usages of np.lib.emath. Still, It's been here for a long time and we're still publicly exposing np.emath, so it would be nice to generate a nicer AttributeError with a migration in the __getattr__ for the module.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure! I added a proper error message for np.lib.emath.

__all__ = [
"Arrayterator", "add_docstring", "add_newdoc", "array_utils",
"introspect", "mixins", "NumpyVersion", "npyio", "scimath",
"stride_tricks", "tracemalloc_domain"
]

from numpy._pytesttester import PytestTester
test = PytestTester(__name__)
Expand All @@ -56,22 +57,33 @@ def __getattr__(attr):
import math
import warnings

if attr == 'math':
if attr == "math":
warnings.warn(
"`np.lib.math` is a deprecated alias for the standard library "
"`math` module (Deprecated Numpy 1.25). Replace usages of "
"`numpy.lib.math` with `math`", DeprecationWarning, stacklevel=2)
return math
elif attr == "emath":
raise AttributeError(
"numpy.lib.emath was an alias for emath module that was removed "
"in NumPy 2.0. Replace usages of numpy.lib.emath with "
"numpy.emath."
)
elif attr in (
"histograms", "type_check", "nanfunctions", "function_base",
"arraypad", "arraysetops", "ufunclike", "utils", "twodim_base",
"shape_base", "polynomial", "index_tricks",
):
raise AttributeError(
f"`np.lib.{attr}` is now private. If you are using a public "
f"numpy.lib.{attr} is now private. If you are using a public "
"function, it should be available in the main numpy namespace, "
"otherwise check the NumPy 2.0 migration guide."
)
elif attr == "arrayterator":
raise AttributeError(
"numpy.lib.arrayterator submodule is now private. To access "
"Arrayterator class use numpy.lib.Arrayterator."
)
else:
raise AttributeError("module {!r} has no attribute "
"{!r}".format(__name__, attr))
3 changes: 1 addition & 2 deletions numpy/lib/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ from numpy.lib._version import (
NumpyVersion as NumpyVersion,
)

from numpy.lib.arrayterator import (
from numpy.lib._arrayterator_impl import (
Arrayterator as Arrayterator,
)

Expand All @@ -39,4 +39,3 @@ __all__: list[str]
test: PytestTester

__version__ = version
emath = scimath
File renamed without changes.
File renamed without changes.
1 change: 0 additions & 1 deletion numpy/tests/test_public_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,6 @@ def test_NPY_NO_EXPORT():
"f2py.symbolic",
"f2py.use_rules",
"fft.helper",
"lib.arrayterator",
"lib.user_array", # note: not in np.lib, but probably should just be deleted
"linalg.lapack_lite",
"linalg.linalg",
Expand Down