Skip to content

TYP: Backport typing fixes from main (4) #28542

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Mar 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 8 additions & 28 deletions numpy/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -2231,11 +2231,9 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DType_co]):
@overload
def resize(self, new_shape: _ShapeLike, /, *, refcheck: builtins.bool = ...) -> None: ...
@overload
def resize(self, *new_shape: SupportsIndex, refcheck: builtins.bool = ...) -> None: ...
def resize(self, /, *new_shape: SupportsIndex, refcheck: builtins.bool = ...) -> None: ...

def setflags(
self, write: builtins.bool = ..., align: builtins.bool = ..., uic: builtins.bool = ...
) -> None: ...
def setflags(self, write: builtins.bool = ..., align: builtins.bool = ..., uic: builtins.bool = ...) -> None: ...

def squeeze(
self,
Expand Down Expand Up @@ -2381,13 +2379,6 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DType_co]):
sorter: None | _ArrayLikeInt_co = ...,
) -> NDArray[intp]: ...

def setfield(
self,
val: ArrayLike,
dtype: DTypeLike,
offset: SupportsIndex = ...,
) -> None: ...

def sort(
self,
axis: SupportsIndex = ...,
Expand Down Expand Up @@ -2567,23 +2558,14 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DType_co]):
@overload # (dtype: ?, type: type[T])
def view(self, /, dtype: DTypeLike, type: type[_ArrayT]) -> _ArrayT: ...

def setfield(self, /, val: ArrayLike, dtype: DTypeLike, offset: CanIndex = 0) -> None: ...
@overload
def getfield(
self,
dtype: _DTypeLike[_SCT],
offset: SupportsIndex = ...
) -> NDArray[_SCT]: ...
def getfield(self, dtype: _DTypeLike[_SCT], offset: SupportsIndex = 0) -> NDArray[_SCT]: ...
@overload
def getfield(
self,
dtype: DTypeLike,
offset: SupportsIndex = ...
) -> NDArray[Any]: ...
def getfield(self, dtype: DTypeLike, offset: SupportsIndex = 0) -> NDArray[Any]: ...

def __index__(self: NDArray[np.integer[Any]], /) -> int: ...
def __int__(self: NDArray[number[Any] | np.timedelta64 | np.bool | object_], /) -> int: ...
def __float__(self: NDArray[number[Any] | np.timedelta64 | np.bool | object_], /) -> float: ...
def __complex__(self: NDArray[number[Any] | np.bool | object_], /) -> complex: ...
def __index__(self: NDArray[integer], /) -> int: ...
def __complex__(self: NDArray[number | np.bool | object_], /) -> complex: ...

def __len__(self) -> int: ...
def __contains__(self, value: object, /) -> builtins.bool: ...
Expand Down Expand Up @@ -2659,9 +2641,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DType_co]):
# @overload
# def __abs__(self: ndarray[_ShapeType, dtype[complex128]], /) -> ndarray[_ShapeType, dtype[float64]]: ...
@overload
def __abs__(
self: ndarray[_ShapeT, dtype[complexfloating[_AnyNBitInexact]]], /
) -> ndarray[_ShapeT, dtype[floating[_AnyNBitInexact]]]: ...
def __abs__(self: ndarray[_ShapeT, dtype[complexfloating[_NBit]]], /) -> ndarray[_ShapeT, dtype[floating[_NBit]]]: ...
@overload
def __abs__(self: _RealArrayT, /) -> _RealArrayT: ...

Expand Down
64 changes: 53 additions & 11 deletions numpy/_core/_internal.pyi
Original file line number Diff line number Diff line change
@@ -1,30 +1,72 @@
from typing import Any, TypeVar, overload, Generic
import ctypes as ct
import re
from collections.abc import Callable, Iterable
from typing import Any, Final, Generic, overload

from numpy.typing import NDArray
from typing_extensions import Self, TypeVar, deprecated

import numpy as np
import numpy.typing as npt
from numpy.ctypeslib import c_intp

_CastT = TypeVar("_CastT", bound=ct._CanCastTo) # Copied from `ctypes.cast`
_CastT = TypeVar("_CastT", bound=ct._CanCastTo)
_T_co = TypeVar("_T_co", covariant=True)
_CT = TypeVar("_CT", bound=ct._CData)
_PT = TypeVar("_PT", bound=int)
_PT_co = TypeVar("_PT_co", bound=int | None, default=None, covariant=True)

###

IS_PYPY: Final[bool] = ...

format_re: Final[re.Pattern[str]] = ...
sep_re: Final[re.Pattern[str]] = ...
space_re: Final[re.Pattern[str]] = ...

###

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

class _ctypes(Generic[_PT]):
class _ctypes(Generic[_PT_co]):
@overload
def __new__(cls, array: NDArray[Any], ptr: None = ...) -> _ctypes[None]: ...
def __init__(self: _ctypes[None], /, array: npt.NDArray[Any], ptr: None = None) -> None: ...
@overload
def __new__(cls, array: NDArray[Any], ptr: _PT) -> _ctypes[_PT]: ...
def __init__(self, /, array: npt.NDArray[Any], ptr: _PT_co) -> None: ...

