Skip to content

Commit bd1f606

Browse files
authored
Merge pull request numpy#27691 from jorenham/typing/_typeshed
TYP: Use ``_typeshed`` to clean up the stubs
2 parents 052a3be + 6eee093 commit bd1f606

File tree

12 files changed

+97
-194
lines changed

12 files changed

+97
-194
lines changed

numpy/__init__.pyi

Lines changed: 15 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -205,11 +205,11 @@ from typing import (
205205
type_check_only,
206206
)
207207

208-
# NOTE: `typing_extensions` is always available in `.pyi` stubs or when
209-
# `TYPE_CHECKING` - even if not available at runtime.
210-
# This is because the `typeshed` stubs for the standard library include
211-
# `typing_extensions` stubs:
208+
# NOTE: `typing_extensions` and `_typeshed` are always available in `.pyi` stubs, even
209+
# if not available at runtime. This is because the `typeshed` stubs for the standard
210+
# library include `typing_extensions` stubs:
212211
# https://github.com/python/typeshed/blob/main/stdlib/typing_extensions.pyi
212+
from _typeshed import StrOrBytesPath, SupportsFlush, SupportsLenAndGetItem, SupportsWrite
213213
from typing_extensions import CapsuleType, Generic, LiteralString, Protocol, Self, TypeVar, overload
214214

