summaryrefslogtreecommitdiff
path: root/numpy/_typing
diff options
context:
space:
mode:
Diffstat (limited to 'numpy/_typing')
-rw-r--r--numpy/_typing/__init__.py6
-rw-r--r--numpy/_typing/_add_docstring.py2
-rw-r--r--numpy/_typing/_array_like.py58
-rw-r--r--numpy/_typing/_callable.pyi2
-rw-r--r--numpy/_typing/_dtype_like.py103
-rw-r--r--numpy/_typing/_extended_precision.py40
-rw-r--r--numpy/_typing/_generic_alias.py245
-rw-r--r--numpy/_typing/_nested_sequence.py2
-rw-r--r--numpy/_typing/_scalars.py14
-rw-r--r--numpy/_typing/_shape.py5
10 files changed, 108 insertions, 369 deletions
diff --git a/numpy/_typing/__init__.py b/numpy/_typing/__init__.py
index a4e763050..29922d958 100644
--- a/numpy/_typing/__init__.py
+++ b/numpy/_typing/__init__.py
@@ -180,6 +180,7 @@ from ._dtype_like import (
_DTypeLikeComplex_co as _DTypeLikeComplex_co,
)
from ._array_like import (
+ NDArray as NDArray,
ArrayLike as ArrayLike,
_ArrayLike as _ArrayLike,
_FiniteNestedSequence as _FiniteNestedSequence,
@@ -201,11 +202,6 @@ from ._array_like import (
_ArrayLikeUnknown as _ArrayLikeUnknown,
_UnknownType as _UnknownType,
)
-from ._generic_alias import (
- NDArray as NDArray,
- _DType as _DType,
- _GenericAlias as _GenericAlias,
-)
if TYPE_CHECKING:
from ._ufunc import (
diff --git a/numpy/_typing/_add_docstring.py b/numpy/_typing/_add_docstring.py
index 10d77f516..f84d19271 100644
--- a/numpy/_typing/_add_docstring.py
+++ b/numpy/_typing/_add_docstring.py
@@ -3,7 +3,7 @@
import re
import textwrap
-from ._generic_alias import NDArray
+from ._array_like import NDArray
_docstrings_list = []
diff --git a/numpy/_typing/_array_like.py b/numpy/_typing/_array_like.py
index 67d67ce19..cba6fffaf 100644
--- a/numpy/_typing/_array_like.py
+++ b/numpy/_typing/_array_like.py
@@ -1,9 +1,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, runtime_checkable
+from collections.abc import Collection, Callable, Sequence
+from typing import Any, Protocol, Union, TypeVar, runtime_checkable
from numpy import (
ndarray,
dtype,
@@ -25,8 +23,11 @@ from ._nested_sequence import _NestedSequence
_T = TypeVar("_T")
_ScalarType = TypeVar("_ScalarType", bound=generic)
-_DType = TypeVar("_DType", bound="dtype[Any]")
-_DType_co = TypeVar("_DType_co", covariant=True, bound="dtype[Any]")
+_ScalarType_co = TypeVar("_ScalarType_co", bound=generic, covariant=True)
+_DType = TypeVar("_DType", bound=dtype[Any])
+_DType_co = TypeVar("_DType_co", covariant=True, bound=dtype[Any])
+
+NDArray = ndarray[Any, dtype[_ScalarType_co]]
# The `_SupportsArray` protocol only cares about the default dtype
# (i.e. `dtype=None` or no `dtype` parameter at all) of the to-be returned
@@ -61,8 +62,8 @@ _FiniteNestedSequence = Union[
# A subset of `npt.ArrayLike` that can be parametrized w.r.t. `np.generic`
_ArrayLike = Union[
- _SupportsArray["dtype[_ScalarType]"],
- _NestedSequence[_SupportsArray["dtype[_ScalarType]"]],
+ _SupportsArray[dtype[_ScalarType]],
+ _NestedSequence[_SupportsArray[dtype[_ScalarType]]],
]
# A union representing array-like objects; consists of two typevars:
@@ -83,64 +84,69 @@ _DualArrayLike = Union[
#
# https://github.com/python/typing/issues/593
ArrayLike = _DualArrayLike[
- dtype,
+ dtype[Any],
Union[bool, int, float, complex, str, bytes],
]
# `ArrayLike<X>_co`: array-like objects that can be coerced into `X`
# given the casting rules `same_kind`
_ArrayLikeBool_co = _DualArrayLike[
- "dtype[bool_]",
+ dtype[bool_],
bool,
]
_ArrayLikeUInt_co = _DualArrayLike[
- "dtype[Union[bool_, unsignedinteger[Any]]]",
+ dtype[Union[bool_, unsignedinteger[Any]]],
bool,
]
_ArrayLikeInt_co = _DualArrayLike[
- "dtype[Union[bool_, integer[Any]]]",
+ dtype[Union[bool_, integer[Any]]],
Union[bool, int],
]
_ArrayLikeFloat_co = _DualArrayLike[
- "dtype[Union[bool_, integer[Any], floating[Any]]]",
+ dtype[Union[bool_, integer[Any], floating[Any]]],
Union[bool, int, float],
]
_ArrayLikeComplex_co = _DualArrayLike[
- "dtype[Union[bool_, integer[Any], floating[Any], complexfloating[Any, Any]]]",
+ dtype[Union[
+ bool_,
+ integer[Any],
+ floating[Any],
+ complexfloating[Any, Any],
+ ]],
Union[bool, int, float, complex],
]
_ArrayLikeNumber_co = _DualArrayLike[
- "dtype[Union[bool_, number[Any]]]",
+ dtype[Union[bool_, number[Any]]],
Union[bool, int, float, complex],
]
_ArrayLikeTD64_co = _DualArrayLike[
- "dtype[Union[bool_, integer[Any], timedelta64]]",
+ dtype[Union[bool_, integer[Any], timedelta64]],
Union[bool, int],
]
_ArrayLikeDT64_co = Union[
- _SupportsArray["dtype[datetime64]"],
- _NestedSequence[_SupportsArray["dtype[datetime64]"]],
+ _SupportsArray[dtype[datetime64]],
+ _NestedSequence[_SupportsArray[dtype[datetime64]]],
]
_ArrayLikeObject_co = Union[
- _SupportsArray["dtype[object_]"],
- _NestedSequence[_SupportsArray["dtype[object_]"]],
+ _SupportsArray[dtype[object_]],
+ _NestedSequence[_SupportsArray[dtype[object_]]],
]
_ArrayLikeVoid_co = Union[
- _SupportsArray["dtype[void]"],
- _NestedSequence[_SupportsArray["dtype[void]"]],
+ _SupportsArray[dtype[void]],
+ _NestedSequence[_SupportsArray[dtype[void]]],
]
_ArrayLikeStr_co = _DualArrayLike[
- "dtype[str_]",
+ dtype[str_],
str,
]
_ArrayLikeBytes_co = _DualArrayLike[
- "dtype[bytes_]",
+ dtype[bytes_],
bytes,
]
_ArrayLikeInt = _DualArrayLike[
- "dtype[integer[Any]]",
+ dtype[integer[Any]],
int,
]
@@ -153,6 +159,6 @@ class _UnknownType:
_ArrayLikeUnknown = _DualArrayLike[
- "dtype[_UnknownType]",
+ dtype[_UnknownType],
_UnknownType,
]
diff --git a/numpy/_typing/_callable.pyi b/numpy/_typing/_callable.pyi
index 5dfe9e7c2..ee818e905 100644
--- a/numpy/_typing/_callable.pyi
+++ b/numpy/_typing/_callable.pyi
@@ -43,7 +43,7 @@ from ._scalars import (
_NumberLike_co,
)
from . import NBitBase
-from ._generic_alias import NDArray
+from ._array_like import NDArray
from ._nested_sequence import _NestedSequence
_T1 = TypeVar("_T1")
diff --git a/numpy/_typing/_dtype_like.py b/numpy/_typing/_dtype_like.py
index e92e17dd2..207a99c56 100644
--- a/numpy/_typing/_dtype_like.py
+++ b/numpy/_typing/_dtype_like.py
@@ -1,10 +1,8 @@
+from collections.abc import Sequence
from typing import (
Any,
- List,
Sequence,
- Tuple,
Union,
- Type,
TypeVar,
Protocol,
TypedDict,
@@ -14,7 +12,6 @@ from typing import (
import numpy as np
from ._shape import _ShapeLike
-from ._generic_alias import _DType as DType
from ._char_codes import (
_BoolCodes,
@@ -59,7 +56,7 @@ from ._char_codes import (
)
_SCT = TypeVar("_SCT", bound=np.generic)
-_DType_co = TypeVar("_DType_co", covariant=True, bound=DType[Any])
+_DType_co = TypeVar("_DType_co", covariant=True, bound=np.dtype[Any])
_DTypeLikeNested = Any # TODO: wait for support for recursive types
@@ -89,41 +86,41 @@ class _SupportsDType(Protocol[_DType_co]):
# A subset of `npt.DTypeLike` that can be parametrized w.r.t. `np.generic`
_DTypeLike = Union[
- "np.dtype[_SCT]",
- Type[_SCT],
- _SupportsDType["np.dtype[_SCT]"],
+ np.dtype[_SCT],
+ type[_SCT],
+ _SupportsDType[np.dtype[_SCT]],
]
# Would create a dtype[np.void]
_VoidDTypeLike = Union[
# (flexible_dtype, itemsize)
- Tuple[_DTypeLikeNested, int],
+ tuple[_DTypeLikeNested, int],
# (fixed_dtype, shape)
- Tuple[_DTypeLikeNested, _ShapeLike],
+ tuple[_DTypeLikeNested, _ShapeLike],
# [(field_name, field_dtype, field_shape), ...]
#
# The type here is quite broad because NumPy accepts quite a wide
# range of inputs inside the list; see the tests for some
# examples.
- List[Any],
+ list[Any],
# {'names': ..., 'formats': ..., 'offsets': ..., 'titles': ...,
# 'itemsize': ...}
_DTypeDict,
# (base_dtype, new_dtype)
- Tuple[_DTypeLikeNested, _DTypeLikeNested],
+ tuple[_DTypeLikeNested, _DTypeLikeNested],
]
# Anything that can be coerced into numpy.dtype.
# Reference: https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html
DTypeLike = Union[
- DType[Any],
+ np.dtype[Any],
# default data type (float64)
None,
# array-scalar types and generic types
- Type[Any], # NOTE: We're stuck with `Type[Any]` due to object dtypes
+ type[Any], # NOTE: We're stuck with `type[Any]` due to object dtypes
# anything with a dtype attribute
- _SupportsDType[DType[Any]],
+ _SupportsDType[np.dtype[Any]],
# character codes, type strings or comma-separated fields, e.g., 'float64'
str,
_VoidDTypeLike,
@@ -139,16 +136,16 @@ DTypeLike = Union[
# Aliases for commonly used dtype-like objects.
# Note that the precision of `np.number` subclasses is ignored herein.
_DTypeLikeBool = Union[
- Type[bool],
- Type[np.bool_],
- DType[np.bool_],
- _SupportsDType[DType[np.bool_]],
+ type[bool],
+ type[np.bool_],
+ np.dtype[np.bool_],
+ _SupportsDType[np.dtype[np.bool_]],
_BoolCodes,
]
_DTypeLikeUInt = Union[
- Type[np.unsignedinteger],
- DType[np.unsignedinteger],
- _SupportsDType[DType[np.unsignedinteger]],
+ type[np.unsignedinteger],
+ np.dtype[np.unsignedinteger],
+ _SupportsDType[np.dtype[np.unsignedinteger]],
_UInt8Codes,
_UInt16Codes,
_UInt32Codes,
@@ -161,10 +158,10 @@ _DTypeLikeUInt = Union[
_ULongLongCodes,
]
_DTypeLikeInt = Union[
- Type[int],
- Type[np.signedinteger],
- DType[np.signedinteger],
- _SupportsDType[DType[np.signedinteger]],
+ type[int],
+ type[np.signedinteger],
+ np.dtype[np.signedinteger],
+ _SupportsDType[np.dtype[np.signedinteger]],
_Int8Codes,
_Int16Codes,
_Int32Codes,
@@ -177,10 +174,10 @@ _DTypeLikeInt = Union[
_LongLongCodes,
]
_DTypeLikeFloat = Union[
- Type[float],
- Type[np.floating],
- DType[np.floating],
- _SupportsDType[DType[np.floating]],
+ type[float],
+ type[np.floating],
+ np.dtype[np.floating],
+ _SupportsDType[np.dtype[np.floating]],
_Float16Codes,
_Float32Codes,
_Float64Codes,
@@ -190,10 +187,10 @@ _DTypeLikeFloat = Union[
_LongDoubleCodes,
]
_DTypeLikeComplex = Union[
- Type[complex],
- Type[np.complexfloating],
- DType[np.complexfloating],
- _SupportsDType[DType[np.complexfloating]],
+ type[complex],
+ type[np.complexfloating],
+ np.dtype[np.complexfloating],
+ _SupportsDType[np.dtype[np.complexfloating]],
_Complex64Codes,
_Complex128Codes,
_CSingleCodes,
@@ -201,42 +198,42 @@ _DTypeLikeComplex = Union[
_CLongDoubleCodes,
]
_DTypeLikeDT64 = Union[
- Type[np.timedelta64],
- DType[np.timedelta64],
- _SupportsDType[DType[np.timedelta64]],
+ type[np.timedelta64],
+ np.dtype[np.timedelta64],
+ _SupportsDType[np.dtype[np.timedelta64]],
_TD64Codes,
]
_DTypeLikeTD64 = Union[
- Type[np.datetime64],
- DType[np.datetime64],
- _SupportsDType[DType[np.datetime64]],
+ type[np.datetime64],
+ np.dtype[np.datetime64],
+ _SupportsDType[np.dtype[np.datetime64]],
_DT64Codes,
]
_DTypeLikeStr = Union[
- Type[str],
- Type[np.str_],
- DType[np.str_],
- _SupportsDType[DType[np.str_]],
+ type[str],
+ type[np.str_],
+ np.dtype[np.str_],
+ _SupportsDType[np.dtype[np.str_]],
_StrCodes,
]
_DTypeLikeBytes = Union[
- Type[bytes],
- Type[np.bytes_],
- DType[np.bytes_],
- _SupportsDType[DType[np.bytes_]],
+ type[bytes],
+ type[np.bytes_],
+ np.dtype[np.bytes_],
+ _SupportsDType[np.dtype[np.bytes_]],
_BytesCodes,
]
_DTypeLikeVoid = Union[
- Type[np.void],
- DType[np.void],
- _SupportsDType[DType[np.void]],
+ type[np.void],
+ np.dtype[np.void],
+ _SupportsDType[np.dtype[np.void]],
_VoidCodes,
_VoidDTypeLike,
]
_DTypeLikeObject = Union[
type,
- DType[np.object_],
- _SupportsDType[DType[np.object_]],
+ np.dtype[np.object_],
+ _SupportsDType[np.dtype[np.object_]],
_ObjectCodes,
]
diff --git a/numpy/_typing/_extended_precision.py b/numpy/_typing/_extended_precision.py
index edc1778ce..7246b47d0 100644
--- a/numpy/_typing/_extended_precision.py
+++ b/numpy/_typing/_extended_precision.py
@@ -5,8 +5,6 @@ The subclasses are defined here (instead of ``__init__.pyi``) such
that they can be imported conditionally via the numpy's mypy plugin.
"""
-from typing import TYPE_CHECKING
-
import numpy as np
from . import (
_80Bit,
@@ -15,29 +13,15 @@ from . import (
_256Bit,
)
-if TYPE_CHECKING:
- uint128 = np.unsignedinteger[_128Bit]
- uint256 = np.unsignedinteger[_256Bit]
- int128 = np.signedinteger[_128Bit]
- int256 = np.signedinteger[_256Bit]
- float80 = np.floating[_80Bit]
- float96 = np.floating[_96Bit]
- float128 = np.floating[_128Bit]
- float256 = np.floating[_256Bit]
- complex160 = np.complexfloating[_80Bit, _80Bit]
- complex192 = np.complexfloating[_96Bit, _96Bit]
- complex256 = np.complexfloating[_128Bit, _128Bit]
- complex512 = np.complexfloating[_256Bit, _256Bit]
-else:
- uint128 = Any
- uint256 = Any
- int128 = Any
- int256 = Any
- float80 = Any
- float96 = Any
- float128 = Any
- float256 = Any
- complex160 = Any
- complex192 = Any
- complex256 = Any
- complex512 = Any
+uint128 = np.unsignedinteger[_128Bit]
+uint256 = np.unsignedinteger[_256Bit]
+int128 = np.signedinteger[_128Bit]
+int256 = np.signedinteger[_256Bit]
+float80 = np.floating[_80Bit]
+float96 = np.floating[_96Bit]
+float128 = np.floating[_128Bit]
+float256 = np.floating[_256Bit]
+complex160 = np.complexfloating[_80Bit, _80Bit]
+complex192 = np.complexfloating[_96Bit, _96Bit]
+complex256 = np.complexfloating[_128Bit, _128Bit]
+complex512 = np.complexfloating[_256Bit, _256Bit]
diff --git a/numpy/_typing/_generic_alias.py b/numpy/_typing/_generic_alias.py
deleted file mode 100644
index 01cd224ad..000000000
--- a/numpy/_typing/_generic_alias.py
+++ /dev/null
@@ -1,245 +0,0 @@
-from __future__ import annotations
-
-import sys
-import types
-from collections.abc import Generator, Iterable, Iterator
-from typing import (
- Any,
- ClassVar,
- NoReturn,
- TypeVar,
- TYPE_CHECKING,
-)
-
-import numpy as np
-
-__all__ = ["_GenericAlias", "NDArray"]
-
-_T = TypeVar("_T", bound="_GenericAlias")
-
-
-def _to_str(obj: object) -> str:
- """Helper function for `_GenericAlias.__repr__`."""
- if obj is Ellipsis:
- return '...'
- elif isinstance(obj, type) and not isinstance(obj, _GENERIC_ALIAS_TYPE):
- if obj.__module__ == 'builtins':
- return obj.__qualname__
- else:
- return f'{obj.__module__}.{obj.__qualname__}'
- else:
- return repr(obj)
-
-
-def _parse_parameters(args: Iterable[Any]) -> Generator[TypeVar, None, None]:
- """Search for all typevars and typevar-containing objects in `args`.
-
- Helper function for `_GenericAlias.__init__`.
-
- """
- for i in args:
- if hasattr(i, "__parameters__"):
- yield from i.__parameters__
- elif isinstance(i, TypeVar):
- yield i
-
-
-def _reconstruct_alias(alias: _T, parameters: Iterator[TypeVar]) -> _T:
- """Recursively replace all typevars with those from `parameters`.
-
- Helper function for `_GenericAlias.__getitem__`.
-
- """
- args = []
- for i in alias.__args__:
- if isinstance(i, TypeVar):
- value: Any = next(parameters)
- elif isinstance(i, _GenericAlias):
- value = _reconstruct_alias(i, parameters)
- elif hasattr(i, "__parameters__"):
- prm_tup = tuple(next(parameters) for _ in i.__parameters__)
- value = i[prm_tup]
- else:
- value = i
- args.append(value)
-
- cls = type(alias)
- return cls(alias.__origin__, tuple(args), alias.__unpacked__)
-
-
-class _GenericAlias:
- """A python-based backport of the `types.GenericAlias` class.
-
- E.g. for ``t = list[int]``, ``t.__origin__`` is ``list`` and
- ``t.__args__`` is ``(int,)``.
-
- See Also
- --------
- :pep:`585`
- The PEP responsible for introducing `types.GenericAlias`.
-
- """
-
- __slots__ = (
- "__weakref__",
- "_origin",
- "_args",
- "_parameters",
- "_hash",
- "_starred",
- )
-
- @property
- def __origin__(self) -> type:
- return super().__getattribute__("_origin")
-
- @property
- def __args__(self) -> tuple[object, ...]:
- return super().__getattribute__("_args")
-
- @property
- def __parameters__(self) -> tuple[TypeVar, ...]:
- """Type variables in the ``GenericAlias``."""
- return super().__getattribute__("_parameters")
-
- @property
- def __unpacked__(self) -> bool:
- return super().__getattribute__("_starred")
-
- @property
- def __typing_unpacked_tuple_args__(self) -> tuple[object, ...] | None:
- # NOTE: This should return `__args__` if `__origin__` is a tuple,
- # which should never be the case with how `_GenericAlias` is used
- # within numpy
- return None
-
- def __init__(
- self,
- origin: type,
- args: object | tuple[object, ...],
- starred: bool = False,
- ) -> None:
- self._origin = origin
- self._args = args if isinstance(args, tuple) else (args,)
- self._parameters = tuple(_parse_parameters(self.__args__))
- self._starred = starred
-
- @property
- def __call__(self) -> type[Any]:
- return self.__origin__
-
- def __reduce__(self: _T) -> tuple[
- type[_T],
- tuple[type[Any], tuple[object, ...], bool],
- ]:
- cls = type(self)
- return cls, (self.__origin__, self.__args__, self.__unpacked__)
-
- def __mro_entries__(self, bases: Iterable[object]) -> tuple[type[Any]]:
- return (self.__origin__,)
-
- def __dir__(self) -> list[str]:
- """Implement ``dir(self)``."""
- cls = type(self)
- dir_origin = set(dir(self.__origin__))
- return sorted(cls._ATTR_EXCEPTIONS | dir_origin)
-
- def __hash__(self) -> int:
- """Return ``hash(self)``."""
- # Attempt to use the cached hash
- try:
- return super().__getattribute__("_hash")
- except AttributeError:
- self._hash: int = (
- hash(self.__origin__) ^
- hash(self.__args__) ^
- hash(self.__unpacked__)
- )
- return super().__getattribute__("_hash")
-
- def __instancecheck__(self, obj: object) -> NoReturn:
- """Check if an `obj` is an instance."""
- raise TypeError("isinstance() argument 2 cannot be a "
- "parameterized generic")
-
- def __subclasscheck__(self, cls: type) -> NoReturn:
- """Check if a `cls` is a subclass."""
- raise TypeError("issubclass() argument 2 cannot be a "
- "parameterized generic")
-
- def __repr__(self) -> str:
- """Return ``repr(self)``."""
- args = ", ".join(_to_str(i) for i in self.__args__)
- origin = _to_str(self.__origin__)
- prefix = "*" if self.__unpacked__ else ""
- return f"{prefix}{origin}[{args}]"
-
- def __getitem__(self: _T, key: object | tuple[object, ...]) -> _T:
- """Return ``self[key]``."""
- key_tup = key if isinstance(key, tuple) else (key,)
-
- if len(self.__parameters__) == 0:
- raise TypeError(f"There are no type variables left in {self}")
- elif len(key_tup) > len(self.__parameters__):
- raise TypeError(f"Too many arguments for {self}")
- elif len(key_tup) < len(self.__parameters__):
- raise TypeError(f"Too few arguments for {self}")
-
- key_iter = iter(key_tup)
- return _reconstruct_alias(self, key_iter)
-
- def __eq__(self, value: object) -> bool:
- """Return ``self == value``."""
- if not isinstance(value, _GENERIC_ALIAS_TYPE):
- return NotImplemented
- return (
- self.__origin__ == value.__origin__ and
- self.__args__ == value.__args__ and
- self.__unpacked__ == getattr(
- value, "__unpacked__", self.__unpacked__
- )
- )
-
- def __iter__(self: _T) -> Generator[_T, None, None]:
- """Return ``iter(self)``."""
- cls = type(self)
- yield cls(self.__origin__, self.__args__, True)
-
- _ATTR_EXCEPTIONS: ClassVar[frozenset[str]] = frozenset({
- "__origin__",
- "__args__",
- "__parameters__",
- "__mro_entries__",
- "__reduce__",
- "__reduce_ex__",
- "__copy__",
- "__deepcopy__",
- "__unpacked__",
- "__typing_unpacked_tuple_args__",
- "__class__",
- })
-
- def __getattribute__(self, name: str) -> Any:
- """Return ``getattr(self, name)``."""
- # Pull the attribute from `__origin__` unless its
- # name is in `_ATTR_EXCEPTIONS`
- cls = type(self)
- if name in cls._ATTR_EXCEPTIONS:
- return super().__getattribute__(name)
- return getattr(self.__origin__, name)
-
-
-# See `_GenericAlias.__eq__`
-if sys.version_info >= (3, 9):
- _GENERIC_ALIAS_TYPE = (_GenericAlias, types.GenericAlias)
-else:
- _GENERIC_ALIAS_TYPE = (_GenericAlias,)
-
-ScalarType = TypeVar("ScalarType", bound=np.generic, covariant=True)
-
-if TYPE_CHECKING or sys.version_info >= (3, 9):
- _DType = np.dtype[ScalarType]
- NDArray = np.ndarray[Any, np.dtype[ScalarType]]
-else:
- _DType = _GenericAlias(np.dtype, (ScalarType,))
- NDArray = _GenericAlias(np.ndarray, (Any, _DType))
diff --git a/numpy/_typing/_nested_sequence.py b/numpy/_typing/_nested_sequence.py
index 789bf3844..4b6cafc51 100644
--- a/numpy/_typing/_nested_sequence.py
+++ b/numpy/_typing/_nested_sequence.py
@@ -2,9 +2,9 @@
from __future__ import annotations
+from collections.abc import Iterator
from typing import (
Any,
- Iterator,
overload,
TypeVar,
Protocol,
diff --git a/numpy/_typing/_scalars.py b/numpy/_typing/_scalars.py
index 516b996dc..e46ff04a0 100644
--- a/numpy/_typing/_scalars.py
+++ b/numpy/_typing/_scalars.py
@@ -1,4 +1,4 @@
-from typing import Union, Tuple, Any
+from typing import Union, Any
import numpy as np
@@ -10,13 +10,13 @@ _CharLike_co = Union[str, bytes]
# The 6 `<X>Like_co` type-aliases below represent all scalars that can be
# coerced into `<X>` (with the casting rule `same_kind`)
_BoolLike_co = Union[bool, np.bool_]
-_UIntLike_co = Union[_BoolLike_co, np.unsignedinteger]
-_IntLike_co = Union[_BoolLike_co, int, np.integer]
-_FloatLike_co = Union[_IntLike_co, float, np.floating]
-_ComplexLike_co = Union[_FloatLike_co, complex, np.complexfloating]
+_UIntLike_co = Union[_BoolLike_co, np.unsignedinteger[Any]]
+_IntLike_co = Union[_BoolLike_co, int, np.integer[Any]]
+_FloatLike_co = Union[_IntLike_co, float, np.floating[Any]]
+_ComplexLike_co = Union[_FloatLike_co, complex, np.complexfloating[Any, Any]]
_TD64Like_co = Union[_IntLike_co, np.timedelta64]
-_NumberLike_co = Union[int, float, complex, np.number, np.bool_]
+_NumberLike_co = Union[int, float, complex, np.number[Any], np.bool_]
_ScalarLike_co = Union[
int,
float,
@@ -27,4 +27,4 @@ _ScalarLike_co = Union[
]
# `_VoidLike_co` is technically not a scalar, but it's close enough
-_VoidLike_co = Union[Tuple[Any, ...], np.void]
+_VoidLike_co = Union[tuple[Any, ...], np.void]
diff --git a/numpy/_typing/_shape.py b/numpy/_typing/_shape.py
index c28859b19..4f1204e47 100644
--- a/numpy/_typing/_shape.py
+++ b/numpy/_typing/_shape.py
@@ -1,6 +1,7 @@
-from typing import Sequence, Tuple, Union, SupportsIndex
+from collections.abc import Sequence
+from typing import Union, SupportsIndex
-_Shape = Tuple[int, ...]
+_Shape = tuple[int, ...]
# Anything that can be coerced to a shape tuple
_ShapeLike = Union[SupportsIndex, Sequence[SupportsIndex]]