#
@property
def data(self) -> _PT: ...
def data(self) -> _PT_co: ...
@property
def shape(self) -> ct.Array[c_intp]: ...
@property
def strides(self) -> ct.Array[c_intp]: ...
@property
def _as_parameter_(self) -> ct.c_void_p: ...

def data_as(self, obj: type[_CastT]) -> _CastT: ...
def shape_as(self, obj: type[_CT]) -> ct.Array[_CT]: ...
def strides_as(self, obj: type[_CT]) -> ct.Array[_CT]: ...
#
def data_as(self, /, obj: type[_CastT]) -> _CastT: ...
def shape_as(self, /, obj: type[_CT]) -> ct.Array[_CT]: ...
def strides_as(self, /, obj: type[_CT]) -> ct.Array[_CT]: ...

#
@deprecated('"get_data" is deprecated. Use "data" instead')
def get_data(self, /) -> _PT_co: ...
@deprecated('"get_shape" is deprecated. Use "shape" instead')
def get_shape(self, /) -> ct.Array[c_intp]: ...
@deprecated('"get_strides" is deprecated. Use "strides" instead')
def get_strides(self, /) -> ct.Array[c_intp]: ...
@deprecated('"get_as_parameter" is deprecated. Use "_as_parameter_" instead')
def get_as_parameter(self, /) -> ct.c_void_p: ...

class dummy_ctype(Generic[_T_co]):
_cls: type[_T_co]

def __init__(self, /, cls: type[_T_co]) -> None: ...
def __eq__(self, other: Self, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
def __ne__(self, other: Self, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
def __mul__(self, other: object, /) -> Self: ...
def __call__(self, /, *other: object) -> _T_co: ...

def array_ufunc_errmsg_formatter(dummy: object, ufunc: np.ufunc, method: str, *inputs: object, **kwargs: object) -> str: ...
def array_function_errmsg_formatter(public_api: Callable[..., object], types: Iterable[str]) -> str: ...
def npy_ctypes_check(cls: type) -> bool: ...
4 changes: 3 additions & 1 deletion numpy/_core/arrayprint.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ from typing import Any, Final, Literal, SupportsIndex, TypeAlias, TypedDict, ove
from typing_extensions import deprecated

import numpy as np
from numpy._globals import _NoValueType
from numpy._typing import NDArray, _CharLike_co, _FloatLike_co

__all__ = [
Expand Down Expand Up @@ -93,13 +94,14 @@ def array2string(
suppress_small: bool | None = None,
separator: str = " ",
prefix: str = "",
*,
style: _NoValueType = ...,
formatter: _FormatDict | None = None,
threshold: int | None = None,
edgeitems: int | None = None,
sign: _Sign | None = None,
floatmode: _FloatMode | None = None,
suffix: str = "",
*,
legacy: _Legacy | None = None,
) -> str: ...
@overload # style=<given> (positional), legacy="1.13"
Expand Down
3 changes: 2 additions & 1 deletion numpy/_core/einsumfunc.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -180,5 +180,6 @@ def einsum_path(
subscripts: str | _ArrayLikeInt_co,
/,
*operands: _ArrayLikeComplex_co | _DTypeLikeObject,
optimize: _OptimizeKind = ...,
optimize: _OptimizeKind = "greedy",
einsum_call: Literal[False] = False,
) -> tuple[list[Any], str]: ...
3 changes: 2 additions & 1 deletion numpy/_core/multiarray.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,8 @@ class _ConstructorEmpty(Protocol):
**kwargs: Unpack[_KwargsEmpty],
) -> NDArray[Any]: ...

error: Final = Exception
# using `Final` or `TypeAlias` will break stubtest
error = Exception

# from ._multiarray_umath
ITEM_HASOBJECT: Final[L[1]]
Expand Down
41 changes: 25 additions & 16 deletions numpy/_core/records.pyi
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
# ruff: noqa: ANN401
# pyright: reportSelfClsParameterName=false
from collections.abc import Iterable, Sequence
from types import EllipsisType
from typing import Any, Literal, Protocol, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only
from typing import Any, ClassVar, Literal, Protocol, SupportsIndex, TypeAlias, overload, type_check_only

from _typeshed import StrOrBytesPath
from typing_extensions import TypeVar

from numpy import _ByteOrder, _OrderKACF, _SupportsBuffer, dtype, generic, ndarray, void
import numpy as np
from numpy import _ByteOrder, _OrderKACF, _SupportsBuffer
from numpy._typing import ArrayLike, DTypeLike, NDArray, _ArrayLikeVoid_co, _NestedSequence, _ShapeLike

__all__ = [
Expand All @@ -22,11 +23,11 @@ __all__ = [
]

_T = TypeVar("_T")
_SCT = TypeVar("_SCT", bound=generic)
_DType_co = TypeVar("_DType_co", bound=dtype[Any], covariant=True)
_SCT = TypeVar("_SCT", bound=np.generic)
_DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype[Any], covariant=True)
_ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], covariant=True)