215215
from numpy import (
@@ -306,7 +306,7 @@ from numpy._core._ufunc_config import (
306306
seterrcall,
307307
geterrcall,
308308
_ErrKind,
309-
_ErrFunc,
309+
_ErrCall,
310310
)
311311

312312
from numpy._core.arrayprint import (
@@ -740,28 +740,21 @@ _AnyStr_contra = TypeVar("_AnyStr_contra", LiteralString, builtins.str, bytes, c
740740
# Protocol for representing file-like-objects accepted
741741
# by `ndarray.tofile` and `fromfile`
742742
@type_check_only
743-
class _IOProtocol(Protocol):
744-
def flush(self) -> object: ...
743+
class _IOProtocol(SupportsFlush, Protocol):
745744
def fileno(self) -> int: ...
746745
def tell(self) -> SupportsIndex: ...
747746
def seek(self, offset: int, whence: int, /) -> object: ...
748747

749748
# NOTE: `seek`, `write` and `flush` are technically only required
750749
# for `readwrite`/`write` modes
751750
@type_check_only
752-
class _MemMapIOProtocol(Protocol):
753-
def flush(self) -> object: ...
751+
class _MemMapIOProtocol(SupportsWrite[bytes], SupportsFlush, Protocol):
754752
def fileno(self) -> SupportsIndex: ...
755753
def tell(self) -> int: ...
756754
def seek(self, offset: int, whence: int, /) -> object: ...
757-
def write(self, s: bytes, /) -> object: ...
758755
@property
759756
def read(self) -> object: ...
760757

761-
@type_check_only
762-
class _SupportsWrite(Protocol[_AnyStr_contra]):
763-
def write(self, s: _AnyStr_contra, /) -> object: ...
764-
765758
__version__: LiteralString
766759
__array_api_version__: Final = "2023.12"
767760
test: PytestTester
@@ -1410,17 +1403,12 @@ class _ArrayOrScalarCommon:
14101403
def __eq__(self, other: Any, /) -> Any: ...
14111404
def __ne__(self, other: Any, /) -> Any: ...
14121405
def copy(self, order: _OrderKACF = ...) -> Self: ...
1413-
def dump(self, file: str | bytes | os.PathLike[str] | os.PathLike[bytes] | _SupportsWrite[bytes]) -> None: ...
1406+
def dump(self, file: StrOrBytesPath | SupportsWrite[bytes]) -> None: ...
14141407
def dumps(self) -> bytes: ...
14151408
def tobytes(self, order: _OrderKACF = ...) -> bytes: ...
14161409
# NOTE: `tostring()` is deprecated and therefore excluded
14171410
# def tostring(self, order=...): ...
1418-
def tofile(
1419-
self,
1420-
fid: str | bytes | os.PathLike[str] | os.PathLike[bytes] | _IOProtocol,
1421-
sep: str = ...,
1422-
format: str = ...,
1423-
) -> None: ...
1411+
def tofile(self, fid: StrOrBytesPath | _IOProtocol, sep: str = ..., format: str = ...) -> None: ...
14241412
# generics and 0d arrays return builtin scalars
14251413
def tolist(self) -> Any: ...
14261414
def to_device(self, device: L["cpu"], /, *, stream: None | int | Any = ...) -> Self: ...
@@ -3347,13 +3335,6 @@ _StringType = TypeVar("_StringType", bound=str | bytes)
33473335
_ShapeType = TypeVar("_ShapeType", bound=_Shape)
33483336
_ObjectType = TypeVar("_ObjectType", bound=object)
33493337

3350-
# A sequence-like interface like `collections.abc.Sequence`, but without the
3351-
# irrelevant methods.
3352-
@type_check_only
3353-
class _SimpleSequence(Protocol):
3354-
def __len__(self, /) -> int: ...
3355-
def __getitem__(self, index: int, /) -> Any: ...
3356-
33573338
# The `object_` constructor returns the passed object, so instances with type
33583339
# `object_` cannot exists (at runtime).
33593340
@final
@@ -3363,12 +3344,9 @@ class object_(generic):
33633344
@overload
33643345
def __new__(cls, stringy: _StringType, /) -> _StringType: ...
33653346
@overload
3366-
def __new__(
3367-
cls,
3368-
array: ndarray[_ShapeType, Any], /,
3369-
) -> ndarray[_ShapeType, dtype[object_]]: ...
3347+
def __new__(cls, array: ndarray[_ShapeType, Any], /) -> ndarray[_ShapeType, dtype[object_]]: ...
33703348
@overload
3371-
def __new__(cls, sequence: _SimpleSequence, /) -> NDArray[object_]: ...
3349+
def __new__(cls, sequence: SupportsLenAndGetItem[object], /) -> NDArray[object_]: ...
33723350
@overload
33733351
def __new__(cls, value: _ObjectType, /) -> _ObjectType: ...
33743352
# catch-all
@@ -4134,7 +4112,7 @@ class errstate:
41344112
def __init__(
41354113
self,
41364114
*,
4137-
call: _ErrFunc | _SupportsWrite[str] = ...,
4115+
call: _ErrCall = ...,
41384116
all: None | _ErrKind = ...,
41394117
divide: None | _ErrKind = ...,
41404118
over: None | _ErrKind = ...,
@@ -4413,7 +4391,7 @@ class memmap(ndarray[_ShapeType_co, _DType_co]):
44134391
@overload
44144392
def __new__(
44154393
subtype,
4416-
filename: str | bytes | os.PathLike[str] | os.PathLike[bytes] | _MemMapIOProtocol,
4394+
filename: StrOrBytesPath | _MemMapIOProtocol,
44174395
dtype: type[uint8] = ...,
44184396
mode: _MemMapModeKind = ...,
44194397
offset: int = ...,
@@ -4423,7 +4401,7 @@ class memmap(ndarray[_ShapeType_co, _DType_co]):
44234401
@overload
44244402
def __new__(
44254403
subtype,
4426-
filename: str | bytes | os.PathLike[str] | os.PathLike[bytes] | _MemMapIOProtocol,
4404+
filename: StrOrBytesPath | _MemMapIOProtocol,
44274405
dtype: _DTypeLike[_ScalarType],
44284406
mode: _MemMapModeKind = ...,
44294407
offset: int = ...,
@@ -4433,7 +4411,7 @@ class memmap(ndarray[_ShapeType_co, _DType_co]):
44334411
@overload
44344412
def __new__(
44354413
subtype,
4436-
filename: str | bytes | os.PathLike[str] | os.PathLike[bytes] | _MemMapIOProtocol,
4414+
filename: StrOrBytesPath | _MemMapIOProtocol,
44374415
dtype: DTypeLike,
44384416
mode: _MemMapModeKind = ...,
44394417
offset: int = ...,

numpy/_core/_ufunc_config.pyi

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1+
from _typeshed import SupportsWrite
12
from collections.abc import Callable
23
from typing import Any, Literal, TypeAlias, TypedDict, type_check_only
34

4-
from numpy import _SupportsWrite
5+
from numpy import errstate as errstate
56

67
_ErrKind: TypeAlias = Literal["ignore", "warn", "raise", "call", "print", "log"]
78
_ErrFunc: TypeAlias = Callable[[str, int], Any]
9+
_ErrCall: TypeAlias = _ErrFunc | SupportsWrite[str]
810

911
@type_check_only
1012
class _ErrDict(TypedDict):
@@ -31,9 +33,7 @@ def seterr(
3133
def geterr() -> _ErrDict: ...
3234
def setbufsize(size: int) -> int: ...
3335
def getbufsize() -> int: ...
34-
def seterrcall(
35-
func: None | _ErrFunc | _SupportsWrite[str]
36-
) -> None | _ErrFunc | _SupportsWrite[str]: ...
37-
def geterrcall() -> None | _ErrFunc | _SupportsWrite[str]: ...
36+
def seterrcall(func: _ErrCall | None) -> _ErrCall | None: ...
37+
def geterrcall() -> _ErrCall | None: ...
3838

3939
# See `numpy/__init__.pyi` for the `errstate` class and `no_nep5_warnings`

numpy/_core/multiarray.pyi

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# TODO: Sort out any and all missing functions in this namespace
2-
import os
32
import datetime as dt
3+
from _typeshed import StrOrBytesPath, SupportsLenAndGetItem
44
from collections.abc import Sequence, Callable, Iterable
55
from typing import (
66
Literal as L,
@@ -236,21 +236,13 @@ _RollKind: TypeAlias = L[ # `raise` is deliberately excluded
236236
"modifiedpreceding",
237237
]
238238

239-
@type_check_only
240-
class _SupportsLenAndGetItem(Protocol[_T_contra, _T_co]):
241-
def __len__(self) -> int: ...
242-
def __getitem__(self, key: _T_contra, /) -> _T_co: ...
243-
244239
@type_check_only
245240
class _SupportsArray(Protocol[_ArrayType_co]):
246241
def __array__(self, /) -> _ArrayType_co: ...
247242

248243
@type_check_only
249-
class _KwargsEmptyLike(TypedDict, total=False):
244+
class _KwargsEmpty(TypedDict, total=False):
250245
device: None | L["cpu"]
251-
252-
@type_check_only
253-
class _KwargsEmpty(_KwargsEmptyLike, total=False):
254246
like: None | _SupportsArrayFunc
255247

256248
@type_check_only
@@ -558,7 +550,7 @@ def concatenate( # type: ignore[misc]
558550
) -> NDArray[_SCT]: ...
559551
@overload
560552
def concatenate( # type: ignore[misc]
561-
arrays: _SupportsLenAndGetItem[int, ArrayLike],
553+
arrays: SupportsLenAndGetItem[ArrayLike],
562554
/,
563555
axis: None | SupportsIndex = ...,
564556
out: None = ...,
@@ -568,7 +560,7 @@ def concatenate( # type: ignore[misc]
568560
) -> NDArray[Any]: ...
569561
@overload
570562
def concatenate( # type: ignore[misc]
571-
arrays: _SupportsLenAndGetItem[int, ArrayLike],
563+
arrays: SupportsLenAndGetItem[ArrayLike],
572564
/,
573565
axis: None | SupportsIndex = ...,
574566
out: None = ...,
@@ -578,7 +570,7 @@ def concatenate( # type: ignore[misc]
578570
) -> NDArray[_SCT]: ...
579571
@overload
580572
def concatenate( # type: ignore[misc]
581-
arrays: _SupportsLenAndGetItem[int, ArrayLike],
573+
arrays: SupportsLenAndGetItem[ArrayLike],
582574
/,
583575
axis: None | SupportsIndex = ...,
584576
out: None = ...,
@@ -588,7 +580,7 @@ def concatenate( # type: ignore[misc]
588580
) -> NDArray[Any]: ...
589581
@overload
590582
def concatenate(
591-
arrays: _SupportsLenAndGetItem[int, ArrayLike],
583+
arrays: SupportsLenAndGetItem[ArrayLike],
592584
/,
593585
axis: None | SupportsIndex = ...,
594586
out: _ArrayType = ...,
@@ -963,7 +955,7 @@ def frompyfunc(
963955

964956
@overload
965957
def fromfile(
966-
file: str | bytes | os.PathLike[Any] | _IOProtocol,
958+
file: StrOrBytesPath | _IOProtocol,
967959
dtype: None = ...,
968960
count: SupportsIndex = ...,
969961
sep: str = ...,
@@ -973,7 +965,7 @@ def fromfile(
973965
) -> NDArray[float64]: ...
974966
@overload
975967
def fromfile(
976-
file: str | bytes | os.PathLike[Any] | _IOProtocol,
968+
file: StrOrBytesPath | _IOProtocol,
977969
dtype: _DTypeLike[_SCT],
978970
count: SupportsIndex = ...,
979971
sep: str = ...,
@@ -983,7 +975,7 @@ def fromfile(
983975
) -> NDArray[_SCT]: ...
984976
@overload
985977
def fromfile(
986-
file: str | bytes | os.PathLike[Any] | _IOProtocol,
978+
file: StrOrBytesPath | _IOProtocol,
987979
dtype: DTypeLike,
988980
count: SupportsIndex = ...,
989981
sep: str = ...,

numpy/_core/records.pyi

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import os
1+
from _typeshed import StrOrBytesPath
22
from collections.abc import Sequence, Iterable
33
from types import EllipsisType
44
from typing import (
@@ -225,7 +225,7 @@ def fromstring(
225225

226226
@overload
227227
def fromfile(
228-
fd: str | bytes | os.PathLike[str] | os.PathLike[bytes] | _SupportsReadInto,
228+
fd: StrOrBytesPath | _SupportsReadInto,
229229
dtype: DTypeLike,
230230
shape: None | _ShapeLike = ...,
231231
offset: int = ...,
@@ -237,7 +237,7 @@ def fromfile(
237237
) -> _RecArray[Any]: ...
238238
@overload
239239
def fromfile(
240-
fd: str | bytes | os.PathLike[str] | os.PathLike[bytes] | _SupportsReadInto,
240+
fd: StrOrBytesPath | _SupportsReadInto,
241241
dtype: None = ...,
242242
shape: None | _ShapeLike = ...,
243243
offset: int = ...,

numpy/ctypeslib.pyi

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
# NOTE: Numpy's mypy plugin is used for importing the correct
22
# platform-specific `ctypes._SimpleCData[int]` sub-type
3+
import ctypes
34
from ctypes import c_int64 as _c_intp
45

5-
import os
6-
import ctypes
6+
from _typeshed import StrOrBytesPath
77
from collections.abc import Iterable, Sequence
88
from typing import (
99
Literal as L,
@@ -104,10 +104,7 @@ class _concrete_ndptr(_ndptr[_DType]):
104104
@property
105105
def contents(self) -> ndarray[_Shape, _DType]: ...
106106

107-
def load_library(
108-
libname: str | bytes | os.PathLike[str] | os.PathLike[bytes],
109-
loader_path: str | bytes | os.PathLike[str] | os.PathLike[bytes],
110-
) -> ctypes.CDLL: ...
107+
def load_library(libname: StrOrBytesPath, loader_path: StrOrBytesPath) -> ctypes.CDLL: ...
111108

112109
c_intp = _c_intp
113110

numpy/f2py/__init__.pyi

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import os
1+
from _typeshed import StrOrBytesPath
22
import subprocess
33
from collections.abc import Iterable
4-
from typing import Literal as L, Any, overload, TypedDict, type_check_only
4+
from typing import Literal as L, overload, TypedDict, type_check_only
55

66
__all__ = ["run_main", "get_include"]
77

@@ -18,12 +18,12 @@ class _F2PyDict(_F2PyDictBase, total=False):
1818
def run_main(comline_list: Iterable[str]) -> dict[str, _F2PyDict]: ...
1919

2020
@overload
21-
def compile( # type: ignore[misc]
21+
def compile(
2222
source: str | bytes,
2323
modulename: str = ...,
2424
extra_args: str | list[str] = ...,
2525
verbose: bool = ...,
26-
source_fn: None | str | bytes | os.PathLike[Any] = ...,
26+
source_fn: StrOrBytesPath | None = ...,
2727
extension: L[".f", ".f90"] = ...,
2828
full_output: L[False] = ...,
2929
) -> int: ...
@@ -33,9 +33,10 @@ def compile(
3333
modulename: str = ...,
3434
extra_args: str | list[str] = ...,
3535
verbose: bool = ...,
36-
source_fn: None | str | bytes | os.PathLike[Any] = ...,
36+
source_fn: StrOrBytesPath | None = ...,
3737
extension: L[".f", ".f90"] = ...,
38-
full_output: L[True] = ...,
38+
*,
39+
full_output: L[True],
3940
) -> subprocess.CompletedProcess[bytes]: ...
4041

4142
def get_include() -> str: ...

numpy/lib/_function_base_impl.pyi

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -103,13 +103,10 @@ _2Tuple: TypeAlias = tuple[_T, _T]
103103
@type_check_only
104104
class _TrimZerosSequence(Protocol[_T_co]):
105105
def __len__(self) -> int: ...
106+
@overload
107+
def __getitem__(self, key: int, /) -> object: ...
108+
@overload
106109
def __getitem__(self, key: slice, /) -> _T_co: ...
107-
def __iter__(self) -> Iterator[Any]: ...
108-
109-
@type_check_only
110-
class _SupportsWriteFlush(Protocol):
111-
def write(self, s: str, /) -> object: ...
112-
def flush(self) -> object: ...
113110

114111
@overload
115112
def rot90(
@@ -356,7 +353,6 @@ def sort_complex(a: ArrayLike) -> NDArray[complexfloating[Any, Any]]: ...
356353
def trim_zeros(
357354
filt: _TrimZerosSequence[_T],
358355
trim: L["f", "b", "fb", "bf"] = ...,
359-
axis: SupportsIndex = ...,
360356
) -> _T: ...
361357

362358
@overload

0 commit comments

Comments
 (0)