diff options
Diffstat (limited to 'numpy')
| -rw-r--r-- | numpy/__init__.pyi | 6 | ||||
| -rw-r--r-- | numpy/_typing/_array_like.py | 6 | ||||
| -rw-r--r-- | numpy/_typing/_dtype_like.py | 2 | ||||
| -rw-r--r-- | numpy/_typing/_nested_sequence.py | 2 | ||||
| -rw-r--r-- | numpy/array_api/__init__.py | 4 | ||||
| -rw-r--r-- | numpy/core/defchararray.py | 9 | ||||
| -rw-r--r-- | numpy/core/fromnumeric.py | 10 | ||||
| -rw-r--r-- | numpy/lib/utils.py | 8 | ||||
| -rw-r--r-- | numpy/polynomial/chebyshev.py | 3 | ||||
| -rw-r--r-- | numpy/typing/tests/data/fail/scalars.pyi | 2 | ||||
| -rw-r--r-- | numpy/typing/tests/data/reveal/ctypeslib.pyi | 2 | ||||
| -rw-r--r-- | numpy/typing/tests/data/reveal/flatiter.pyi | 2 | ||||
| -rw-r--r-- | numpy/typing/tests/data/reveal/ndarray_misc.pyi | 4 | ||||
| -rw-r--r-- | numpy/typing/tests/test_runtime.py | 33 |
14 files changed, 76 insertions, 17 deletions
diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi index 58ec814f4..d9b50b7b4 100644 --- a/numpy/__init__.pyi +++ b/numpy/__init__.pyi @@ -1551,6 +1551,12 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeType, _DType_co]): ) -> ndarray[_ShapeType2, _DType]: ... @overload + def __getitem__(self, key: ( + NDArray[integer[Any]] + | NDArray[bool_] + | tuple[NDArray[integer[Any]] | NDArray[bool_], ...] + )) -> ndarray[Any, _DType_co]: ... + @overload def __getitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...]) -> Any: ... @overload def __getitem__(self, key: ( diff --git a/numpy/_typing/_array_like.py b/numpy/_typing/_array_like.py index 2e5684b0b..67d67ce19 100644 --- a/numpy/_typing/_array_like.py +++ b/numpy/_typing/_array_like.py @@ -3,7 +3,7 @@ from __future__ import annotations # NOTE: Import `Sequence` from `typing` as we it is needed for a type-alias, # not an annotation from collections.abc import Collection, Callable -from typing import Any, Sequence, Protocol, Union, TypeVar +from typing import Any, Sequence, Protocol, Union, TypeVar, runtime_checkable from numpy import ( ndarray, dtype, @@ -33,10 +33,12 @@ _DType_co = TypeVar("_DType_co", covariant=True, bound="dtype[Any]") # array. # Concrete implementations of the protocol are responsible for adding # any and all remaining overloads +@runtime_checkable class _SupportsArray(Protocol[_DType_co]): def __array__(self) -> ndarray[Any, _DType_co]: ... +@runtime_checkable class _SupportsArrayFunc(Protocol): """A protocol class representing `~class.__array_function__`.""" def __array_function__( @@ -146,7 +148,7 @@ _ArrayLikeInt = _DualArrayLike[ # Used as the first overload, should only match NDArray[Any], # not any actual types. # https://github.com/numpy/numpy/pull/22193 -class _UnknownType: +class _UnknownType: ... diff --git a/numpy/_typing/_dtype_like.py b/numpy/_typing/_dtype_like.py index b705d82fd..e92e17dd2 100644 --- a/numpy/_typing/_dtype_like.py +++ b/numpy/_typing/_dtype_like.py @@ -8,6 +8,7 @@ from typing import ( TypeVar, Protocol, TypedDict, + runtime_checkable, ) import numpy as np @@ -80,6 +81,7 @@ class _DTypeDict(_DTypeDictBase, total=False): # A protocol for anything with the dtype attribute +@runtime_checkable class _SupportsDType(Protocol[_DType_co]): @property def dtype(self) -> _DType_co: ... diff --git a/numpy/_typing/_nested_sequence.py b/numpy/_typing/_nested_sequence.py index 360c0f1b2..789bf3844 100644 --- a/numpy/_typing/_nested_sequence.py +++ b/numpy/_typing/_nested_sequence.py @@ -8,6 +8,7 @@ from typing import ( overload, TypeVar, Protocol, + runtime_checkable, ) __all__ = ["_NestedSequence"] @@ -15,6 +16,7 @@ __all__ = ["_NestedSequence"] _T_co = TypeVar("_T_co", covariant=True) +@runtime_checkable class _NestedSequence(Protocol[_T_co]): """A protocol for representing nested sequences. diff --git a/numpy/array_api/__init__.py b/numpy/array_api/__init__.py index bbe2fdce2..5e58ee0a8 100644 --- a/numpy/array_api/__init__.py +++ b/numpy/array_api/__init__.py @@ -121,7 +121,9 @@ warnings.warn( "The numpy.array_api submodule is still experimental. See NEP 47.", stacklevel=2 ) -__all__ = [] +__array_api_version__ = "2021.12" + +__all__ = ["__array_api_version__"] from ._constants import e, inf, nan, pi diff --git a/numpy/core/defchararray.py b/numpy/core/defchararray.py index 0a4b091a8..6750e497a 100644 --- a/numpy/core/defchararray.py +++ b/numpy/core/defchararray.py @@ -1250,7 +1250,16 @@ def replace(a, old, new, count=None): See Also -------- str.replace + + Examples + -------- + >>> a = np.array(["That is a mango", "Monkeys eat mangos"]) + >>> np.char.replace(a, 'mango', 'banana') + array(['That is a banana', 'Monkeys eat bananas'], dtype='<U19') + >>> a = np.array(["The dish is fresh", "This is it"]) + >>> np.char.replace(a, 'is', 'was') + array(['The dwash was fresh', 'Thwas was it'], dtype='<U19') """ return _to_string_or_unicode_array( _vec_string( diff --git a/numpy/core/fromnumeric.py b/numpy/core/fromnumeric.py index f4c7af88a..89d731e32 100644 --- a/numpy/core/fromnumeric.py +++ b/numpy/core/fromnumeric.py @@ -2750,8 +2750,9 @@ def amax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue, ------- amax : ndarray or scalar Maximum of `a`. If `axis` is None, the result is a scalar value. - If `axis` is given, the result is an array of dimension - ``a.ndim - 1``. + If `axis` is an int, the result is an array of dimension + ``a.ndim - 1``. If `axis` is a tuple, the result is an array of + dimension ``a.ndim - len(axis)``. See Also -------- @@ -2875,8 +2876,9 @@ def amin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue, ------- amin : ndarray or scalar Minimum of `a`. If `axis` is None, the result is a scalar value. - If `axis` is given, the result is an array of dimension - ``a.ndim - 1``. + If `axis` is an int, the result is an array of dimension + ``a.ndim - 1``. If `axis` is a tuple, the result is an array of + dimension ``a.ndim - len(axis)``. See Also -------- diff --git a/numpy/lib/utils.py b/numpy/lib/utils.py index 497827e75..f9d29e89d 100644 --- a/numpy/lib/utils.py +++ b/numpy/lib/utils.py @@ -972,8 +972,12 @@ def _lookfor_generate_cache(module, import_modules, regenerate): finally: sys.stdout = old_stdout sys.stderr = old_stderr - # Catch SystemExit, too - except (Exception, SystemExit): + except KeyboardInterrupt: + # Assume keyboard interrupt came from a user + raise + except BaseException: + # Ignore also SystemExit and pytests.importorskip + # `Skipped` (these are BaseExceptions; gh-22345) continue for n, v in _getmembers(item): diff --git a/numpy/polynomial/chebyshev.py b/numpy/polynomial/chebyshev.py index 5c595bcf6..c663ffab0 100644 --- a/numpy/polynomial/chebyshev.py +++ b/numpy/polynomial/chebyshev.py @@ -1959,7 +1959,8 @@ def chebpts2(npts): Chebyshev points of the second kind. The Chebyshev points of the second kind are the points ``cos(x)``, - where ``x = [pi*k/(npts - 1) for k in range(npts)]``. + where ``x = [pi*k/(npts - 1) for k in range(npts)]`` sorted in ascending + order. Parameters ---------- diff --git a/numpy/typing/tests/data/fail/scalars.pyi b/numpy/typing/tests/data/fail/scalars.pyi index 964470538..c24f9e479 100644 --- a/numpy/typing/tests/data/fail/scalars.pyi +++ b/numpy/typing/tests/data/fail/scalars.pyi @@ -70,8 +70,6 @@ np.timedelta64(value=0) # E: Unexpected keyword argument np.bytes_(b"hello", encoding='utf-8') # E: No overload variant np.str_("hello", encoding='utf-8') # E: No overload variant -complex(np.bytes_("1")) # E: No overload variant - f8.item(1) # E: incompatible type f8.item((0, 1)) # E: incompatible type f8.squeeze(axis=1) # E: incompatible type diff --git a/numpy/typing/tests/data/reveal/ctypeslib.pyi b/numpy/typing/tests/data/reveal/ctypeslib.pyi index ccbdfe36e..2d30de3d1 100644 --- a/numpy/typing/tests/data/reveal/ctypeslib.pyi +++ b/numpy/typing/tests/data/reveal/ctypeslib.pyi @@ -20,7 +20,7 @@ AR_double: npt.NDArray[np.double] AR_longdouble: npt.NDArray[np.longdouble] AR_void: npt.NDArray[np.void] -pointer: ctypes.pointer[Any] +pointer: ctypes._Pointer[Any] reveal_type(np.ctypeslib.c_intp()) # E: {c_intp} diff --git a/numpy/typing/tests/data/reveal/flatiter.pyi b/numpy/typing/tests/data/reveal/flatiter.pyi index 0f0758175..8d3e80632 100644 --- a/numpy/typing/tests/data/reveal/flatiter.pyi +++ b/numpy/typing/tests/data/reveal/flatiter.pyi @@ -7,7 +7,7 @@ reveal_type(a.base) # E: ndarray[Any, dtype[str_]] reveal_type(a.copy()) # E: ndarray[Any, dtype[str_]] reveal_type(a.coords) # E: tuple[builtins.int, ...] reveal_type(a.index) # E: int -reveal_type(iter(a)) # E: flatiter[ndarray[Any, dtype[str_]]] +reveal_type(iter(a)) # E: Any reveal_type(next(a)) # E: str_ reveal_type(a[0]) # E: str_ reveal_type(a[[0, 1, 2]]) # E: ndarray[Any, dtype[str_]] diff --git a/numpy/typing/tests/data/reveal/ndarray_misc.pyi b/numpy/typing/tests/data/reveal/ndarray_misc.pyi index 779d0909b..03fea72dc 100644 --- a/numpy/typing/tests/data/reveal/ndarray_misc.pyi +++ b/numpy/typing/tests/data/reveal/ndarray_misc.pyi @@ -200,8 +200,8 @@ reveal_type(AR_f8.__array_wrap__(B)) # E: ndarray[Any, dtype[object_]] reveal_type(AR_V[0]) # E: Any reveal_type(AR_V[0, 0]) # E: Any -reveal_type(AR_V[AR_i8]) # E: Any -reveal_type(AR_V[AR_i8, AR_i8]) # E: Any +reveal_type(AR_V[AR_i8]) # E: ndarray[Any, dtype[void]] +reveal_type(AR_V[AR_i8, AR_i8]) # E: ndarray[Any, dtype[void]] reveal_type(AR_V[AR_i8, None]) # E: ndarray[Any, dtype[void]] reveal_type(AR_V[0, ...]) # E: ndarray[Any, dtype[void]] reveal_type(AR_V[[0]]) # E: ndarray[Any, dtype[void]] diff --git a/numpy/typing/tests/test_runtime.py b/numpy/typing/tests/test_runtime.py index 5b5df49dc..44d069006 100644 --- a/numpy/typing/tests/test_runtime.py +++ b/numpy/typing/tests/test_runtime.py @@ -3,11 +3,19 @@ from __future__ import annotations import sys -from typing import get_type_hints, Union, NamedTuple, get_args, get_origin +from typing import ( + get_type_hints, + Union, + NamedTuple, + get_args, + get_origin, + Any, +) import pytest import numpy as np import numpy.typing as npt +import numpy._typing as _npt class TypeTup(NamedTuple): @@ -80,3 +88,26 @@ def test_keys() -> None: keys = TYPES.keys() ref = set(npt.__all__) assert keys == ref + + +PROTOCOLS: dict[str, tuple[type[Any], object]] = { + "_SupportsDType": (_npt._SupportsDType, np.int64(1)), + "_SupportsArray": (_npt._SupportsArray, np.arange(10)), + "_SupportsArrayFunc": (_npt._SupportsArrayFunc, np.arange(10)), + "_NestedSequence": (_npt._NestedSequence, [1]), +} + + +@pytest.mark.parametrize("cls,obj", PROTOCOLS.values(), ids=PROTOCOLS.keys()) +class TestRuntimeProtocol: + def test_isinstance(self, cls: type[Any], obj: object) -> None: + assert isinstance(obj, cls) + assert not isinstance(None, cls) + + def test_issubclass(self, cls: type[Any], obj: object) -> None: + if cls is _npt._SupportsDType: + pytest.xfail( + "Protocols with non-method members don't support issubclass()" + ) + assert issubclass(type(obj), cls) + assert not issubclass(type(None), cls) |
