diff --git a/doc/release/upcoming_changes/24587.python_removal.rst b/doc/release/upcoming_changes/24587.python_removal.rst new file mode 100644 index 000000000000..801e7fb3a100 --- /dev/null +++ b/doc/release/upcoming_changes/24587.python_removal.rst @@ -0,0 +1,9 @@ +* ``np.compare_chararrays`` has been removed from the main namespace. + Use ``np.char.compare_chararrays`` instead. + +* The ``charrarray`` in the main namespace has been deprecated. It can be imported + without a deprecation warning from ``np.char.chararray`` for now, + but we are planning to fully deprecate and remove ``chararray`` in the future. + +* ``np.format_parser`` has been removed from the main namespace. + Use ``np.rec.format_parser`` instead. diff --git a/doc/source/reference/arrays.classes.rst b/doc/source/reference/arrays.classes.rst index f1b98c5b9567..ae2926be8b9c 100644 --- a/doc/source/reference/arrays.classes.rst +++ b/doc/source/reference/arrays.classes.rst @@ -494,14 +494,14 @@ executing them on an element-by-element basis. Perhaps the easiest way to create a chararray is to use :meth:`self.view(chararray) ` where *self* is an ndarray of str or unicode data-type. However, a chararray can also be created using the -:meth:`numpy.chararray` constructor, or via the +:meth:`numpy.char.chararray` constructor, or via the :func:`numpy.char.array ` function: .. autosummary:: :toctree: generated/ - chararray - core.defchararray.array + char.chararray + char.array Another difference with the standard ndarray of str data-type is that the chararray inherits the feature introduced by Numarray that diff --git a/doc/source/reference/routines.dtype.rst b/doc/source/reference/routines.dtype.rst index 4da9831a9298..35fd431587b4 100644 --- a/doc/source/reference/routines.dtype.rst +++ b/doc/source/reference/routines.dtype.rst @@ -20,7 +20,7 @@ Creating data types :toctree: generated/ dtype - format_parser + rec.format_parser Data type information --------------------- diff --git a/doc/source/user/basics.rec.rst b/doc/source/user/basics.rec.rst index f7e06fa4fada..efe2c8cc982d 100644 --- a/doc/source/user/basics.rec.rst +++ b/doc/source/user/basics.rec.rst @@ -630,8 +630,8 @@ Record Arrays ============= As an optional convenience numpy provides an ndarray subclass, -:class:`numpy.recarray` that allows access to fields of structured arrays by -attribute instead of only by index. +:class:`numpy.recarray` that allows access to fields of structured arrays +by attribute instead of only by index. Record arrays use a special datatype, :class:`numpy.record`, that allows field access by attribute on the structured scalars obtained from the array. The ``numpy.rec`` module provides functions for creating recarrays from @@ -697,7 +697,7 @@ array if the field has a structured type but as a plain ndarray otherwise. :: >>> type(recordarr.foo) >>> type(recordarr.bar) - + Note that if a field has the same name as an ndarray attribute, the ndarray attribute takes precedence. Such fields will be inaccessible by attribute but diff --git a/numpy/__init__.py b/numpy/__init__.py index 096da76ca4ac..1128e5ee525b 100644 --- a/numpy/__init__.py +++ b/numpy/__init__.py @@ -120,7 +120,7 @@ from . import core from .core import ( - _no_nep50_warning, memmap, iinfo, finfo, + _no_nep50_warning, memmap, iinfo, finfo, recarray, False_, ScalarType, True_, abs, absolute, add, all, allclose, alltrue, amax, amin, any, arange, arccos, arccosh, arcsin, arcsinh, arctan, arctan2, arctanh, argmax, argmin, argpartition, argsort, argwhere, @@ -129,8 +129,7 @@ atleast_1d, atleast_2d, atleast_3d, base_repr, binary_repr, bitwise_and, bitwise_not, bitwise_or, bitwise_xor, block, bool_, broadcast, busday_count, busday_offset, busdaycalendar, byte, bytes_, - can_cast, cbrt, cdouble, ceil, char, character, chararray, - choose, clip, clongdouble, compare_chararrays, + 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, @@ -139,7 +138,7 @@ 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, format_parser, + 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, @@ -156,7 +155,7 @@ 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, rec, recarray, reciprocal, + ptp, put, putmask, rad2deg, radians, ravel, reciprocal, record, remainder, repeat, require, reshape, resize, result_type, right_shift, rint, roll, rollaxis, round, searchsorted, set_printoptions, @@ -248,7 +247,7 @@ __numpy_submodules__ = { "linalg", "fft", "dtypes", "random", "polynomial", "ma", "exceptions", "lib", "ctypeslib", "testing", "typing", - "f2py", "test" + "f2py", "test", "rec", "char" } # We build warning messages for former attributes @@ -358,6 +357,12 @@ def __getattr__(attr): elif attr == "typing": import numpy.typing as typing return typing + elif attr == "rec": + import numpy.rec as rec + return rec + elif attr == "char": + import numpy.char as char + return char elif attr == "array_api": import numpy.array_api as array_api return array_api @@ -385,6 +390,14 @@ def __getattr__(attr): f"{__expired_attributes__[attr]}" ) + if attr == "chararray": + warnings.warn( + "`np.chararray` is deprecated and will be removed from " + "the main namespace in the future. Use an array with a string " + "or bytes dtype instead.", DeprecationWarning, stacklevel=2) + import numpy.char as char + return char.chararray + raise AttributeError("module {!r} has no attribute " "{!r}".format(__name__, attr)) diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi index 2608e7ce1ef8..19a540f8a0e5 100644 --- a/numpy/__init__.pyi +++ b/numpy/__init__.pyi @@ -207,11 +207,18 @@ from numpy import ( version as version, exceptions as exceptions, dtypes as dtypes, + rec as rec, + char as char, ) -from numpy.core import defchararray, records -char = defchararray -rec = records +from numpy.core.records import ( + record as record, + recarray as recarray, +) + +from numpy.core.defchararray import ( + chararray as chararray, +) from numpy.core.function_base import ( linspace as linspace, @@ -327,7 +334,6 @@ from numpy.core.multiarray import ( arange as arange, busday_count as busday_count, busday_offset as busday_offset, - compare_chararrays as compare_chararrays, datetime_as_string as datetime_as_string, datetime_data as datetime_data, frombuffer as frombuffer, @@ -3389,97 +3395,6 @@ class iinfo(Generic[_IntType]): @overload def __new__(cls, dtype: str) -> iinfo[Any]: ... -class format_parser: - dtype: dtype[void] - def __init__( - self, - formats: DTypeLike, - names: None | str | Sequence[str], - titles: None | str | Sequence[str], - aligned: bool = ..., - byteorder: None | _ByteOrder = ..., - ) -> None: ... - -class recarray(ndarray[_ShapeType, _DType_co]): - # NOTE: While not strictly mandatory, we're demanding here that arguments - # for the `format_parser`- and `dtype`-based dtype constructors are - # mutually exclusive - @overload - def __new__( - subtype, - shape: _ShapeLike, - dtype: None = ..., - buf: None | _SupportsBuffer = ..., - offset: SupportsIndex = ..., - strides: None | _ShapeLike = ..., - *, - formats: DTypeLike, - names: None | str | Sequence[str] = ..., - titles: None | str | Sequence[str] = ..., - byteorder: None | _ByteOrder = ..., - aligned: bool = ..., - order: _OrderKACF = ..., - ) -> recarray[Any, dtype[record]]: ... - @overload - def __new__( - subtype, - shape: _ShapeLike, - dtype: DTypeLike, - buf: None | _SupportsBuffer = ..., - offset: SupportsIndex = ..., - strides: None | _ShapeLike = ..., - formats: None = ..., - names: None = ..., - titles: None = ..., - byteorder: None = ..., - aligned: L[False] = ..., - order: _OrderKACF = ..., - ) -> recarray[Any, dtype[Any]]: ... - def __array_finalize__(self, obj: object) -> None: ... - def __getattribute__(self, attr: str) -> Any: ... - def __setattr__(self, attr: str, val: ArrayLike) -> None: ... - @overload - def __getitem__(self, indx: ( - SupportsIndex - | _ArrayLikeInt_co - | tuple[SupportsIndex | _ArrayLikeInt_co, ...] - )) -> Any: ... - @overload - def __getitem__(self: recarray[Any, dtype[void]], indx: ( - None - | slice - | ellipsis - | SupportsIndex - | _ArrayLikeInt_co - | tuple[None | slice | ellipsis | _ArrayLikeInt_co | SupportsIndex, ...] - )) -> recarray[Any, _DType_co]: ... - @overload - def __getitem__(self, indx: ( - None - | slice - | ellipsis - | SupportsIndex - | _ArrayLikeInt_co - | tuple[None | slice | ellipsis | _ArrayLikeInt_co | SupportsIndex, ...] - )) -> ndarray[Any, _DType_co]: ... - @overload - def __getitem__(self, indx: str) -> NDArray[Any]: ... - @overload - def __getitem__(self, indx: list[str]) -> recarray[_ShapeType, dtype[record]]: ... - @overload - def field(self, attr: int | str, val: None = ...) -> Any: ... - @overload - def field(self, attr: int | str, val: ArrayLike) -> None: ... - -class record(void): - def __getattribute__(self, attr: str) -> Any: ... - def __setattr__(self, attr: str, val: ArrayLike) -> None: ... - def pprint(self) -> str: ... - @overload - def __getitem__(self, key: str | SupportsIndex) -> Any: ... - @overload - def __getitem__(self, key: list[str]) -> record: ... - _NDIterFlagsKind = L[ "buffered", "c_index", @@ -3876,423 +3791,6 @@ class matrix(ndarray[_ShapeType, _DType_co]): _CharType = TypeVar("_CharType", str_, bytes_) _CharDType = TypeVar("_CharDType", dtype[str_], dtype[bytes_]) -_CharArray = chararray[Any, dtype[_CharType]] - -class chararray(ndarray[_ShapeType, _CharDType]): - @overload - def __new__( - subtype, - shape: _ShapeLike, - itemsize: SupportsIndex | SupportsInt = ..., - unicode: L[False] = ..., - buffer: _SupportsBuffer = ..., - offset: SupportsIndex = ..., - strides: _ShapeLike = ..., - order: _OrderKACF = ..., - ) -> chararray[Any, dtype[bytes_]]: ... - @overload - def __new__( - subtype, - shape: _ShapeLike, - itemsize: SupportsIndex | SupportsInt = ..., - unicode: L[True] = ..., - buffer: _SupportsBuffer = ..., - offset: SupportsIndex = ..., - strides: _ShapeLike = ..., - order: _OrderKACF = ..., - ) -> chararray[Any, dtype[str_]]: ... - - def __array_finalize__(self, obj: object) -> None: ... - def __mul__(self, other: _ArrayLikeInt_co) -> chararray[Any, _CharDType]: ... - def __rmul__(self, other: _ArrayLikeInt_co) -> chararray[Any, _CharDType]: ... - def __mod__(self, i: Any) -> chararray[Any, _CharDType]: ... - - @overload - def __eq__( - self: _CharArray[str_], - other: _ArrayLikeStr_co, - ) -> NDArray[bool_]: ... - @overload - def __eq__( - self: _CharArray[bytes_], - other: _ArrayLikeBytes_co, - ) -> NDArray[bool_]: ... - - @overload - def __ne__( - self: _CharArray[str_], - other: _ArrayLikeStr_co, - ) -> NDArray[bool_]: ... - @overload - def __ne__( - self: _CharArray[bytes_], - other: _ArrayLikeBytes_co, - ) -> NDArray[bool_]: ... - - @overload - def __ge__( - self: _CharArray[str_], - other: _ArrayLikeStr_co, - ) -> NDArray[bool_]: ... - @overload - def __ge__( - self: _CharArray[bytes_], - other: _ArrayLikeBytes_co, - ) -> NDArray[bool_]: ... - - @overload - def __le__( - self: _CharArray[str_], - other: _ArrayLikeStr_co, - ) -> NDArray[bool_]: ... - @overload - def __le__( - self: _CharArray[bytes_], - other: _ArrayLikeBytes_co, - ) -> NDArray[bool_]: ... - - @overload - def __gt__( - self: _CharArray[str_], - other: _ArrayLikeStr_co, - ) -> NDArray[bool_]: ... - @overload - def __gt__( - self: _CharArray[bytes_], - other: _ArrayLikeBytes_co, - ) -> NDArray[bool_]: ... - - @overload - def __lt__( - self: _CharArray[str_], - other: _ArrayLikeStr_co, - ) -> NDArray[bool_]: ... - @overload - def __lt__( - self: _CharArray[bytes_], - other: _ArrayLikeBytes_co, - ) -> NDArray[bool_]: ... - - @overload - def __add__( - self: _CharArray[str_], - other: _ArrayLikeStr_co, - ) -> _CharArray[str_]: ... - @overload - def __add__( - self: _CharArray[bytes_], - other: _ArrayLikeBytes_co, - ) -> _CharArray[bytes_]: ... - - @overload - def __radd__( - self: _CharArray[str_], - other: _ArrayLikeStr_co, - ) -> _CharArray[str_]: ... - @overload - def __radd__( - self: _CharArray[bytes_], - other: _ArrayLikeBytes_co, - ) -> _CharArray[bytes_]: ... - - @overload - def center( - self: _CharArray[str_], - width: _ArrayLikeInt_co, - fillchar: _ArrayLikeStr_co = ..., - ) -> _CharArray[str_]: ... - @overload - def center( - self: _CharArray[bytes_], - width: _ArrayLikeInt_co, - fillchar: _ArrayLikeBytes_co = ..., - ) -> _CharArray[bytes_]: ... - - @overload - def count( - self: _CharArray[str_], - sub: _ArrayLikeStr_co, - start: _ArrayLikeInt_co = ..., - end: None | _ArrayLikeInt_co = ..., - ) -> NDArray[int_]: ... - @overload - def count( - self: _CharArray[bytes_], - sub: _ArrayLikeBytes_co, - start: _ArrayLikeInt_co = ..., - end: None | _ArrayLikeInt_co = ..., - ) -> NDArray[int_]: ... - - def decode( - self: _CharArray[bytes_], - encoding: None | str = ..., - errors: None | str = ..., - ) -> _CharArray[str_]: ... - - def encode( - self: _CharArray[str_], - encoding: None | str = ..., - errors: None | str = ..., - ) -> _CharArray[bytes_]: ... - - @overload - def endswith( - self: _CharArray[str_], - suffix: _ArrayLikeStr_co, - start: _ArrayLikeInt_co = ..., - end: None | _ArrayLikeInt_co = ..., - ) -> NDArray[bool_]: ... - @overload - def endswith( - self: _CharArray[bytes_], - suffix: _ArrayLikeBytes_co, - start: _ArrayLikeInt_co = ..., - end: None | _ArrayLikeInt_co = ..., - ) -> NDArray[bool_]: ... - - def expandtabs( - self, - tabsize: _ArrayLikeInt_co = ..., - ) -> chararray[Any, _CharDType]: ... - - @overload - def find( - self: _CharArray[str_], - sub: _ArrayLikeStr_co, - start: _ArrayLikeInt_co = ..., - end: None | _ArrayLikeInt_co = ..., - ) -> NDArray[int_]: ... - @overload - def find( - self: _CharArray[bytes_], - sub: _ArrayLikeBytes_co, - start: _ArrayLikeInt_co = ..., - end: None | _ArrayLikeInt_co = ..., - ) -> NDArray[int_]: ... - - @overload - def index( - self: _CharArray[str_], - sub: _ArrayLikeStr_co, - start: _ArrayLikeInt_co = ..., - end: None | _ArrayLikeInt_co = ..., - ) -> NDArray[int_]: ... - @overload - def index( - self: _CharArray[bytes_], - sub: _ArrayLikeBytes_co, - start: _ArrayLikeInt_co = ..., - end: None | _ArrayLikeInt_co = ..., - ) -> NDArray[int_]: ... - - @overload - def join( - self: _CharArray[str_], - seq: _ArrayLikeStr_co, - ) -> _CharArray[str_]: ... - @overload - def join( - self: _CharArray[bytes_], - seq: _ArrayLikeBytes_co, - ) -> _CharArray[bytes_]: ... - - @overload - def ljust( - self: _CharArray[str_], - width: _ArrayLikeInt_co, - fillchar: _ArrayLikeStr_co = ..., - ) -> _CharArray[str_]: ... - @overload - def ljust( - self: _CharArray[bytes_], - width: _ArrayLikeInt_co, - fillchar: _ArrayLikeBytes_co = ..., - ) -> _CharArray[bytes_]: ... - - @overload - def lstrip( - self: _CharArray[str_], - chars: None | _ArrayLikeStr_co = ..., - ) -> _CharArray[str_]: ... - @overload - def lstrip( - self: _CharArray[bytes_], - chars: None | _ArrayLikeBytes_co = ..., - ) -> _CharArray[bytes_]: ... - - @overload - def partition( - self: _CharArray[str_], - sep: _ArrayLikeStr_co, - ) -> _CharArray[str_]: ... - @overload - def partition( - self: _CharArray[bytes_], - sep: _ArrayLikeBytes_co, - ) -> _CharArray[bytes_]: ... - - @overload - def replace( - self: _CharArray[str_], - old: _ArrayLikeStr_co, - new: _ArrayLikeStr_co, - count: None | _ArrayLikeInt_co = ..., - ) -> _CharArray[str_]: ... - @overload - def replace( - self: _CharArray[bytes_], - old: _ArrayLikeBytes_co, - new: _ArrayLikeBytes_co, - count: None | _ArrayLikeInt_co = ..., - ) -> _CharArray[bytes_]: ... - - @overload - def rfind( - self: _CharArray[str_], - sub: _ArrayLikeStr_co, - start: _ArrayLikeInt_co = ..., - end: None | _ArrayLikeInt_co = ..., - ) -> NDArray[int_]: ... - @overload - def rfind( - self: _CharArray[bytes_], - sub: _ArrayLikeBytes_co, - start: _ArrayLikeInt_co = ..., - end: None | _ArrayLikeInt_co = ..., - ) -> NDArray[int_]: ... - - @overload - def rindex( - self: _CharArray[str_], - sub: _ArrayLikeStr_co, - start: _ArrayLikeInt_co = ..., - end: None | _ArrayLikeInt_co = ..., - ) -> NDArray[int_]: ... - @overload - def rindex( - self: _CharArray[bytes_], - sub: _ArrayLikeBytes_co, - start: _ArrayLikeInt_co = ..., - end: None | _ArrayLikeInt_co = ..., - ) -> NDArray[int_]: ... - - @overload - def rjust( - self: _CharArray[str_], - width: _ArrayLikeInt_co, - fillchar: _ArrayLikeStr_co = ..., - ) -> _CharArray[str_]: ... - @overload - def rjust( - self: _CharArray[bytes_], - width: _ArrayLikeInt_co, - fillchar: _ArrayLikeBytes_co = ..., - ) -> _CharArray[bytes_]: ... - - @overload - def rpartition( - self: _CharArray[str_], - sep: _ArrayLikeStr_co, - ) -> _CharArray[str_]: ... - @overload - def rpartition( - self: _CharArray[bytes_], - sep: _ArrayLikeBytes_co, - ) -> _CharArray[bytes_]: ... - - @overload - def rsplit( - self: _CharArray[str_], - sep: None | _ArrayLikeStr_co = ..., - maxsplit: None | _ArrayLikeInt_co = ..., - ) -> NDArray[object_]: ... - @overload - def rsplit( - self: _CharArray[bytes_], - sep: None | _ArrayLikeBytes_co = ..., - maxsplit: None | _ArrayLikeInt_co = ..., - ) -> NDArray[object_]: ... - - @overload - def rstrip( - self: _CharArray[str_], - chars: None | _ArrayLikeStr_co = ..., - ) -> _CharArray[str_]: ... - @overload - def rstrip( - self: _CharArray[bytes_], - chars: None | _ArrayLikeBytes_co = ..., - ) -> _CharArray[bytes_]: ... - - @overload - def split( - self: _CharArray[str_], - sep: None | _ArrayLikeStr_co = ..., - maxsplit: None | _ArrayLikeInt_co = ..., - ) -> NDArray[object_]: ... - @overload - def split( - self: _CharArray[bytes_], - sep: None | _ArrayLikeBytes_co = ..., - maxsplit: None | _ArrayLikeInt_co = ..., - ) -> NDArray[object_]: ... - - def splitlines(self, keepends: None | _ArrayLikeBool_co = ...) -> NDArray[object_]: ... - - @overload - def startswith( - self: _CharArray[str_], - prefix: _ArrayLikeStr_co, - start: _ArrayLikeInt_co = ..., - end: None | _ArrayLikeInt_co = ..., - ) -> NDArray[bool_]: ... - @overload - def startswith( - self: _CharArray[bytes_], - prefix: _ArrayLikeBytes_co, - start: _ArrayLikeInt_co = ..., - end: None | _ArrayLikeInt_co = ..., - ) -> NDArray[bool_]: ... - - @overload - def strip( - self: _CharArray[str_], - chars: None | _ArrayLikeStr_co = ..., - ) -> _CharArray[str_]: ... - @overload - def strip( - self: _CharArray[bytes_], - chars: None | _ArrayLikeBytes_co = ..., - ) -> _CharArray[bytes_]: ... - - @overload - def translate( - self: _CharArray[str_], - table: _ArrayLikeStr_co, - deletechars: None | _ArrayLikeStr_co = ..., - ) -> _CharArray[str_]: ... - @overload - def translate( - self: _CharArray[bytes_], - table: _ArrayLikeBytes_co, - deletechars: None | _ArrayLikeBytes_co = ..., - ) -> _CharArray[bytes_]: ... - - def zfill(self, width: _ArrayLikeInt_co) -> chararray[Any, _CharDType]: ... - def capitalize(self) -> chararray[_ShapeType, _CharDType]: ... - def title(self) -> chararray[_ShapeType, _CharDType]: ... - def swapcase(self) -> chararray[_ShapeType, _CharDType]: ... - def lower(self) -> chararray[_ShapeType, _CharDType]: ... - def upper(self) -> chararray[_ShapeType, _CharDType]: ... - def isalnum(self) -> ndarray[_ShapeType, dtype[bool_]]: ... - def isalpha(self) -> ndarray[_ShapeType, dtype[bool_]]: ... - def isdigit(self) -> ndarray[_ShapeType, dtype[bool_]]: ... - def islower(self) -> ndarray[_ShapeType, dtype[bool_]]: ... - def isspace(self) -> ndarray[_ShapeType, dtype[bool_]]: ... - def istitle(self) -> ndarray[_ShapeType, dtype[bool_]]: ... - def isupper(self) -> ndarray[_ShapeType, dtype[bool_]]: ... - def isnumeric(self) -> ndarray[_ShapeType, dtype[bool_]]: ... - def isdecimal(self) -> ndarray[_ShapeType, dtype[bool_]]: ... # NOTE: Deprecated # class MachAr: ... diff --git a/numpy/_expired_attrs_2_0.py b/numpy/_expired_attrs_2_0.py index 8cf0ae95a297..bf9456c00c89 100644 --- a/numpy/_expired_attrs_2_0.py +++ b/numpy/_expired_attrs_2_0.py @@ -69,4 +69,7 @@ "DataSource": "It's still available as `np.lib.npyio.DataSource`.", "nbytes": "Use `np.dtype().itemsize` instead.", "byte_bounds": "Now it's available under `np.lib.array_utils.byte_bounds`", + "compare_chararrays": + "It's still available as `np.char.compare_chararrays`.", + "format_parser": "It's still available as `np.rec.format_parser`.", } diff --git a/numpy/char/__init__.py b/numpy/char/__init__.py new file mode 100644 index 000000000000..f9e3eaf3466b --- /dev/null +++ b/numpy/char/__init__.py @@ -0,0 +1,2 @@ +from numpy.core.defchararray import __all__, __doc__ +from numpy.core.defchararray import * diff --git a/numpy/char/__init__.pyi b/numpy/char/__init__.pyi new file mode 100644 index 000000000000..f5612532b3d1 --- /dev/null +++ b/numpy/char/__init__.pyi @@ -0,0 +1,57 @@ +from numpy.core.defchararray import ( + equal as equal, + not_equal as not_equal, + greater_equal as greater_equal, + less_equal as less_equal, + greater as greater, + less as less, + str_len as str_len, + add as add, + multiply as multiply, + mod as mod, + capitalize as capitalize, + center as center, + count as count, + decode as decode, + encode as encode, + endswith as endswith, + expandtabs as expandtabs, + find as find, + index as index, + isalnum as isalnum, + isalpha as isalpha, + isdigit as isdigit, + islower as islower, + isspace as isspace, + istitle as istitle, + isupper as isupper, + join as join, + ljust as ljust, + lower as lower, + lstrip as lstrip, + partition as partition, + replace as replace, + rfind as rfind, + rindex as rindex, + rjust as rjust, + rpartition as rpartition, + rsplit as rsplit, + rstrip as rstrip, + split as split, + splitlines as splitlines, + startswith as startswith, + strip as strip, + swapcase as swapcase, + title as title, + translate as translate, + upper as upper, + zfill as zfill, + isnumeric as isnumeric, + isdecimal as isdecimal, + array as array, + asarray as asarray, + compare_chararrays as compare_chararrays, + chararray as chararray +) + +__all__: list[str] diff --git a/numpy/core/__init__.py b/numpy/core/__init__.py index fc1483dd82ac..a0946d89eaee 100644 --- a/numpy/core/__init__.py +++ b/numpy/core/__init__.py @@ -76,13 +76,9 @@ from .numeric import * from . import fromnumeric from .fromnumeric import * -from . import defchararray as char -from . import records -from . import records as rec -from .records import record, recarray, format_parser +from .records import record, recarray # Note: module name memmap is overwritten by a class with same name from .memmap import * -from .defchararray import chararray from . import function_base from .function_base import * from . import _machar @@ -106,9 +102,8 @@ from . import _dtype from . import _methods -__all__ = ['char', 'rec', 'memmap', 'sctypeDict'] +__all__ = ['memmap', 'sctypeDict', 'record', 'recarray', 'abs'] __all__ += numeric.__all__ -__all__ += ['record', 'recarray', 'format_parser', 'chararray', 'abs'] __all__ += function_base.__all__ __all__ += getlimits.__all__ __all__ += shape_base.__all__ diff --git a/numpy/core/_add_newdocs.py b/numpy/core/_add_newdocs.py index 0c6d7d5a59aa..67dcbaa767bf 100644 --- a/numpy/core/_add_newdocs.py +++ b/numpy/core/_add_newdocs.py @@ -980,7 +980,7 @@ >>> issubclass(np.recarray, np.ndarray) True - >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray) + >>> a = np.array([(1., 2), (3., 4)], dtype='f4,i4').view(np.recarray) >>> np.asarray(a) is a False >>> np.asanyarray(a) is a @@ -1044,7 +1044,7 @@ Instances of `ndarray` subclasses are passed through as-is: - >>> a = np.array([(1.0, 2), (3.0, 4)], dtype='f4,i4').view(np.recarray) + >>> a = np.array([(1., 2), (3., 4)], dtype='f4,i4').view(np.recarray) >>> np.asanyarray(a) is a True @@ -1419,7 +1419,7 @@ -------- >>> a = np.array(["a", "b", "cde"]) >>> b = np.array(["a", "a", "dec"]) - >>> np.compare_chararrays(a, b, ">", True) + >>> np.char.compare_chararrays(a, b, ">", True) array([False, True, False]) """) diff --git a/numpy/core/defchararray.py b/numpy/core/defchararray.py index c93581214c6c..b523c0db477c 100644 --- a/numpy/core/defchararray.py +++ b/numpy/core/defchararray.py @@ -20,9 +20,8 @@ from .._utils import set_module from .numerictypes import ( bytes_, str_, integer, int_, object_, bool_, character) -from .numeric import ndarray, compare_chararrays -from .numeric import array as narray -from numpy.core.multiarray import _vec_string +from .numeric import ndarray, array as narray +from numpy.core.multiarray import _vec_string, compare_chararrays from numpy.core import overrides from numpy._utils import asbytes import numpy @@ -36,7 +35,7 @@ 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill', 'isnumeric', 'isdecimal', - 'array', 'asarray' + 'array', 'asarray', 'compare_chararrays', 'chararray' ] @@ -1920,7 +1919,7 @@ def isdecimal(a): return _vec_string(a, bool_, 'isdecimal') -@set_module('numpy') +@set_module("numpy.char") class chararray(ndarray): """ chararray(shape, itemsize=1, unicode=False, buffer=None, offset=0, @@ -2046,14 +2045,14 @@ class adds the following functionality: Examples -------- - >>> charar = np.chararray((3, 3)) + >>> charar = np.char.chararray((3, 3)) >>> charar[:] = 'a' >>> charar chararray([[b'a', b'a', b'a'], [b'a', b'a', b'a'], [b'a', b'a', b'a']], dtype='|S1') - >>> charar = np.chararray(charar.shape, itemsize=5) + >>> charar = np.char.chararray(charar.shape, itemsize=5) >>> charar[:] = 'abc' >>> charar chararray([[b'abc', b'abc', b'abc'], @@ -2247,7 +2246,7 @@ def argsort(self, axis=-1, kind=None, order=None): Examples -------- >>> c = np.array(['a1b c', '1b ca', 'b ca1', 'Ca1b'], 'S5') - >>> c = c.view(np.chararray); c + >>> c = c.view(np.char.chararray); c chararray(['a1b c', '1b ca', 'b ca1', 'Ca1b'], dtype='|S5') >>> c[c.argsort()] diff --git a/numpy/core/defchararray.pyi b/numpy/core/defchararray.pyi index 73d90bb2fc53..e79aa3b468f4 100644 --- a/numpy/core/defchararray.pyi +++ b/numpy/core/defchararray.pyi @@ -3,10 +3,12 @@ from typing import ( overload, TypeVar, Any, + SupportsIndex, + SupportsInt, ) from numpy import ( - chararray as chararray, + ndarray, dtype, str_, bytes_, @@ -14,10 +16,14 @@ from numpy import ( bool_, object_, _OrderKACF, + _ShapeType, + _CharDType, + _SupportsBuffer, ) from numpy._typing import ( NDArray, + _ShapeLike, _ArrayLikeStr_co as U_co, _ArrayLikeBytes_co as S_co, _ArrayLikeInt_co as i_co, @@ -29,6 +35,422 @@ from numpy.core.multiarray import compare_chararrays as compare_chararrays _SCT = TypeVar("_SCT", str_, bytes_) _CharArray = chararray[Any, dtype[_SCT]] +class chararray(ndarray[_ShapeType, _CharDType]): + @overload + def __new__( + subtype, + shape: _ShapeLike, + itemsize: SupportsIndex | SupportsInt = ..., + unicode: L[False] = ..., + buffer: _SupportsBuffer = ..., + offset: SupportsIndex = ..., + strides: _ShapeLike = ..., + order: _OrderKACF = ..., + ) -> chararray[Any, dtype[bytes_]]: ... + @overload + def __new__( + subtype, + shape: _ShapeLike, + itemsize: SupportsIndex | SupportsInt = ..., + unicode: L[True] = ..., + buffer: _SupportsBuffer = ..., + offset: SupportsIndex = ..., + strides: _ShapeLike = ..., + order: _OrderKACF = ..., + ) -> chararray[Any, dtype[str_]]: ... + + def __array_finalize__(self, obj: object) -> None: ... + def __mul__(self, other: i_co) -> chararray[Any, _CharDType]: ... + def __rmul__(self, other: i_co) -> chararray[Any, _CharDType]: ... + def __mod__(self, i: Any) -> chararray[Any, _CharDType]: ... + + @overload + def __eq__( + self: _CharArray[str_], + other: U_co, + ) -> NDArray[bool_]: ... + @overload + def __eq__( + self: _CharArray[bytes_], + other: S_co, + ) -> NDArray[bool_]: ... + + @overload + def __ne__( + self: _CharArray[str_], + other: U_co, + ) -> NDArray[bool_]: ... + @overload + def __ne__( + self: _CharArray[bytes_], + other: S_co, + ) -> NDArray[bool_]: ... + + @overload + def __ge__( + self: _CharArray[str_], + other: U_co, + ) -> NDArray[bool_]: ... + @overload + def __ge__( + self: _CharArray[bytes_], + other: S_co, + ) -> NDArray[bool_]: ... + + @overload + def __le__( + self: _CharArray[str_], + other: U_co, + ) -> NDArray[bool_]: ... + @overload + def __le__( + self: _CharArray[bytes_], + other: S_co, + ) -> NDArray[bool_]: ... + + @overload + def __gt__( + self: _CharArray[str_], + other: U_co, + ) -> NDArray[bool_]: ... + @overload + def __gt__( + self: _CharArray[bytes_], + other: S_co, + ) -> NDArray[bool_]: ... + + @overload + def __lt__( + self: _CharArray[str_], + other: U_co, + ) -> NDArray[bool_]: ... + @overload + def __lt__( + self: _CharArray[bytes_], + other: S_co, + ) -> NDArray[bool_]: ... + + @overload + def __add__( + self: _CharArray[str_], + other: U_co, + ) -> _CharArray[str_]: ... + @overload + def __add__( + self: _CharArray[bytes_], + other: S_co, + ) -> _CharArray[bytes_]: ... + + @overload + def __radd__( + self: _CharArray[str_], + other: U_co, + ) -> _CharArray[str_]: ... + @overload + def __radd__( + self: _CharArray[bytes_], + other: S_co, + ) -> _CharArray[bytes_]: ... + + @overload + def center( + self: _CharArray[str_], + width: i_co, + fillchar: U_co = ..., + ) -> _CharArray[str_]: ... + @overload + def center( + self: _CharArray[bytes_], + width: i_co, + fillchar: S_co = ..., + ) -> _CharArray[bytes_]: ... + + @overload + def count( + self: _CharArray[str_], + sub: U_co, + start: i_co = ..., + end: None | i_co = ..., + ) -> NDArray[int_]: ... + @overload + def count( + self: _CharArray[bytes_], + sub: S_co, + start: i_co = ..., + end: None | i_co = ..., + ) -> NDArray[int_]: ... + + def decode( + self: _CharArray[bytes_], + encoding: None | str = ..., + errors: None | str = ..., + ) -> _CharArray[str_]: ... + + def encode( + self: _CharArray[str_], + encoding: None | str = ..., + errors: None | str = ..., + ) -> _CharArray[bytes_]: ... + + @overload + def endswith( + self: _CharArray[str_], + suffix: U_co, + start: i_co = ..., + end: None | i_co = ..., + ) -> NDArray[bool_]: ... + @overload + def endswith( + self: _CharArray[bytes_], + suffix: S_co, + start: i_co = ..., + end: None | i_co = ..., + ) -> NDArray[bool_]: ... + + def expandtabs( + self, + tabsize: i_co = ..., + ) -> chararray[Any, _CharDType]: ... + + @overload + def find( + self: _CharArray[str_], + sub: U_co, + start: i_co = ..., + end: None | i_co = ..., + ) -> NDArray[int_]: ... + @overload + def find( + self: _CharArray[bytes_], + sub: S_co, + start: i_co = ..., + end: None | i_co = ..., + ) -> NDArray[int_]: ... + + @overload + def index( + self: _CharArray[str_], + sub: U_co, + start: i_co = ..., + end: None | i_co = ..., + ) -> NDArray[int_]: ... + @overload + def index( + self: _CharArray[bytes_], + sub: S_co, + start: i_co = ..., + end: None | i_co = ..., + ) -> NDArray[int_]: ... + + @overload + def join( + self: _CharArray[str_], + seq: U_co, + ) -> _CharArray[str_]: ... + @overload + def join( + self: _CharArray[bytes_], + seq: S_co, + ) -> _CharArray[bytes_]: ... + + @overload + def ljust( + self: _CharArray[str_], + width: i_co, + fillchar: U_co = ..., + ) -> _CharArray[str_]: ... + @overload + def ljust( + self: _CharArray[bytes_], + width: i_co, + fillchar: S_co = ..., + ) -> _CharArray[bytes_]: ... + + @overload + def lstrip( + self: _CharArray[str_], + chars: None | U_co = ..., + ) -> _CharArray[str_]: ... + @overload + def lstrip( + self: _CharArray[bytes_], + chars: None | S_co = ..., + ) -> _CharArray[bytes_]: ... + + @overload + def partition( + self: _CharArray[str_], + sep: U_co, + ) -> _CharArray[str_]: ... + @overload + def partition( + self: _CharArray[bytes_], + sep: S_co, + ) -> _CharArray[bytes_]: ... + + @overload + def replace( + self: _CharArray[str_], + old: U_co, + new: U_co, + count: None | i_co = ..., + ) -> _CharArray[str_]: ... + @overload + def replace( + self: _CharArray[bytes_], + old: S_co, + new: S_co, + count: None | i_co = ..., + ) -> _CharArray[bytes_]: ... + + @overload + def rfind( + self: _CharArray[str_], + sub: U_co, + start: i_co = ..., + end: None | i_co = ..., + ) -> NDArray[int_]: ... + @overload + def rfind( + self: _CharArray[bytes_], + sub: S_co, + start: i_co = ..., + end: None | i_co = ..., + ) -> NDArray[int_]: ... + + @overload + def rindex( + self: _CharArray[str_], + sub: U_co, + start: i_co = ..., + end: None | i_co = ..., + ) -> NDArray[int_]: ... + @overload + def rindex( + self: _CharArray[bytes_], + sub: S_co, + start: i_co = ..., + end: None | i_co = ..., + ) -> NDArray[int_]: ... + + @overload + def rjust( + self: _CharArray[str_], + width: i_co, + fillchar: U_co = ..., + ) -> _CharArray[str_]: ... + @overload + def rjust( + self: _CharArray[bytes_], + width: i_co, + fillchar: S_co = ..., + ) -> _CharArray[bytes_]: ... + + @overload + def rpartition( + self: _CharArray[str_], + sep: U_co, + ) -> _CharArray[str_]: ... + @overload + def rpartition( + self: _CharArray[bytes_], + sep: S_co, + ) -> _CharArray[bytes_]: ... + + @overload + def rsplit( + self: _CharArray[str_], + sep: None | U_co = ..., + maxsplit: None | i_co = ..., + ) -> NDArray[object_]: ... + @overload + def rsplit( + self: _CharArray[bytes_], + sep: None | S_co = ..., + maxsplit: None | i_co = ..., + ) -> NDArray[object_]: ... + + @overload + def rstrip( + self: _CharArray[str_], + chars: None | U_co = ..., + ) -> _CharArray[str_]: ... + @overload + def rstrip( + self: _CharArray[bytes_], + chars: None | S_co = ..., + ) -> _CharArray[bytes_]: ... + + @overload + def split( + self: _CharArray[str_], + sep: None | U_co = ..., + maxsplit: None | i_co = ..., + ) -> NDArray[object_]: ... + @overload + def split( + self: _CharArray[bytes_], + sep: None | S_co = ..., + maxsplit: None | i_co = ..., + ) -> NDArray[object_]: ... + + def splitlines(self, keepends: None | b_co = ...) -> NDArray[object_]: ... + + @overload + def startswith( + self: _CharArray[str_], + prefix: U_co, + start: i_co = ..., + end: None | i_co = ..., + ) -> NDArray[bool_]: ... + @overload + def startswith( + self: _CharArray[bytes_], + prefix: S_co, + start: i_co = ..., + end: None | i_co = ..., + ) -> NDArray[bool_]: ... + + @overload + def strip( + self: _CharArray[str_], + chars: None | U_co = ..., + ) -> _CharArray[str_]: ... + @overload + def strip( + self: _CharArray[bytes_], + chars: None | S_co = ..., + ) -> _CharArray[bytes_]: ... + + @overload + def translate( + self: _CharArray[str_], + table: U_co, + deletechars: None | U_co = ..., + ) -> _CharArray[str_]: ... + @overload + def translate( + self: _CharArray[bytes_], + table: S_co, + deletechars: None | S_co = ..., + ) -> _CharArray[bytes_]: ... + + def zfill(self, width: _ArrayLikeInt_co) -> chararray[Any, _CharDType]: ... + def capitalize(self) -> chararray[_ShapeType, _CharDType]: ... + def title(self) -> chararray[_ShapeType, _CharDType]: ... + def swapcase(self) -> chararray[_ShapeType, _CharDType]: ... + def lower(self) -> chararray[_ShapeType, _CharDType]: ... + def upper(self) -> chararray[_ShapeType, _CharDType]: ... + def isalnum(self) -> ndarray[_ShapeType, dtype[bool_]]: ... + def isalpha(self) -> ndarray[_ShapeType, dtype[bool_]]: ... + def isdigit(self) -> ndarray[_ShapeType, dtype[bool_]]: ... + def islower(self) -> ndarray[_ShapeType, dtype[bool_]]: ... + def isspace(self) -> ndarray[_ShapeType, dtype[bool_]]: ... + def istitle(self) -> ndarray[_ShapeType, dtype[bool_]]: ... + def isupper(self) -> ndarray[_ShapeType, dtype[bool_]]: ... + def isnumeric(self) -> ndarray[_ShapeType, dtype[bool_]]: ... + def isdecimal(self) -> ndarray[_ShapeType, dtype[bool_]]: ... + __all__: list[str] # Comparison diff --git a/numpy/core/numeric.py b/numpy/core/numeric.py index ea3aeaf5f513..5d44b18bd3bd 100644 --- a/numpy/core/numeric.py +++ b/numpy/core/numeric.py @@ -12,7 +12,7 @@ ALLOW_THREADS, BUFSIZE, CLIP, MAXDIMS, MAY_SHARE_BOUNDS, MAY_SHARE_EXACT, RAISE, WRAP, arange, array, asarray, asanyarray, ascontiguousarray, - asfortranarray, broadcast, can_cast, compare_chararrays, + asfortranarray, broadcast, can_cast, concatenate, copyto, dot, dtype, empty, empty_like, flatiter, frombuffer, from_dlpack, fromfile, fromiter, fromstring, inner, lexsort, matmul, may_share_memory, @@ -50,7 +50,7 @@ 'rollaxis', 'moveaxis', 'cross', 'tensordot', 'little_endian', 'fromiter', 'array_equal', 'array_equiv', 'indices', 'fromfunction', 'isclose', 'isscalar', 'binary_repr', 'base_repr', 'ones', - 'identity', 'allclose', 'compare_chararrays', 'putmask', + 'identity', 'allclose', 'putmask', 'flatnonzero', 'inf', 'nan', 'False_', 'True_', 'bitwise_not', 'full', 'full_like', 'matmul', 'shares_memory', 'may_share_memory', '_get_promotion_state', '_set_promotion_state'] diff --git a/numpy/core/records.py b/numpy/core/records.py index 14f8f0836f86..525fc4897afd 100644 --- a/numpy/core/records.py +++ b/numpy/core/records.py @@ -45,8 +45,8 @@ # All of the functions allow formats to be a dtype __all__ = [ - 'record', 'recarray', 'format_parser', - 'fromarrays', 'fromrecords', 'fromstring', 'fromfile', 'array', + 'record', 'recarray', 'format_parser', 'fromarrays', 'fromrecords', + 'fromstring', 'fromfile', 'array', 'find_duplicate', ] @@ -75,6 +75,7 @@ numfmt = nt.sctypeDict +@set_module('numpy.rec') def find_duplicate(list): """Find duplication in a list, return a list of duplicated elements""" return [ @@ -84,7 +85,7 @@ def find_duplicate(list): ] -@set_module('numpy') +@set_module('numpy.rec') class format_parser: """ Class to convert formats, names, titles description to a dtype. @@ -128,18 +129,18 @@ class format_parser: Examples -------- - >>> np.format_parser(['>> np.rec.format_parser(['>> np.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'], - ... []).dtype + >>> np.rec.format_parser(['f8', 'i4', 'a5'], ['col1', 'col2', 'col3'], + ... []).dtype dtype([('col1', '>> np.format_parser(['>> np.rec.format_parser([' int: ... def readinto(self, buffer: memoryview, /) -> int: ... +class record(void): + def __getattribute__(self, attr: str) -> Any: ... + def __setattr__(self, attr: str, val: ArrayLike) -> None: ... + def pprint(self) -> str: ... + @overload + def __getitem__(self, key: str | SupportsIndex) -> Any: ... + @overload + def __getitem__(self, key: list[str]) -> record: ... + +class recarray(ndarray[_ShapeType, _DType_co]): + # NOTE: While not strictly mandatory, we're demanding here that arguments + # for the `format_parser`- and `dtype`-based dtype constructors are + # mutually exclusive + @overload + def __new__( + subtype, + shape: _ShapeLike, + dtype: None = ..., + buf: None | _SupportsBuffer = ..., + offset: SupportsIndex = ..., + strides: None | _ShapeLike = ..., + *, + formats: DTypeLike, + names: None | str | Sequence[str] = ..., + titles: None | str | Sequence[str] = ..., + byteorder: None | _ByteOrder = ..., + aligned: bool = ..., + order: _OrderKACF = ..., + ) -> recarray[Any, dtype[record]]: ... + @overload + def __new__( + subtype, + shape: _ShapeLike, + dtype: DTypeLike, + buf: None | _SupportsBuffer = ..., + offset: SupportsIndex = ..., + strides: None | _ShapeLike = ..., + formats: None = ..., + names: None = ..., + titles: None = ..., + byteorder: None = ..., + aligned: Literal[False] = ..., + order: _OrderKACF = ..., + ) -> recarray[Any, dtype[Any]]: ... + def __array_finalize__(self, obj: object) -> None: ... + def __getattribute__(self, attr: str) -> Any: ... + def __setattr__(self, attr: str, val: ArrayLike) -> None: ... + @overload + def __getitem__(self, indx: ( + SupportsIndex + | _ArrayLikeInt_co + | tuple[SupportsIndex | _ArrayLikeInt_co, ...] + )) -> Any: ... + @overload + def __getitem__(self: recarray[Any, dtype[void]], indx: ( + None + | slice + | ellipsis + | SupportsIndex + | _ArrayLikeInt_co + | tuple[None | slice | ellipsis | _ArrayLikeInt_co | SupportsIndex, ...] + )) -> recarray[Any, _DType_co]: ... + @overload + def __getitem__(self, indx: ( + None + | slice + | ellipsis + | SupportsIndex + | _ArrayLikeInt_co + | tuple[None | slice | ellipsis | _ArrayLikeInt_co | SupportsIndex, ...] + )) -> ndarray[Any, _DType_co]: ... + @overload + def __getitem__(self, indx: str) -> NDArray[Any]: ... + @overload + def __getitem__(self, indx: list[str]) -> recarray[_ShapeType, dtype[record]]: ... + @overload + def field(self, attr: int | str, val: None = ...) -> Any: ... + @overload + def field(self, attr: int | str, val: ArrayLike) -> None: ... + +class format_parser: + dtype: dtype[void] + def __init__( + self, + formats: DTypeLike, + names: None | str | Sequence[str], + titles: None | str | Sequence[str], + aligned: bool = ..., + byteorder: None | _ByteOrder = ..., + ) -> None: ... + __all__: list[str] @overload diff --git a/numpy/core/tests/test_arraymethod.py b/numpy/core/tests/test_arraymethod.py index 4fd4d555845a..b98d712800b7 100644 --- a/numpy/core/tests/test_arraymethod.py +++ b/numpy/core/tests/test_arraymethod.py @@ -65,7 +65,9 @@ def test_invalid_arguments(self, args, error): @pytest.mark.parametrize( - "cls", [np.ndarray, np.recarray, np.chararray, np.matrix, np.memmap] + "cls", [ + np.ndarray, np.recarray, np.char.chararray, np.matrix, np.memmap + ] ) class TestClassGetItem: def test_class_getitem(self, cls: type[np.ndarray]) -> None: diff --git a/numpy/core/tests/test_defchararray.py b/numpy/core/tests/test_defchararray.py index d6692a23ac14..9f4432879e80 100644 --- a/numpy/core/tests/test_defchararray.py +++ b/numpy/core/tests/test_defchararray.py @@ -135,9 +135,9 @@ def fail(): class TestWhitespace: def setup_method(self): self.A = np.array([['abc ', '123 '], - ['789 ', 'xyz ']]).view(np.chararray) + ['789 ', 'xyz ']]).view(np.char.chararray) self.B = np.array([['abc', '123'], - ['789', 'xyz']]).view(np.chararray) + ['789', 'xyz']]).view(np.char.chararray) def test1(self): assert_(np.all(self.A == self.B)) @@ -149,7 +149,7 @@ def test1(self): class TestChar: def setup_method(self): - self.A = np.array('abc1', dtype='c').view(np.chararray) + self.A = np.array('abc1', dtype='c').view(np.char.chararray) def test_it(self): assert_equal(self.A.shape, (4,)) @@ -158,9 +158,9 @@ def test_it(self): class TestComparisons: def setup_method(self): self.A = np.array([['abc', '123'], - ['789', 'xyz']]).view(np.chararray) + ['789', 'xyz']]).view(np.char.chararray) self.B = np.array([['efg', '123 '], - ['051', 'tuv']]).view(np.chararray) + ['051', 'tuv']]).view(np.char.chararray) def test_not_equal(self): assert_array_equal((self.A != self.B), [[True, False], [True, True]]) @@ -192,7 +192,7 @@ class TestComparisonsMixed1(TestComparisons): def setup_method(self): TestComparisons.setup_method(self) self.B = np.array([['efg', '123 '], - ['051', 'tuv']], np.str_).view(np.chararray) + ['051', 'tuv']], np.str_).view(np.char.chararray) class TestComparisonsMixed2(TestComparisons): """Ticket #1276""" @@ -200,16 +200,19 @@ class TestComparisonsMixed2(TestComparisons): def setup_method(self): TestComparisons.setup_method(self) self.A = np.array([['abc', '123'], - ['789', 'xyz']], np.str_).view(np.chararray) + ['789', 'xyz']], np.str_) \ + .view(np.char.chararray) class TestInformation: def setup_method(self): self.A = np.array([[' abc ', ''], ['12345', 'MixedCase'], - ['123 \t 345 \0 ', 'UPPER']]).view(np.chararray) + ['123 \t 345 \0 ', 'UPPER']]) \ + .view(np.char.chararray) self.B = np.array([[' \u03a3 ', ''], ['12345', 'MixedCase'], - ['123 \t 345 \0 ', 'UPPER']]).view(np.chararray) + ['123 \t 345 \0 ', 'UPPER']]) \ + .view(np.char.chararray) def test_len(self): assert_(issubclass(np.char.str_len(self.A).dtype.type, np.integer)) @@ -313,10 +316,11 @@ def setup_method(self): self.A = np.array([[' abc ', ''], ['12345', 'MixedCase'], ['123 \t 345 \0 ', 'UPPER']], - dtype='S').view(np.chararray) + dtype='S').view(np.char.chararray) self.B = np.array([[' \u03a3 ', ''], ['12345', 'MixedCase'], - ['123 \t 345 \0 ', 'UPPER']]).view(np.chararray) + ['123 \t 345 \0 ', 'UPPER']]).view( + np.char.chararray) def test_capitalize(self): tgt = [[b' abc ', b''], @@ -584,26 +588,26 @@ def fail(): class TestOperations: def setup_method(self): self.A = np.array([['abc', '123'], - ['789', 'xyz']]).view(np.chararray) + ['789', 'xyz']]).view(np.char.chararray) self.B = np.array([['efg', '456'], - ['051', 'tuv']]).view(np.chararray) + ['051', 'tuv']]).view(np.char.chararray) def test_add(self): AB = np.array([['abcefg', '123456'], - ['789051', 'xyztuv']]).view(np.chararray) + ['789051', 'xyztuv']]).view(np.char.chararray) assert_array_equal(AB, (self.A + self.B)) assert_(len((self.A + self.B)[0][0]) == 6) def test_radd(self): QA = np.array([['qabc', 'q123'], - ['q789', 'qxyz']]).view(np.chararray) + ['q789', 'qxyz']]).view(np.char.chararray) assert_array_equal(QA, ('q' + self.A)) def test_mul(self): A = self.A for r in (2, 3, 5, 7, 197): Ar = np.array([[A[0, 0]*r, A[0, 1]*r], - [A[1, 0]*r, A[1, 1]*r]]).view(np.chararray) + [A[1, 0]*r, A[1, 1]*r]]).view(np.char.chararray) assert_array_equal(Ar, (self.A * r)) @@ -616,7 +620,7 @@ def test_rmul(self): A = self.A for r in (2, 3, 5, 7, 197): Ar = np.array([[A[0, 0]*r, A[0, 1]*r], - [A[1, 0]*r, A[1, 1]*r]]).view(np.chararray) + [A[1, 0]*r, A[1, 1]*r]]).view(np.char.chararray) assert_array_equal(Ar, (r * self.A)) for ob in [object(), 'qrs']: @@ -626,19 +630,19 @@ def test_rmul(self): def test_mod(self): """Ticket #856""" - F = np.array([['%d', '%f'], ['%s', '%r']]).view(np.chararray) + F = np.array([['%d', '%f'], ['%s', '%r']]).view(np.char.chararray) C = np.array([[3, 7], [19, 1]], dtype=np.int64) FC = np.array([['3', '7.000000'], - ['19', 'np.int64(1)']]).view(np.chararray) + ['19', 'np.int64(1)']]).view(np.char.chararray) assert_array_equal(FC, F % C) - A = np.array([['%.3f', '%d'], ['%s', '%r']]).view(np.chararray) + A = np.array([['%.3f', '%d'], ['%s', '%r']]).view(np.char.chararray) A1 = np.array([['1.000', '1'], - ['1', repr(np.array(1)[()])]]).view(np.chararray) + ['1', repr(np.array(1)[()])]]).view(np.char.chararray) assert_array_equal(A1, (A % 1)) A2 = np.array([['1.000', '2'], - ['3', repr(np.array(4)[()])]]).view(np.chararray) + ['3', repr(np.array(4)[()])]]).view(np.char.chararray) assert_array_equal(A2, (A % [[1, 2], [3, 4]])) def test_rmod(self): @@ -654,7 +658,7 @@ def test_slice(self): """Regression test for https://github.com/numpy/numpy/issues/5982""" arr = np.array([['abc ', 'def '], ['geh ', 'ijk ']], - dtype='S4').view(np.chararray) + dtype='S4').view(np.char.chararray) sl1 = arr[:] assert_array_equal(sl1, arr) assert_(sl1.base is arr) @@ -672,7 +676,7 @@ def test_empty_indexing(): """Regression test for ticket 1948.""" # Check that indexing a chararray with an empty list/array returns an # empty chararray instead of a chararray with a single empty string in it. - s = np.chararray((4,)) + s = np.char.chararray((4,)) assert_(s[[]].size == 0) diff --git a/numpy/core/tests/test_deprecations.py b/numpy/core/tests/test_deprecations.py index a82d91ebf29b..3a366e6f5371 100644 --- a/numpy/core/tests/test_deprecations.py +++ b/numpy/core/tests/test_deprecations.py @@ -771,3 +771,4 @@ def test_lib_functions_deprecation_call(self): self.assert_deprecated(lambda: in1d([1], [1])) self.assert_deprecated(lambda: row_stack([[]])) self.assert_deprecated(lambda: trapz([1], [1])) + self.assert_deprecated(lambda: np.chararray) diff --git a/numpy/core/tests/test_dtype.py b/numpy/core/tests/test_dtype.py index 2db170d09c4e..fa85d0358c8a 100644 --- a/numpy/core/tests/test_dtype.py +++ b/numpy/core/tests/test_dtype.py @@ -569,7 +569,7 @@ def test_fieldless_views(self): def test_nonstructured_with_object(self): # See gh-23277, the dtype here thinks it contain objects, if the # assert about that fails, the test becomes meaningless (which is OK) - arr = np.recarray((0,), dtype="O") + arr = np.recarray((0,), dtype="O") assert arr.dtype.names is None # no fields assert arr.dtype.hasobject # but claims to contain objects del arr # the deletion failed previously. diff --git a/numpy/core/tests/test_records.py b/numpy/core/tests/test_records.py index 1b6ae7cf4cef..e7823503e88c 100644 --- a/numpy/core/tests/test_records.py +++ b/numpy/core/tests/test_records.py @@ -442,11 +442,13 @@ def test_pickle_void(self): def test_objview_record(self): # https://github.com/numpy/numpy/issues/2599 dt = np.dtype([('foo', 'i8'), ('bar', 'O')]) - r = np.zeros((1,3), dtype=dt).view(np.recarray) + r = np.zeros((1, 3), dtype=dt).view(np.recarray) r.foo = np.array([1, 2, 3]) # TypeError? # https://github.com/numpy/numpy/issues/3256 - ra = np.recarray((2,), dtype=[('x', object), ('y', float), ('z', int)]) + ra = np.recarray( + (2,), dtype=[('x', object), ('y', float), ('z', int)] + ) ra[['x','y']] # TypeError? def test_record_scalar_setitem(self): diff --git a/numpy/core/tests/test_regression.py b/numpy/core/tests/test_regression.py index 6899cb1c4bec..1e588f6ffc79 100644 --- a/numpy/core/tests/test_regression.py +++ b/numpy/core/tests/test_regression.py @@ -378,7 +378,7 @@ def index_tmp(): def test_chararray_rstrip(self): # Ticket #222 - x = np.chararray((1,), 5) + x = np.char.chararray((1,), 5) x[0] = b'a ' x = x.rstrip() assert_equal(x[0], b'a') @@ -2079,7 +2079,7 @@ def test_searchsorted_wrong_dtype(self): a = np.array([('a', 1)], dtype='S1, int') assert_raises(TypeError, np.searchsorted, a, 1.2) # Ticket #2066, similar problem: - dtype = np.format_parser(['i4', 'i4'], [], []) + dtype = np.rec.format_parser(['i4', 'i4'], [], []) a = np.recarray((2,), dtype) a[...] = [(1, 2), (3, 4)] assert_raises(TypeError, np.searchsorted, a, 1) diff --git a/numpy/core/tests/test_strings.py b/numpy/core/tests/test_strings.py index 29a7bb93cadf..7e8b33eab3c2 100644 --- a/numpy/core/tests/test_strings.py +++ b/numpy/core/tests/test_strings.py @@ -64,12 +64,16 @@ def test_string_comparisons(op, ufunc, sym, dtypes, aligned): expected = [op(d1, d2) for d1, d2 in zip(arr.tolist(), arr2.tolist())] assert_array_equal(op(arr, arr2), expected) assert_array_equal(ufunc(arr, arr2), expected) - assert_array_equal(np.compare_chararrays(arr, arr2, sym, False), expected) + assert_array_equal( + np.char.compare_chararrays(arr, arr2, sym, False), expected + ) expected = [op(d2, d1) for d1, d2 in zip(arr.tolist(), arr2.tolist())] assert_array_equal(op(arr2, arr), expected) assert_array_equal(ufunc(arr2, arr), expected) - assert_array_equal(np.compare_chararrays(arr2, arr, sym, False), expected) + assert_array_equal( + np.char.compare_chararrays(arr2, arr, sym, False), expected + ) @pytest.mark.parametrize(["op", "ufunc", "sym"], COMPARISONS) @@ -82,7 +86,9 @@ def test_string_comparisons_empty(op, ufunc, sym, dtypes): expected = np.empty(np.broadcast_shapes(arr.shape, arr2.shape), dtype=bool) assert_array_equal(op(arr, arr2), expected) assert_array_equal(ufunc(arr, arr2), expected) - assert_array_equal(np.compare_chararrays(arr, arr2, sym, False), expected) + assert_array_equal( + np.char.compare_chararrays(arr, arr2, sym, False), expected + ) @pytest.mark.parametrize("str_dt", ["S", "U"]) diff --git a/numpy/lib/_shape_base_impl.py b/numpy/lib/_shape_base_impl.py index 817278edc4a0..076dd67604a6 100644 --- a/numpy/lib/_shape_base_impl.py +++ b/numpy/lib/_shape_base_impl.py @@ -8,6 +8,7 @@ from numpy.core import overrides from numpy.core import vstack, atleast_3d from numpy.core.numeric import normalize_axis_tuple +from numpy.core.overrides import set_module from numpy.core.shape_base import _arrays_for_stack_dispatcher from numpy.lib._index_tricks_impl import ndindex from numpy.matrixlib.defmatrix import matrix # this raises all the right alarm bells @@ -604,7 +605,8 @@ def expand_dims(a, axis): return a.reshape(shape) -# TODO: Remove once deprecation period passes +# NOTE: Remove once deprecation period passes +@set_module("numpy") def row_stack(tup, *, dtype=None, casting="same_kind"): # Deprecated in NumPy 2.0, 2023-08-18 warnings.warn( diff --git a/numpy/lib/recfunctions.py b/numpy/lib/recfunctions.py index 2637f6419d90..f22f4e9ccd3f 100644 --- a/numpy/lib/recfunctions.py +++ b/numpy/lib/recfunctions.py @@ -8,10 +8,11 @@ import itertools import numpy as np import numpy.ma as ma -from numpy import ndarray, recarray +from numpy import ndarray from numpy.ma import MaskedArray from numpy.ma.mrecords import MaskedRecords from numpy.core.overrides import array_function_dispatch +from numpy.core.records import recarray from numpy.lib._iotools import _is_string_like _check_fill_value = np.ma.core._check_fill_value diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py index 9d8784d0fe13..56e48b94b692 100644 --- a/numpy/lib/tests/test_arraysetops.py +++ b/numpy/lib/tests/test_arraysetops.py @@ -694,7 +694,7 @@ def check_all(a, b, i1, i2, c, dt): assert_array_equal(a2_inv, inv) # test for chararrays with return_inverse (gh-5099) - a = np.chararray(5) + a = np.char.chararray(5) a[...] = '' a2, a2_inv = np.unique(a, return_inverse=True) assert_array_equal(a2_inv, np.zeros(5)) diff --git a/numpy/ma/mrecords.py b/numpy/ma/mrecords.py index 1e8103bcf632..82b2ff79c6b4 100644 --- a/numpy/ma/mrecords.py +++ b/numpy/ma/mrecords.py @@ -22,10 +22,10 @@ import numpy as np from numpy import ( - bool_, dtype, ndarray, recarray, array as narray + bool_, dtype, ndarray, array as narray ) from numpy.core.records import ( - fromarrays as recfromarrays, fromrecords as recfromrecords + recarray, fromarrays as recfromarrays, fromrecords as recfromrecords ) _byteorderconv = np.core.records._byteorderconv diff --git a/numpy/ma/tests/test_mrecords.py b/numpy/ma/tests/test_mrecords.py index 761bd77cf0c3..83099a4b7376 100644 --- a/numpy/ma/tests/test_mrecords.py +++ b/numpy/ma/tests/test_mrecords.py @@ -9,11 +9,10 @@ import numpy as np import numpy.ma as ma -from numpy import recarray from numpy.ma import masked, nomask from numpy.testing import temppath from numpy.core.records import ( - fromrecords as recfromrecords, fromarrays as recfromarrays + recarray, fromrecords as recfromrecords, fromarrays as recfromarrays ) from numpy.ma.mrecords import ( MaskedRecords, mrecarray, fromarrays, fromtextfile, fromrecords, diff --git a/numpy/meson.build b/numpy/meson.build index a4509bc33067..e2dc683bfea5 100644 --- a/numpy/meson.build +++ b/numpy/meson.build @@ -293,7 +293,9 @@ pure_subdirs = [ 'polynomial', 'testing', 'tests', - 'typing' + 'typing', + 'rec', + 'char' ] if py.version().version_compare('<3.12') pure_subdirs += 'distutils' diff --git a/numpy/rec/__init__.py b/numpy/rec/__init__.py new file mode 100644 index 000000000000..dd5bd9d16062 --- /dev/null +++ b/numpy/rec/__init__.py @@ -0,0 +1,2 @@ +from numpy.core.records import __all__, __doc__ +from numpy.core.records import * diff --git a/numpy/rec/__init__.pyi b/numpy/rec/__init__.pyi new file mode 100644 index 000000000000..3e5d6713b244 --- /dev/null +++ b/numpy/rec/__init__.pyi @@ -0,0 +1,13 @@ +from numpy.core.records import ( + record as record, + recarray as recarray, + format_parser as format_parser, + fromarrays as fromarrays, + fromrecords as fromrecords, + fromstring as fromstring, + fromfile as fromfile, + array as array +) + +__all__: list[str] +__path__: list[str] diff --git a/numpy/tests/test_public_api.py b/numpy/tests/test_public_api.py index 4aded7fdde6e..6078037aa132 100644 --- a/numpy/tests/test_public_api.py +++ b/numpy/tests/test_public_api.py @@ -31,15 +31,11 @@ def check_dir(module, module_name=None): def test_numpy_namespace(): - # None of these objects are publicly documented to be part of the main - # NumPy namespace (some are useful though, others need to be cleaned up) - undocumented = { - 'compare_chararrays': 'numpy.core._multiarray_umath.compare_chararrays', + # We override dir to not show these members + allowlist = { + 'recarray': 'numpy.rec.recarray', 'show_config': 'numpy.__config__.show', - 'row_stack': 'numpy.lib._shape_base_impl.row_stack' } - # We override dir to not show these members - allowlist = undocumented bad_results = check_dir(np) # pytest gives better error messages with the builtin assert than with # assert_equal diff --git a/numpy/typing/__init__.py b/numpy/typing/__init__.py index fa8e86af83d6..0388a2009f4b 100644 --- a/numpy/typing/__init__.py +++ b/numpy/typing/__init__.py @@ -139,7 +139,7 @@ functions in general, can be specified in one of two ways: * Directly via the ``dtype`` argument. -* With up to five helper arguments that operate via `numpy.format_parser`: +* With up to five helper arguments that operate via `numpy.rec.format_parser`: ``formats``, ``names``, ``titles``, ``aligned`` and ``byteorder``. These two approaches are currently typed as being mutually exclusive, diff --git a/numpy/typing/tests/data/fail/chararray.pyi b/numpy/typing/tests/data/fail/chararray.pyi index ebc182ec2f04..d334f689d121 100644 --- a/numpy/typing/tests/data/fail/chararray.pyi +++ b/numpy/typing/tests/data/fail/chararray.pyi @@ -1,8 +1,8 @@ import numpy as np from typing import Any -AR_U: np.chararray[Any, np.dtype[np.str_]] -AR_S: np.chararray[Any, np.dtype[np.bytes_]] +AR_U: np.char.chararray[Any, np.dtype[np.str_]] +AR_S: np.char.chararray[Any, np.dtype[np.bytes_]] AR_S.encode() # E: Invalid self argument AR_U.decode() # E: Invalid self argument diff --git a/numpy/typing/tests/data/fail/multiarray.pyi b/numpy/typing/tests/data/fail/multiarray.pyi index 16cc4a3e9770..ccf020e0cd74 100644 --- a/numpy/typing/tests/data/fail/multiarray.pyi +++ b/numpy/typing/tests/data/fail/multiarray.pyi @@ -43,7 +43,7 @@ np.busday_offset("2012", 10) # E: No overload variant np.datetime_as_string("2012") # E: No overload variant -np.compare_chararrays("a", b"a", "==", False) # E: No overload variant +np.char.compare_chararrays("a", b"a", "==", False) # E: No overload variant np.nested_iters([AR_i8, AR_i8]) # E: Missing positional argument np.nested_iters([AR_i8, AR_i8], 0) # E: incompatible type diff --git a/numpy/typing/tests/data/reveal/char.pyi b/numpy/typing/tests/data/reveal/char.pyi index e15ed0801a0d..86d4e5af0034 100644 --- a/numpy/typing/tests/data/reveal/char.pyi +++ b/numpy/typing/tests/data/reveal/char.pyi @@ -139,16 +139,16 @@ assert_type(np.char.isupper(AR_S), npt.NDArray[np.bool_]) assert_type(np.char.str_len(AR_U), npt.NDArray[np.int_]) assert_type(np.char.str_len(AR_S), npt.NDArray[np.int_]) -assert_type(np.char.array(AR_U), np.chararray[Any, np.dtype[np.str_]]) -assert_type(np.char.array(AR_S, order="K"), np.chararray[Any, np.dtype[np.bytes_]]) -assert_type(np.char.array("bob", copy=True), np.chararray[Any, np.dtype[np.str_]]) -assert_type(np.char.array(b"bob", itemsize=5), np.chararray[Any, np.dtype[np.bytes_]]) -assert_type(np.char.array(1, unicode=False), np.chararray[Any, np.dtype[np.bytes_]]) -assert_type(np.char.array(1, unicode=True), np.chararray[Any, np.dtype[np.str_]]) - -assert_type(np.char.asarray(AR_U), np.chararray[Any, np.dtype[np.str_]]) -assert_type(np.char.asarray(AR_S, order="K"), np.chararray[Any, np.dtype[np.bytes_]]) -assert_type(np.char.asarray("bob"), np.chararray[Any, np.dtype[np.str_]]) -assert_type(np.char.asarray(b"bob", itemsize=5), np.chararray[Any, np.dtype[np.bytes_]]) -assert_type(np.char.asarray(1, unicode=False), np.chararray[Any, np.dtype[np.bytes_]]) -assert_type(np.char.asarray(1, unicode=True), np.chararray[Any, np.dtype[np.str_]]) +assert_type(np.char.array(AR_U), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(np.char.array(AR_S, order="K"), np.char.chararray[Any, np.dtype[np.bytes_]]) +assert_type(np.char.array("bob", copy=True), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(np.char.array(b"bob", itemsize=5), np.char.chararray[Any, np.dtype[np.bytes_]]) +assert_type(np.char.array(1, unicode=False), np.char.chararray[Any, np.dtype[np.bytes_]]) +assert_type(np.char.array(1, unicode=True), np.char.chararray[Any, np.dtype[np.str_]]) + +assert_type(np.char.asarray(AR_U), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(np.char.asarray(AR_S, order="K"), np.char.chararray[Any, np.dtype[np.bytes_]]) +assert_type(np.char.asarray("bob"), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(np.char.asarray(b"bob", itemsize=5), np.char.chararray[Any, np.dtype[np.bytes_]]) +assert_type(np.char.asarray(1, unicode=False), np.char.chararray[Any, np.dtype[np.bytes_]]) +assert_type(np.char.asarray(1, unicode=True), np.char.chararray[Any, np.dtype[np.str_]]) diff --git a/numpy/typing/tests/data/reveal/chararray.pyi b/numpy/typing/tests/data/reveal/chararray.pyi index 4bcbeda2e6ad..2f9075d619c3 100644 --- a/numpy/typing/tests/data/reveal/chararray.pyi +++ b/numpy/typing/tests/data/reveal/chararray.pyi @@ -9,8 +9,8 @@ if sys.version_info >= (3, 11): else: from typing_extensions import assert_type -AR_U: np.chararray[Any, np.dtype[np.str_]] -AR_S: np.chararray[Any, np.dtype[np.bytes_]] +AR_U: np.char.chararray[Any, np.dtype[np.str_]] +AR_S: np.char.chararray[Any, np.dtype[np.bytes_]] assert_type(AR_U == AR_U, npt.NDArray[np.bool_]) assert_type(AR_S == AR_S, npt.NDArray[np.bool_]) @@ -30,46 +30,46 @@ assert_type(AR_S > AR_S, npt.NDArray[np.bool_]) assert_type(AR_U < AR_U, npt.NDArray[np.bool_]) assert_type(AR_S < AR_S, npt.NDArray[np.bool_]) -assert_type(AR_U * 5, np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S * [5], np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U * 5, np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S * [5], np.char.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U % "test", np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S % b"test", np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U % "test", np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S % b"test", np.char.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.capitalize(), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.capitalize(), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.capitalize(), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.capitalize(), np.char.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.center(5), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.center([2, 3, 4], b"a"), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.center(5), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.center([2, 3, 4], b"a"), np.char.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.encode(), np.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_S.decode(), np.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_U.encode(), np.char.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_S.decode(), np.char.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_U.expandtabs(), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.expandtabs(tabsize=4), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.expandtabs(), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.expandtabs(tabsize=4), np.char.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.join("_"), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.join([b"_", b""]), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.join("_"), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.join([b"_", b""]), np.char.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.ljust(5), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.ljust([4, 3, 1], fillchar=[b"a", b"b", b"c"]), np.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.rjust(5), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.rjust([4, 3, 1], fillchar=[b"a", b"b", b"c"]), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.ljust(5), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.ljust([4, 3, 1], fillchar=[b"a", b"b", b"c"]), np.char.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.rjust(5), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.rjust([4, 3, 1], fillchar=[b"a", b"b", b"c"]), np.char.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.lstrip(), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.lstrip(chars=b"_"), np.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.rstrip(), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.rstrip(chars=b"_"), np.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.strip(), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.strip(chars=b"_"), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.lstrip(), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.lstrip(chars=b"_"), np.char.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.rstrip(), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.rstrip(chars=b"_"), np.char.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.strip(), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.strip(chars=b"_"), np.char.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.partition("\n"), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.partition([b"a", b"b", b"c"]), np.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.rpartition("\n"), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.rpartition([b"a", b"b", b"c"]), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.partition("\n"), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.partition([b"a", b"b", b"c"]), np.char.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.rpartition("\n"), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.rpartition([b"a", b"b", b"c"]), np.char.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.replace("_", "-"), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.replace([b"_", b""], [b"a", b"b"]), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.replace("_", "-"), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.replace([b"_", b""], [b"a", b"b"]), np.char.chararray[Any, np.dtype[np.bytes_]]) assert_type(AR_U.split("_"), npt.NDArray[np.object_]) assert_type(AR_S.split(maxsplit=[1, 2, 3]), npt.NDArray[np.object_]) @@ -79,17 +79,17 @@ assert_type(AR_S.rsplit(maxsplit=[1, 2, 3]), npt.NDArray[np.object_]) assert_type(AR_U.splitlines(), npt.NDArray[np.object_]) assert_type(AR_S.splitlines(keepends=[True, True, False]), npt.NDArray[np.object_]) -assert_type(AR_U.swapcase(), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.swapcase(), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.swapcase(), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.swapcase(), np.char.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.title(), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.title(), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.title(), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.title(), np.char.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.upper(), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.upper(), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.upper(), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.upper(), np.char.chararray[Any, np.dtype[np.bytes_]]) -assert_type(AR_U.zfill(5), np.chararray[Any, np.dtype[np.str_]]) -assert_type(AR_S.zfill([2, 3, 4]), np.chararray[Any, np.dtype[np.bytes_]]) +assert_type(AR_U.zfill(5), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(AR_S.zfill([2, 3, 4]), np.char.chararray[Any, np.dtype[np.bytes_]]) assert_type(AR_U.count("a", start=[1, 2, 3]), npt.NDArray[np.int_]) assert_type(AR_S.count([b"a", b"b", b"c"], end=9), npt.NDArray[np.int_]) diff --git a/numpy/typing/tests/data/reveal/lib_function_base.pyi b/numpy/typing/tests/data/reveal/lib_function_base.pyi index 670ac9833d04..6666c2407a1f 100644 --- a/numpy/typing/tests/data/reveal/lib_function_base.pyi +++ b/numpy/typing/tests/data/reveal/lib_function_base.pyi @@ -23,7 +23,7 @@ AR_M: npt.NDArray[np.datetime64] AR_O: npt.NDArray[np.object_] AR_b: npt.NDArray[np.bool_] AR_U: npt.NDArray[np.str_] -CHAR_AR_U: np.chararray[Any, np.dtype[np.str_]] +CHAR_AR_U: np.char.chararray[Any, np.dtype[np.str_]] def func(*args: Any, **kwargs: Any) -> Any: ... @@ -73,8 +73,8 @@ assert_type(np.select([AR_f8], [AR_f8]), npt.NDArray[Any]) assert_type(np.copy(AR_LIKE_f8), npt.NDArray[Any]) assert_type(np.copy(AR_U), npt.NDArray[np.str_]) assert_type(np.copy(CHAR_AR_U), np.ndarray[Any, Any]) -assert_type(np.copy(CHAR_AR_U, "K", subok=True), np.chararray[Any, np.dtype[np.str_]]) -assert_type(np.copy(CHAR_AR_U, subok=True), np.chararray[Any, np.dtype[np.str_]]) +assert_type(np.copy(CHAR_AR_U, "K", subok=True), np.char.chararray[Any, np.dtype[np.str_]]) +assert_type(np.copy(CHAR_AR_U, subok=True), np.char.chararray[Any, np.dtype[np.str_]]) assert_type(np.gradient(AR_f8, axis=None), Any) assert_type(np.gradient(AR_LIKE_f8, edge_order=2), Any) diff --git a/numpy/typing/tests/data/reveal/multiarray.pyi b/numpy/typing/tests/data/reveal/multiarray.pyi index ec8a5234cb24..6afc1dc57e0a 100644 --- a/numpy/typing/tests/data/reveal/multiarray.pyi +++ b/numpy/typing/tests/data/reveal/multiarray.pyi @@ -134,8 +134,8 @@ assert_type(np.datetime_as_string(AR_M), npt.NDArray[np.str_]) assert_type(np.busdaycalendar(holidays=date_seq), np.busdaycalendar) assert_type(np.busdaycalendar(holidays=[M]), np.busdaycalendar) -assert_type(np.compare_chararrays("a", "b", "!=", rstrip=False), npt.NDArray[np.bool_]) -assert_type(np.compare_chararrays(b"a", b"a", "==", True), npt.NDArray[np.bool_]) +assert_type(np.char.compare_chararrays("a", "b", "!=", rstrip=False), npt.NDArray[np.bool_]) +assert_type(np.char.compare_chararrays(b"a", b"a", "==", True), npt.NDArray[np.bool_]) assert_type(np.nested_iters([AR_i8, AR_i8], [[0], [1]], flags=["c_index"]), tuple[np.nditer, ...]) assert_type(np.nested_iters([AR_i8, AR_i8], [[0], [1]], op_flags=[["readonly", "readonly"]]), tuple[np.nditer, ...]) diff --git a/numpy/typing/tests/data/reveal/rec.pyi b/numpy/typing/tests/data/reveal/rec.pyi index 37408d839f51..1c1558bf3462 100644 --- a/numpy/typing/tests/data/reveal/rec.pyi +++ b/numpy/typing/tests/data/reveal/rec.pyi @@ -14,17 +14,16 @@ AR_i8: npt.NDArray[np.int64] REC_AR_V: np.recarray[Any, np.dtype[np.record]] AR_LIST: list[npt.NDArray[np.int64]] -format_parser: np.format_parser record: np.record file_obj: io.BufferedIOBase -assert_type(np.format_parser( +assert_type(np.rec.format_parser( formats=[np.float64, np.int64, np.bool_], names=["f8", "i8", "?"], titles=None, aligned=True, -), np.format_parser) -assert_type(format_parser.dtype, np.dtype[np.void]) +), np.rec.format_parser) +assert_type(np.rec.format_parser.dtype, np.dtype[np.void]) assert_type(record.field_a, Any) assert_type(record.field_b, Any) @@ -74,7 +73,11 @@ assert_type( np.recarray[Any, np.dtype[np.record]], ) -assert_type(np.rec.fromrecords((1, 1.5)), np.recarray[Any, np.dtype[np.record]]) +assert_type( + np.rec.fromrecords((1, 1.5)), + np.recarray[Any, np.dtype[np.record]] +) + assert_type( np.rec.fromrecords( [(1, 1.5)], @@ -82,6 +85,7 @@ assert_type( ), np.recarray[Any, np.dtype[np.record]], ) + assert_type( np.rec.fromrecords( REC_AR_V, @@ -98,6 +102,7 @@ assert_type( ), np.recarray[Any, np.dtype[np.record]], ) + assert_type( np.rec.fromstring( REC_AR_V,