8000 TYP: fix stubtest errors in ``numpy._core`` (#28535) · numpy/numpy@8f561db · GitHub
[go: up one dir, main page]

Skip to content

Commit 8f561db

Browse files
jorenhamcharris
authored andcommitted
TYP: fix stubtest errors in numpy._core (#28535)
* TYP: fix stubtest errors in ``numpy._core._internal`` Ported from numpy/numtype#238 * TYP: fix stubtest errors in ``numpy._core.einsumfunc`` Ported from numpy/numtype#239 * TYP: fix stubtest errors in ``numpy._core.arrayprint``` Ported from numpy/numtype#240 * TYP: fix remaining stubtest errors in ``numpy._core`` Ported from numpy/numtype#246 * TYP: fix incorrect warning ignore in "pass" type-tests
1 parent 7974ff9 commit 8f561db

File tree

7 files changed

+98
-35
lines changed

7 files changed

+98
-35
lines changed

numpy/_core/_internal.pyi

Lines changed: 53 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,72 @@
1-
from typing import Any, TypeVar, overload, Generic
21
import ctypes as ct
2+
import re
3+
from collections.abc import Callable, Iterable
4+
from typing import Any, Final, Generic, overload
35

4-
from numpy.typing import NDArray
6+
from typing_extensions import Self, TypeVar, deprecated
7+
8+
import numpy as np
9+
import numpy.typing as npt
510
from numpy.ctypeslib import c_intp
611

7-
_CastT = TypeVar("_CastT", bound=ct._CanCastTo) # Copied from `ctypes.cast`
12+
_CastT = TypeVar("_CastT", bound=ct._CanCastTo)
13+
_T_co = TypeVar("_T_co", covariant=True)
814
_CT = TypeVar("_CT", bound=ct._CData)
9-
_PT = TypeVar("_PT", bound=int)
15+
_PT_co = TypeVar("_PT_co", bound=int | None, default=None, covariant=True)
16+
17+
###
18+
19+
IS_PYPY: Final[bool] = ...
20+
21+
format_re: Final[re.Pattern[str]] = ...
22+
sep_re: Final[re.Pattern[str]] = ...
23+
space_re: Final[re.Pattern[str]] = ...
24+
25+
###
1026

1127
# TODO: Let the likes of `shape_as` and `strides_as` return `None`
1228
# for 0D arrays once we've got shape-support
1329

14-
class _ctypes(Generic[_PT]):
30+
class _ctypes(Generic[_PT_co]):
1531
@overload
16-
def __new__(cls, array: NDArray[Any], ptr: None = ...) -> _ctypes[None]: ...
32+
def __init__(self: _ctypes[None], /, array: npt.NDArray[Any], ptr: None = None) -> None: ...
1733
@overload
18-
def __new__(cls, array: NDArray[Any], ptr: _PT) -> _ctypes[_PT]: ...
34+
def __init__(self, /, array: npt.NDArray[Any], ptr: _PT_co) -> None: ...
35+
36+
#
1937
@property
20-
def data(self) -> _PT: ...
38+
def data(self) -> _PT_co: ...
2139
@property
2240
def shape(self) -> ct.Array[c_intp]: ...
2341
@property
2442
def strides(self) -> ct.Array[c_intp]: ...
2543
@property
2644
def _as_parameter_(self) -> ct.c_void_p: ...
2745

28-
def data_as(self, obj: type[_CastT]) -> _CastT: ...
29-
def shape_as(self, obj: type[_CT]) -> ct.Array[_CT]: ...
30-
def strides_as(self, obj: type[_CT]) -> ct.Array[_CT]: ...
46+
#
47+
def data_as(self, /, obj: type[_CastT]) -> _CastT: ...
48+
def shape_as(self, /, obj: type[_CT]) -> ct.Array[_CT]: ...
49+
def strides_as(self, /, obj: type[_CT]) -> ct.Array[_CT]: ...
50+
51+
#
52+
@deprecated('"get_data" is deprecated. Use "data" instead')
53+
def get_data(self, /) -> _PT_co: ...
54+
@deprecated('"get_shape" is deprecated. Use "shape" instead')
55+
def get_shape(self, /) -> ct.Array[c_intp]: ...
56+
@deprecated('"get_strides" is deprecated. Use "strides" instead')
57+
def get_strides(self, /) -> ct.Array[c_intp]: ...
58+
@deprecated('"get_as_parameter" is deprecated. Use "_as_parameter_" instead')
59+
def get_as_parameter(self, /) -> ct.c_void_p: ...
60+
61+
class dummy_ctype(Generic[_T_co]):
62+
_cls: type[_T_co]
63+
64+
def __init__(self, /, cls: type[_T_co]) -> None: ...
65+
def __eq__(self, other: Self, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
66+
def __ne__(self, other: Self, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
67+
def __mul__(self, other: object, /) -> Self: ...
68+
def __call__(self, /, *other: object) -> _T_co: ...
69+
70+
def array_ufunc_errmsg_formatter(dummy: object, ufunc: np.ufunc, method: str, *inputs: object, **kwargs: object) -> str: ...
71+
def array_function_errmsg_formatter(public_api: Callable[..., object], types: Iterable[str]) -> str: ...
72+
def npy_ctypes_check(cls: type) -> bool: ...

numpy/_core/arrayprint.pyi

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ from typing import Any, Final, Literal, SupportsIndex, TypeAlias, TypedDict, ove
88
from typing_extensions import deprecated
99

1010
import numpy as np
11+
from numpy._globals import _NoValueType
1112
from numpy._typing import NDArray, _CharLike_co, _FloatLike_co
1213

1314
__all__ = [
@@ -93,13 +94,14 @@ def array2string(
9394
suppress_small: bool | None = None,
9495
separator: str = " ",
9596
prefix: str = "",
96-
*,
97+
style: _NoValueType = ...,
9798
formatter: _FormatDict | None = None,
9899
threshold: int | None = None,
99100
edgeitems: int | None = None,
100101
sign: _Sign | None = None,
101102
floatmode: _FloatMode | None = None,
102103
suffix: str = "",
104+
*,
103105
legacy: _Legacy | None = None,
104106
) -> str: ...
105107
@overload # style=<given> (positional), legacy="1.13"

numpy/_core/einsumfunc.pyi

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -180,5 +180,6 @@ def einsum_path(
180180
subscripts: str | _ArrayLikeInt_co,
181181
/,
182182
*operands: _ArrayLikeComplex_co | _DTypeLikeObject,
183-
optimize: _OptimizeKind = ...,
183+
optimize: _OptimizeKind = "greedy",
184+
einsum_call: Literal[False] = False,
184185
) -> tuple[list[Any], str]: ...

numpy/_core/multiarray.pyi

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,8 @@ class _ConstructorEmpty(Protocol):
355355
**kwargs: Unpack[_KwargsEmpty],
356356
) -> NDArray[Any]: ...
357357

358-
error: Final = Exception
358+
# using `Final` or `TypeAlias` will break stubtest
359+
error = Exception
359360

360361
# from ._multiarray_umath
361362
ITEM_HASOBJECT: Final[L[1]]

numpy/_core/records.pyi

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
# ruff: noqa: ANN401
22
# pyright: reportSelfClsParameterName=false
33
from collections.abc import Iterable, Sequence
4-
from types import EllipsisType
5-
from typing import Any, Literal, Protocol, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only
4+
from typing import Any, ClassVar, Literal, Protocol, SupportsIndex, TypeAlias, overload, type_check_only
65

76
from _typeshed import StrOrBytesPath
7+
from typing_extensions import TypeVar
88

9-
from numpy import _ByteOrder, _OrderKACF, _SupportsBuffer, dtype, generic, ndarray, void
9+
import numpy as np
10+
from numpy import _ByteOrder, _OrderKACF, _SupportsBuffer
1011
from numpy._typing import ArrayLike, DTypeLike, NDArray, _ArrayLikeVoid_co, _NestedSequence, _ShapeLike
1112

1213
__all__ = [
@@ -22,11 +23,11 @@ __all__ = [
2223
]
2324

2425
_T = TypeVar("_T")
25-
_SCT = TypeVar("_SCT", bound=generic)
26-
_DType_co = TypeVar("_DType_co", bound=dtype[Any], covariant=True)
26+
_SCT = TypeVar("_SCT", bound=np.generic)
27+
_DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype[Any], covariant=True)
2728
_ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], covariant=True)
2829

29-
_RecArray: TypeAlias = recarray[Any, dtype[_SCT]]
30+
_RecArray: TypeAlias = recarray[Any, np.dtype[_SCT]]
3031

3132
@type_check_only
3233
class _SupportsReadInto(Protocol):
@@ -37,7 +38,7 @@ class _SupportsReadInto(Protocol):
3738
###
3839

3940
# exported in `numpy.rec`
40-
class record(void):
41+
class record(np.void):
4142
def __getattribute__(self, attr: str) -> Any: ...
4243
def __setattr__(self, attr: str, val: ArrayLike) -> None: ...
4344
def pprint(self) -> str: ...
@@ -47,10 +48,9 @@ class record(void):
4748
def __getitem__(self, key: list[str]) -> record: ...
4849

4950
# exported in `numpy.rec`
50-
class recarray(ndarray[_ShapeT_co, _DType_co]):
51-
# NOTE: While not strictly mandatory, we're demanding here that arguments
52-
# for the `format_parser`- and `dtype`-based dtype constructors are
53-
# mutually exclusive
51+
class recarray(np.ndarray[_ShapeT_co, _DTypeT_co]):
52+
__name__: ClassVar[Literal["record"]] = "record"
53+
__module__: Literal["numpy"] = "numpy"
5454
@overload
5555
def __new__(
5656
subtype,
@@ -66,7 +66,7 @@ class recarray(ndarray[_ShapeT_co, _DType_co]):
6666
byteorder: _ByteOrder | None = None,
6767
aligned: bool = False,
6868
order: _OrderKACF = "C",
69-
) -> recarray[Any, dtype[record]]: ...
69+
) -> _RecArray[record]: ...
7070
@overload
7171
def __new__(
7272
subtype,
@@ -81,18 +81,20 @@ class recarray(ndarray[_ShapeT_co, _DType_co]):
8181
byteorder: None = None,
8282
aligned: Literal[False] = False,
8383
order: _OrderKACF = "C",
84-
) -> recarray[Any, dtype[Any]]: ...
84+
) -> _RecArray[Any]: ...
8585
def __array_finalize__(self, /, obj: object) -> None: ...
8686
def __getattribute__(self, attr: str, /) -> Any: ...
8787
def __setattr__(self, attr: str, val: ArrayLike, /) -> None: ...
88-
@overload
89-
def field(self, /, attr: int | str, val: None = None) -> Any: ...
88+
89+
#
9090
@overload
9191
def field(self, /, attr: int | str, val: ArrayLike) -> None: ...
92+
@overload
93+
def field(self, /, attr: int | str, val: None = None) -> Any: ...
9294

