diff --git a/numpy/typing/_array_like.py b/numpy/typing/_array_like.py index cfd9aacb4927..a1642f9d03e5 100644 --- a/numpy/typing/_array_like.py +++ b/numpy/typing/_array_like.py @@ -1,7 +1,15 @@ from __future__ import annotations import sys -from typing import Any, overload, Sequence, TYPE_CHECKING, Union, TypeVar +from typing import ( + Any, + overload, + Sequence, + TYPE_CHECKING, + Union, + TypeVar, + Generic, +) from numpy import ( ndarray, @@ -47,7 +55,8 @@ class _SupportsArray(Protocol[_DType_co]): def __array__(self) -> ndarray[Any, _DType_co]: ... else: - _SupportsArray = Any + class _SupportsArray(Generic[_DType_co]): + pass # TODO: Wait for support for recursive types _NestedSequence = Union[ diff --git a/numpy/typing/_dtype_like.py b/numpy/typing/_dtype_like.py index 636e2209b45f..9864f46d5e1f 100644 --- a/numpy/typing/_dtype_like.py +++ b/numpy/typing/_dtype_like.py @@ -67,6 +67,8 @@ _ObjectCodes, ) +_DType_co = TypeVar("_DType_co", covariant=True, bound=np.dtype) + _DTypeLikeNested = Any # TODO: wait for support for recursive types if TYPE_CHECKING or HAVE_PROTOCOL: @@ -82,7 +84,6 @@ class _DTypeDict(_DTypeDictBase, total=False): itemsize: int aligned: bool - _DType_co = TypeVar("_DType_co", covariant=True, bound=np.dtype) # A protocol for anything with the dtype attribute class _SupportsDType(Protocol[_DType_co]): diff --git a/numpy/typing/tests/test_typing_extensions.py b/numpy/typing/tests/test_typing_extensions.py new file mode 100644 index 000000000000..f59f222fbdd0 --- /dev/null +++ b/numpy/typing/tests/test_typing_extensions.py @@ -0,0 +1,35 @@ +"""Tests for the optional typing-extensions dependency.""" + +import sys +import textwrap +import subprocess + +CODE = textwrap.dedent(r""" + import sys + import importlib + + assert "typing_extensions" not in sys.modules + assert "numpy.typing" not in sys.modules + + # Importing `typing_extensions` will now raise an `ImportError` + sys.modules["typing_extensions"] = None + assert importlib.import_module("numpy.typing") +""") + + +def test_no_typing_extensions() -> None: + """Import `numpy.typing` in the absence of typing-extensions. + + Notes + ----- + Ideally, we'd just run the normal typing tests in an environment where + typing-extensions is not installed, but unfortunatelly this is currently + impossible as it is an indirect hard dependency of pytest. + + """ + p = subprocess.run([sys.executable, '-c', CODE], capture_output=True) + if p.returncode: + raise AssertionError( + f"Non-zero return code: {p.returncode!r}\n\n{p.stderr.decode()}" + ) +