Skip to content

Commit 1188650

Browse files
authored
Merge pull request #28542 from charris/backport-typing-4
TYP: Backport typing fixes from main (4)
2 parents 7974ff9 + 18795c2 commit 1188650

File tree

18 files changed

+613
-536
lines changed

18 files changed

+613
-536
lines changed

numpy/__init__.pyi

Lines changed: 8 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2231,11 +2231,9 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DType_co]):
22312231
@overload
22322232
def resize(self, new_shape: _ShapeLike, /, *, refcheck: builtins.bool = ...) -> None: ...
22332233
@overload
2234-
def resize(self, *new_shape: SupportsIndex, refcheck: builtins.bool = ...) -> None: ...
2234+
def resize(self, /, *new_shape: SupportsIndex, refcheck: builtins.bool = ...) -> None: ...
22352235

2236-
def setflags(
2237-
self, write: builtins.bool = ..., align: builtins.bool = ..., uic: builtins.bool = ...
2238-
) -> None: ...
2236+
def setflags(self, write: builtins.bool = ..., align: builtins.bool = ..., uic: builtins.bool = ...) -> None: ...
22392237

22402238
def squeeze(
22412239
self,
@@ -2381,13 +2379,6 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DType_co]):
23812379
sorter: None | _ArrayLikeInt_co = ...,
23822380
) -> NDArray[intp]: ...
23832381

2384-
def setfield(
2385-
self,
2386-
val: ArrayLike,
2387-
dtype: DTypeLike,
2388-
offset: SupportsIndex = ...,
2389-
) -> None: ...
2390-
23912382
def sort(
23922383
self,
23932384
axis: SupportsIndex = ...,
@@ -2567,23 +2558,14 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DType_co]):
25672558
@overload # (dtype: ?, type: type[T])
25682559
def view(self, /, dtype: DTypeLike, type: type[_ArrayT]) -> _ArrayT: ...
25692560

2561+
def setfield(self, /, val: ArrayLike, dtype: DTypeLike, offset: CanIndex = 0) -> None: ...
25702562
@overload
2571-
def getfield(
2572-
self,
2573-
dtype: _DTypeLike[_SCT],
2574-
offset: SupportsIndex = ...
2575-
) -> NDArray[_SCT]: ...
2563+
def getfield(self, dtype: _DTypeLike[_SCT], offset: SupportsIndex = 0) -> NDArray[_SCT]: ...
25762564
@overload
2577-
def getfield(
2578-
self,
2579-
dtype: DTypeLike,
2580-
offset: SupportsIndex = ...
2581-
) -> NDArray[Any]: ...
2565+
def getfield(self, dtype: DTypeLike, offset: SupportsIndex = 0) -> NDArray[Any]: ...
25822566

2583-
def __index__(self: NDArray[np.integer[Any]], /) -> int: ...
2584-
def __int__(self: NDArray[number[Any] | np.timedelta64 | np.bool | object_], /) -> int: ...
2585-
def __float__(self: NDArray[number[Any] | np.timedelta64 | np.bool | object_], /) -> float: ...
2586-
def __complex__(self: NDArray[number[Any] | np.bool | object_], /) -> complex: ...
2567+
def __index__(self: NDArray[integer], /) -> int: ...
2568+
def __complex__(self: NDArray[number | np.bool | object_], /) -> complex: ...
25872569

25882570
def __len__(self) -> int: ...
25892571
def __contains__(self, value: object, /) -> builtins.bool: ...
@@ -2659,9 +2641,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DType_co]):
26592641
# @overload
26602642
# def __abs__(self: ndarray[_ShapeType, dtype[complex128]], /) -> ndarray[_ShapeType, dtype[float64]]: ...
26612643
@overload
2662-
def __abs__(
2663-
self: ndarray[_ShapeT, dtype[complexfloating[_AnyNBitInexact]]], /
2664-
) -> ndarray[_ShapeT, dtype[floating[_AnyNBitInexact]]]: ...
2644+
def __abs__(self: ndarray[_ShapeT, dtype[complexfloating[_NBit]]], /) -> ndarray[_ShapeT, dtype[floating[_NBit]]]: ...
26652645
@overload
26662646
def __abs__(self: _RealArrayT, /) -> _RealArrayT: ...
26672647

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/_globals.pyi

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@ from typing import Final, final
66
@final
77
class _CopyMode(enum.Enum):
88
ALWAYS = True
9-
IF_NEEDED = False
10-
NEVER = 2
9+
NEVER = False
10+
IF_NEEDED = 2
11+
12+
def __bool__(self, /) -> bool: ...
1113

1214
@final
1315
class _NoValueType: ...

0 commit comments

Comments
 (0)