9395
# exported in `numpy.rec`
9496
class format_parser:
95-
dtype: dtype[void]
97+
dtype: np.dtype[np.void]
9698
def __init__(
9799
self,
98100
/,
@@ -213,6 +215,7 @@ def array(
213215
dtype: None = None,
214216
shape: _ShapeLike | None = None,
215217
offset: int = 0,
218+
strides: tuple[int, ...] | None = None,
216219
formats: None = None,
217220
names: None = None,
218221
titles: None = None,
@@ -226,6 +229,7 @@ def array(
226229
dtype: DTypeLike,
227230
shape: _ShapeLike | None = None,
228231
offset: int = 0,
232+
strides: tuple[int, ...] | None = None,
229233
formats: None = None,
230234
names: None = None,
231235
titles: None = None,
@@ -239,6 +243,7 @@ def array(
239243
dtype: None = None,
240244
shape: _ShapeLike | None = None,
241245
offset: int = 0,
246+
strides: tuple[int, ...] | None = None,
242247
*,
243248
formats: DTypeLike,
244249
names: str | Sequence[str] | None = None,
@@ -253,6 +258,7 @@ def array(
253258
dtype: DTypeLike,
254259
shape: _ShapeLike,
255260
offset: int = 0,
261+
strides: tuple[int, ...] | None = None,
256262
formats: None = None,
257263
names: None = None,
258264
titles: None = None,
@@ -267,6 +273,7 @@ def array(
267273
*,
268274
shape: _ShapeLike,
269275
offset: int = 0,
276+
strides: tuple[int, ...] | None = None,
270277
formats: DTypeLike,
271278
names: str | Sequence[str] | None = None,
272279
titles: str | Sequence[str] | None = None,
@@ -280,6 +287,7 @@ def array(
280287
dtype: DTypeLike,
281288
shape: _ShapeLike | None = None,
282289
offset: int = 0,
290+
strides: tuple[int, ...] | None = None,
283291
formats: None = None,
284292
names: None = None,
285293
titles: None = None,
@@ -293,6 +301,7 @@ def array(
293301
dtype: None = None,
294302
shape: _ShapeLike | None = None,
295303
offset: int = 0,
304+
strides: tuple[int, ...] | None = None,
296305
*,
297306
formats: DTypeLike,
298307
names: str | Sequence[str] | None = None,

numpy/typing/tests/data/fail/ndarray_misc.pyi

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,6 @@ AR_b: npt.NDArray[np.bool]
1616

1717
ctypes_obj = AR_f8.ctypes
1818

19-
reveal_type(ctypes_obj.get_data()) # E: has no attribute
20-
reveal_type(ctypes_obj.get_shape()) # E: has no attribute
21-
reveal_type(ctypes_obj.get_strides()) # E: has no attribute
22-
reveal_type(ctypes_obj.get_as_parameter()) # E: has no attribute
23-
2419
f8.argpartition(0) # E: has no attribute
2520
f8.diagonal() # E: has no attribute
2621
f8.dot(1) # E: has no attribute

numpy/typing/tests/data/pass/ndarray_misc.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ class SubClass(npt.NDArray[np.float64]): ...
2424
C: np.ndarray[Any, np.dtype[np.int32]] = np.array([0, 1, 2], dtype=np.int32)
2525
D = np.ones(3).view(SubClass)
2626

27+
ctypes_obj = A.ctypes
28+
2729
i4.all()
2830
A.all()
2931
A.all(axis=0)
@@ -181,3 +183,14 @@ class SubClass(npt.NDArray[np.float64]): ...
181183
A_void: npt.NDArray[np.void] = np.empty(3, [("yop", float), ("yap", float)])
182184
A_void["yop"] = A_float[:, 0]
183185
A_void["yap"] = A_float[:, 1]
186+
187+
# deprecated
188+
189+
with np.testing.assert_warns(DeprecationWarning):
190+
ctypes_obj.get_data() # pyright: ignore[reportDeprecated]
191+
with np.testing.assert_warns(DeprecationWarning):
192+
ctypes_obj.get_shape() # pyright: ignore[reportDeprecated]
193+
with np.testing.assert_warns(DeprecationWarning):
194+
ctypes_obj.get_strides() # pyright: ignore[reportDeprecated]
195+
with np.testing.assert_warns(DeprecationWarning):
196+
ctypes_obj.get_as_parameter() # pyright: ignore[reportDeprecated]

0 commit comments

Comments
 (0)
0