Skip to content

Commit

Permalink
Merge pull request #19533 from BvB93/optional2
Browse files Browse the repository at this point in the history
BUG: Fix an issue wherein importing `numpy.typing` could raise
  • Loading branch information
charris committed Jul 22, 2021
2 parents 42240ba + 3b79a87 commit cfb451b
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 3 deletions.
13 changes: 11 additions & 2 deletions numpy/typing/_array_like.py
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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[
Expand Down
3 changes: 2 additions & 1 deletion numpy/typing/_dtype_like.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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]):
Expand Down
35 changes: 35 additions & 0 deletions numpy/typing/tests/test_typing_extensions.py
Original file line number Diff line number Diff line change
@@ -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()}"
)

0 comments on commit cfb451b

Please sign in to comment.