From 4c0bc269615d8932a662deac9ff81beb93c19376 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Sok=C3=B3=C5=82?= Date: Thu, 19 Oct 2023 13:45:11 +0200 Subject: [PATCH] MAINT: Python API cleanup nitpicks --- numpy/__init__.py | 101 ++++++++---------- numpy/__init__.pyi | 2 +- numpy/lib/__init__.py | 44 +++++--- numpy/lib/__init__.pyi | 3 +- ...{arrayterator.py => _arrayterator_impl.py} | 0 ...rrayterator.pyi => _arrayterator_impl.pyi} | 0 numpy/tests/test_public_api.py | 1 - 7 files changed, 77 insertions(+), 74 deletions(-) rename numpy/lib/{arrayterator.py => _arrayterator_impl.py} (100%) rename numpy/lib/{arrayterator.pyi => _arrayterator_impl.pyi} (100%) diff --git a/numpy/__init__.py b/numpy/__init__.py index 065a1fe14a91..1b8026e6adde 100644 --- a/numpy/__init__.py +++ b/numpy/__init__.py @@ -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 @@ -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 ) @@ -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__) | @@ -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 @@ -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 diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi index 96890e9269b6..7679e5c157d9 100644 --- a/numpy/__init__.pyi +++ b/numpy/__init__.pyi @@ -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 ( diff --git a/numpy/lib/__init__.py b/numpy/lib/__init__.py index 39cade203e18..22ad35e93c35 100644 --- a/numpy/lib/__init__.py +++ b/numpy/lib/__init__.py @@ -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.`` 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 @@ -25,7 +25,6 @@ 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 @@ -33,19 +32,21 @@ 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'] +__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__) @@ -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)) diff --git a/numpy/lib/__init__.pyi b/numpy/lib/__init__.pyi index b6e22129ca0e..6b105bf44b8e 100644 --- a/numpy/lib/__init__.pyi +++ b/numpy/lib/__init__.pyi @@ -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, ) @@ -39,4 +39,3 @@ __all__: list[str] test: PytestTester __version__ = version -emath = scimath diff --git a/numpy/lib/arrayterator.py b/numpy/lib/_arrayterator_impl.py similarity index 100% rename from numpy/lib/arrayterator.py rename to numpy/lib/_arrayterator_impl.py diff --git a/numpy/lib/arrayterator.pyi b/numpy/lib/_arrayterator_impl.pyi similarity index 100% rename from numpy/lib/arrayterator.pyi rename to numpy/lib/_arrayterator_impl.pyi diff --git a/numpy/tests/test_public_api.py b/numpy/tests/test_public_api.py index 27236e4ea47a..136ace04b9f5 100644 --- a/numpy/tests/test_public_api.py +++ b/numpy/tests/test_public_api.py @@ -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",