Skip to content
This repository was archived by the owner on Jun 10, 2020. It is now read-only.

Commit 4f654e5

Browse files
committed
MAINT: use a _SupportsArray protocol to improve ArrayLike
1 parent 7d410ee commit 4f654e5

File tree

2 files changed

+40
-11
lines changed

2 files changed

+40
-11
lines changed

numpy-stubs/__init__.pyi

+10-1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,11 @@ if sys.version_info[0] < 3:
3535
else:
3636
from typing import SupportsBytes
3737

38+
if sys.version_info >= (3, 8):
39+
from typing import Protocol
40+
else:
41+
from typing_extensions import Protocol
42+
3843
# TODO: remove when the full numpy namespace is defined
3944
def __getattr__(name: str) -> Any: ...
4045

@@ -87,7 +92,10 @@ _DtypeLike = Union[
8792

8893
_NdArraySubClass = TypeVar("_NdArraySubClass", bound=ndarray)
8994

90-
ArrayLike = Union[int, float, complex, generic, ndarray, Sequence]
95+
class _SupportsArray(Protocol):
96+
def __array__(self) -> Union[Sequence, ndarray]: ...
97+
98+
ArrayLike = Union[bool, int, float, complex, _SupportsArray, Sequence]
9199

92100
class dtype:
93101
names: Optional[Tuple[str, ...]]
@@ -212,6 +220,7 @@ class _ArrayOrScalarCommon(
212220
def shape(self) -> _Shape: ...
213221
@property
214222
def strides(self) -> _Shape: ...
223+
def __array__(self) -> ndarray: ...
215224
def __int__(self) -> int: ...
216225
def __float__(self) -> float: ...
217226
def __complex__(self) -> complex: ...

tests/pass/array_like_py3.py

+30-10
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,32 @@
1+
from typing import Any
2+
13
import numpy as np
24

3-
x1: 'np.ArrayLike' = 5
4-
x2: 'np.ArrayLike' = 1.0
5-
x3: 'np.ArrayLike' = 1 + 1j
6-
x4: 'np.ArrayLike' = np.int8(1)
7-
x5: 'np.ArrayLike' = np.float64(1)
8-
x6: 'np.ArrayLike' = np.complex128(1)
9-
x7: 'np.ArrayLike' = np.array([1, 2, 3])
10-
x8: 'np.ArrayLike' = [1, 2, 3]
11-
x9: 'np.ArrayLike' = (1, 2, 3)
12-
x10: 'np.ArrayLike' = 'foo'
5+
x1: 'np.ArrayLike' = True
6+
x2: 'np.ArrayLike' = 5
7+
x3: 'np.ArrayLike' = 1.0
8+
x4: 'np.ArrayLike' = 1 + 1j
9+
x5: 'np.ArrayLike' = np.int8(1)
10+
x6: 'np.ArrayLike' = np.float64(1)
11+
x7: 'np.ArrayLike' = np.complex128(1)
12+
x8: 'np.ArrayLike' = np.array([1, 2, 3])
13+
x9: 'np.ArrayLike' = [1, 2, 3]
14+
x10: 'np.ArrayLike' = (1, 2, 3)
15+
x11: 'np.ArrayLike' = 'foo'
16+
17+
class A:
18+
def __array__(self):
19+
return [1, 2, 3]
20+
21+
x12: 'np.ArrayLike' = A()
22+
23+
class B:
24+
def __array__(self):
25+
return np.array([1, 2, 3])
26+
27+
x13: 'np.ArrayLike' = B()
28+
29+
# Escape hatch for when you mean to make something like an object
30+
# array.
31+
object_array_scalar: Any = (i for i in range(10))
32+
np.array(object_array_scalar)

0 commit comments

Comments
 (0)