_RecArray: TypeAlias = recarray[Any, dtype[_SCT]]
_RecArray: TypeAlias = recarray[Any, np.dtype[_SCT]]

@type_check_only
class _SupportsReadInto(Protocol):
Expand All @@ -37,7 +38,7 @@ class _SupportsReadInto(Protocol):
###

# exported in `numpy.rec`
class record(void):
class record(np.void):
def __getattribute__(self, attr: str) -> Any: ...
def __setattr__(self, attr: str, val: ArrayLike) -> None: ...
def pprint(self) -> str: ...
Expand All @@ -47,10 +48,9 @@ class record(void):
def __getitem__(self, key: list[str]) -> record: ...

# exported in `numpy.rec`
class recarray(ndarray[_ShapeT_co, _DType_co]):
# NOTE: While not strictly mandatory, we're demanding here that arguments
# for the `format_parser`- and `dtype`-based dtype constructors are
# mutually exclusive
class recarray(np.ndarray[_ShapeT_co, _DTypeT_co]):
__name__: ClassVar[Literal["record"]] = "record"
__module__: Literal["numpy"] = "numpy"
@overload
def __new__(
subtype,
Expand All @@ -66,7 +66,7 @@ class recarray(ndarray[_ShapeT_co, _DType_co]):
byteorder: _ByteOrder | None = None,
aligned: bool = False,
order: _OrderKACF = "C",
) -> recarray[Any, dtype[record]]: ...
) -> _RecArray[record]: ...
@overload
def __new__(
subtype,
Expand All @@ -81,18 +81,20 @@ class recarray(ndarray[_ShapeT_co, _DType_co]):
byteorder: None = None,
aligned: Literal[False] = False,
order: _OrderKACF = "C",
) -> recarray[Any, dtype[Any]]: ...
) -> _RecArray[Any]: ...
def __array_finalize__(self, /, obj: object) -> None: ...
def __getattribute__(self, attr: str, /) -> Any: ...
def __setattr__(self, attr: str, val: ArrayLike, /) -> None: ...
@overload
def field(self, /, attr: int | str, val: None = None) -> Any: ...

#
@overload
def field(self, /, attr: int | str, val: ArrayLike) -> None: ...
@overload
def field(self, /, attr: int | str, val: None = None) -> Any: ...

# exported in `numpy.rec`
class format_parser:
dtype: dtype[void]
dtype: np.dtype[np.void]
def __init__(
self,
/,
Expand Down Expand Up @@ -213,6 +215,7 @@ def array(
dtype: None = None,
shape: _ShapeLike | None = None,
offset: int = 0,
strides: tuple[int, ...] | None = None,
formats: None = None,
names: None = None,
titles: None = None,
Expand All @@ -226,6 +229,7 @@ def array(
dtype: DTypeLike,
shape: _ShapeLike | None = None,
offset: int = 0,
strides: tuple[int, ...] | None = None,
formats: None = None,
names: None = None,
titles: None = None,
Expand All @@ -239,6 +243,7 @@ def array(
dtype: None = None,
shape: _ShapeLike | None = None,
offset: int = 0,
strides: tuple[int, ...] | None = None,
*,
formats: DTypeLike,
names: str | Sequence[str] | None = None,
Expand All @@ -253,6 +258,7 @@ def array(
dtype: DTypeLike,
shape: _ShapeLike,
offset: int = 0,
strides: tuple[int, ...] | None = None,
formats: None = None,
names: None = None,
titles: None = None,
Expand All @@ -267,6 +273,7 @@ def array(
*,
shape: _ShapeLike,
offset: int = 0,
strides: tuple[int, ...] | None = None,
formats: DTypeLike,
names: str | Sequence[str] | None = None,
titles: str | Sequence[str] | None = None,
Expand All @@ -280,6 +287,7 @@ def array(
dtype: DTypeLike,
shape: _ShapeLike | None = None,
offset: int = 0,
strides: tuple[int, ...] | None = None,
formats: None = None,
names: None = None,
titles: None = None,
Expand All @@ -293,6 +301,7 @@ def array(
dtype: None = None,
shape: _ShapeLike | None = None,
offset: int = 0,
strides: tuple[int, ...] | None = None,
*,
formats: DTypeLike,
names: str | Sequence[str] | None = None,
Expand Down
6 changes: 4 additions & 2 deletions numpy/_globals.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ from typing import Final, final
@final
class _CopyMode(enum.Enum):
ALWAYS = True
IF_NEEDED = False
NEVER = 2
NEVER = False
IF_NEEDED = 2

def __bool__(self, /) -> bool: ...

@final
class _NoValueType: ...
Expand Down
Loading
Loading