Skip to content

Commit ab0bd8c

Browse files
Sync typeshed (#16969)
Source commit: python/typeshed@e050986
1 parent 02c50bc commit ab0bd8c

33 files changed

+437
-191
lines changed

mypy/typeshed/stdlib/VERSIONS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ _heapq: 3.0-
3636
_imp: 3.0-
3737
_json: 3.0-
3838
_locale: 3.0-
39+
_lsprof: 3.0-
3940
_markupbase: 3.0-
4041
_msi: 3.0-
4142
_operator: 3.4-

mypy/typeshed/stdlib/_ctypes.pyi

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ class _CData(metaclass=_CDataMeta):
6464
# Structure.from_buffer(...) # valid at runtime
6565
# Structure(...).from_buffer(...) # invalid at runtime
6666
#
67+
6768
@classmethod
6869
def from_buffer(cls, source: WriteableBuffer, offset: int = ...) -> Self: ...
6970
@classmethod
@@ -106,14 +107,15 @@ class _CArgObject: ...
106107

107108
def byref(obj: _CData, offset: int = ...) -> _CArgObject: ...
108109

109-
_ECT: TypeAlias = Callable[[type[_CData] | None, CFuncPtr, tuple[_CData, ...]], _CData]
110+
_ECT: TypeAlias = Callable[[_CData | None, CFuncPtr, tuple[_CData, ...]], _CData]
110111
_PF: TypeAlias = tuple[int] | tuple[int, str | None] | tuple[int, str | None, Any]
111112

112113
class CFuncPtr(_PointerLike, _CData):
113114
restype: type[_CData] | Callable[[int], Any] | None
114115
argtypes: Sequence[type[_CData]]
115116
errcheck: _ECT
116-
_flags_: ClassVar[int] # Abstract attribute that must be defined on subclasses
117+
# Abstract attribute that must be defined on subclasses
118+
_flags_: ClassVar[int]
117119
@overload
118120
def __init__(self) -> None: ...
119121
@overload

mypy/typeshed/stdlib/_dummy_thread.pyi

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,19 @@
11
from collections.abc import Callable
22
from types import TracebackType
3-
from typing import Any, NoReturn
3+
from typing import Any, NoReturn, overload
4+
from typing_extensions import TypeVarTuple, Unpack
45

56
__all__ = ["error", "start_new_thread", "exit", "get_ident", "allocate_lock", "interrupt_main", "LockType", "RLock"]
67

8+
_Ts = TypeVarTuple("_Ts")
9+
710
TIMEOUT_MAX: int
811
error = RuntimeError
912

10-
def start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any] = {}) -> None: ...
13+
@overload
14+
def start_new_thread(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]]) -> None: ...
15+
@overload
16+
def start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any]) -> None: ...
1117
def exit() -> NoReturn: ...
1218
def get_ident() -> int: ...
1319
def allocate_lock() -> LockType: ...

mypy/typeshed/stdlib/_lsprof.pyi

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import sys
2+
from _typeshed import structseq
3+
from collections.abc import Callable
4+
from types import CodeType
5+
from typing import Any, Final, final
6+
7+
class Profiler:
8+
def __init__(
9+
self, timer: Callable[[], float] | None = None, timeunit: float = 0.0, subcalls: bool = True, builtins: bool = True
10+
) -> None: ...
11+
def getstats(self) -> list[profiler_entry]: ...
12+
def enable(self, subcalls: bool = True, builtins: bool = True) -> None: ...
13+
def disable(self) -> None: ...
14+
def clear(self) -> None: ...
15+
16+
@final
17+
class profiler_entry(structseq[Any], tuple[CodeType | str, int, int, float, float, list[profiler_subentry]]):
18+
if sys.version_info >= (3, 10):
19+
__match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime", "calls")
20+
code: CodeType | str
21+
callcount: int
22+
reccallcount: int
23+
totaltime: float
24+
inlinetime: float
25+
calls: list[profiler_subentry]
26+
27+
@final
28+
class profiler_subentry(structseq[Any], tuple[CodeType | str, int, int, float, float]):
29+
if sys.version_info >= (3, 10):
30+
__match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime")
31+
code: CodeType | str
32+
callcount: int
33+
reccallcount: int
34+
totaltime: float
35+
inlinetime: float

mypy/typeshed/stdlib/_operator.pyi

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -95,16 +95,16 @@ def length_hint(__obj: object, __default: int = 0) -> int: ...
9595
@final
9696
class attrgetter(Generic[_T_co]):
9797
@overload
98-
def __new__(cls, attr: str) -> attrgetter[Any]: ...
98+
def __new__(cls, attr: str, /) -> attrgetter[Any]: ...
9999
@overload
100-
def __new__(cls, attr: str, __attr2: str) -> attrgetter[tuple[Any, Any]]: ...
100+
def __new__(cls, attr: str, attr2: str, /) -> attrgetter[tuple[Any, Any]]: ...
101101
@overload
102-
def __new__(cls, attr: str, __attr2: str, __attr3: str) -> attrgetter[tuple[Any, Any, Any]]: ...
102+
def __new__(cls, attr: str, attr2: str, attr3: str, /) -> attrgetter[tuple[Any, Any, Any]]: ...
103103
@overload
104-
def __new__(cls, attr: str, __attr2: str, __attr3: str, __attr4: str) -> attrgetter[tuple[Any, Any, Any, Any]]: ...
104+
def __new__(cls, attr: str, attr2: str, attr3: str, attr4: str, /) -> attrgetter[tuple[Any, Any, Any, Any]]: ...
105105
@overload
106-
def __new__(cls, attr: str, *attrs: str) -> attrgetter[tuple[Any, ...]]: ...
107-
def __call__(self, obj: Any) -> _T_co: ...
106+
def __new__(cls, attr: str, /, *attrs: str) -> attrgetter[tuple[Any, ...]]: ...
107+
def __call__(self, obj: Any, /) -> _T_co: ...
108108

109109
@final
110110
class itemgetter(Generic[_T_co]):

mypy/typeshed/stdlib/_thread.pyi

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@ from _typeshed import structseq
33
from collections.abc import Callable
44
from threading import Thread
55
from types import TracebackType
6-
from typing import Any, Final, NoReturn, final
6+
from typing import Any, Final, NoReturn, final, overload
7+
from typing_extensions import TypeVarTuple, Unpack
8+
9+
_Ts = TypeVarTuple("_Ts")
710

811
error = RuntimeError
912

@@ -18,7 +21,10 @@ class LockType:
1821
self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None
1922
) -> None: ...
2023

21-
def start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any] = ...) -> int: ...
24+
@overload
25+
def start_new_thread(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]]) -> int: ...
26+
@overload
27+
def start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any]) -> int: ...
2228
def interrupt_main() -> None: ...
2329
def exit() -> NoReturn: ...
2430
def allocate_lock() -> LockType: ...

mypy/typeshed/stdlib/abc.pyi

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import sys
33
from _typeshed import SupportsWrite
44
from collections.abc import Callable
55
from typing import Any, Literal, TypeVar
6-
from typing_extensions import Concatenate, ParamSpec
6+
from typing_extensions import Concatenate, ParamSpec, deprecated
77

88
_T = TypeVar("_T")
99
_R_co = TypeVar("_R_co", covariant=True)
@@ -28,15 +28,17 @@ class ABCMeta(type):
2828
def register(cls: ABCMeta, subclass: type[_T]) -> type[_T]: ...
2929

3030
def abstractmethod(funcobj: _FuncT) -> _FuncT: ...
31-
31+
@deprecated("Deprecated, use 'classmethod' with 'abstractmethod' instead")
3232
class abstractclassmethod(classmethod[_T, _P, _R_co]):
3333
__isabstractmethod__: Literal[True]
3434
def __init__(self, callable: Callable[Concatenate[type[_T], _P], _R_co]) -> None: ...
3535

36+
@deprecated("Deprecated, use 'staticmethod' with 'abstractmethod' instead")
3637
class abstractstaticmethod(staticmethod[_P, _R_co]):
3738
__isabstractmethod__: Literal[True]
3839
def __init__(self, callable: Callable[_P, _R_co]) -> None: ...
3940

41+
@deprecated("Deprecated, use 'property' with 'abstractmethod' instead")
4042
class abstractproperty(property):
4143
__isabstractmethod__: Literal[True]
4244

mypy/typeshed/stdlib/argparse.pyi

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ from _typeshed import sentinel
33
from collections.abc import Callable, Generator, Iterable, Sequence
44
from re import Pattern
55
from typing import IO, Any, Generic, Literal, NewType, NoReturn, Protocol, TypeVar, overload
6-
from typing_extensions import Self, TypeAlias
6+
from typing_extensions import Self, TypeAlias, deprecated
77

88
__all__ = [
99
"ArgumentParser",
@@ -339,11 +339,23 @@ class Action(_AttributeHolder):
339339

340340
if sys.version_info >= (3, 12):
341341
class BooleanOptionalAction(Action):
342+
@overload
342343
def __init__(
343344
self,
344345
option_strings: Sequence[str],
345346
dest: str,
346-
default: _T | str | None = None,
347+
default: bool | None = None,
348+
*,
349+
required: bool = False,
350+
help: str | None = None,
351+
) -> None: ...
352+
@overload
353+
@deprecated("The `type`, `choices`, and `metavar` parameters are ignored and will be removed in Python 3.14.")
354+
def __init__(
355+
self,
356+
option_strings: Sequence[str],
357+
dest: str,
358+
default: _T | bool | None = None,
347359
type: Callable[[str], _T] | FileType | None = sentinel,
348360
choices: Iterable[_T] | None = sentinel,
349361
required: bool = False,
@@ -353,11 +365,23 @@ if sys.version_info >= (3, 12):
353365

354366
elif sys.version_info >= (3, 9):
355367
class BooleanOptionalAction(Action):
368+
@overload
369+
def __init__(
370+
self,
371+
option_strings: Sequence[str],
372+
dest: str,
373+
default: bool | None = None,
374+
*,
375+
required: bool = False,
376+
help: str | None = None,
377+
) -> None: ...
378+
@overload
379+
@deprecated("The `type`, `choices`, and `metavar` parameters are ignored and will be removed in Python 3.14.")
356380
def __init__(
357381
self,
358382
option_strings: Sequence[str],
359383
dest: str,
360-
default: _T | str | None = None,
384+
default: _T | bool | None = None,
361385
type: Callable[[str], _T] | FileType | None = None,
362386
choices: Iterable[_T] | None = None,
363387
required: bool = False,

mypy/typeshed/stdlib/asyncio/events.pyi

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -543,10 +543,18 @@ class AbstractEventLoopPolicy:
543543
@abstractmethod
544544
def new_event_loop(self) -> AbstractEventLoop: ...
545545
# Child processes handling (Unix only).
546-
@abstractmethod
547-
def get_child_watcher(self) -> AbstractChildWatcher: ...
548-
@abstractmethod
549-
def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ...
546+
if sys.version_info >= (3, 12):
547+
@abstractmethod
548+
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
549+
def get_child_watcher(self) -> AbstractChildWatcher: ...
550+
@abstractmethod
551+
@deprecated("Deprecated as of Python 3.12; will be removed in Python 3.14")
552+
def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ...
553+
else:
554+
@abstractmethod
555+
def get_child_watcher(self) -> AbstractChildWatcher: ...
556+
@abstractmethod
557+
def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ...
550558

551559
class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy, metaclass=ABCMeta):
552560
def get_event_loop(self) -> AbstractEventLoop: ...

mypy/typeshed/stdlib/asyncio/tasks.pyi

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -375,14 +375,16 @@ else:
375375

376376
if sys.version_info >= (3, 12):
377377
_TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co]
378+
elif sys.version_info >= (3, 9):
379+
_TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co]
378380
else:
379381
_TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Awaitable[_T_co]
380382

381383
# mypy and pyright complain that a subclass of an invariant class shouldn't be covariant.
382384
# While this is true in general, here it's sort-of okay to have a covariant subclass,
383385
# since the only reason why `asyncio.Future` is invariant is the `set_result()` method,
384386
# and `asyncio.Task.set_result()` always raises.
385-
class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportGeneralTypeIssues]
387+
class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments]
386388
if sys.version_info >= (3, 12):
387389
def __init__(
388390
self,

mypy/typeshed/stdlib/builtins.pyi

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,7 @@ class str(Sequence[str]):
437437
def capitalize(self) -> str: ... # type: ignore[misc]
438438
def casefold(self) -> str: ... # type: ignore[misc]
439439
def center(self, __width: SupportsIndex, __fillchar: str = " ") -> str: ... # type: ignore[misc]
440-
def count(self, x: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ...
440+
def count(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ...
441441
def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: ...
442442
def endswith(
443443
self, __suffix: str | tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...
@@ -1130,7 +1130,7 @@ class property:
11301130
class _NotImplementedType(Any):
11311131
# A little weird, but typing the __call__ as NotImplemented makes the error message
11321132
# for NotImplemented() much better
1133-
__call__: NotImplemented # type: ignore[valid-type] # pyright: ignore[reportGeneralTypeIssues]
1133+
__call__: NotImplemented # type: ignore[valid-type] # pyright: ignore[reportInvalidTypeForm]
11341134

11351135
NotImplemented: _NotImplementedType
11361136

@@ -1544,9 +1544,9 @@ def quit(code: sys._ExitCode = None) -> NoReturn: ...
15441544

15451545
class reversed(Iterator[_T]):
15461546
@overload
1547-
def __init__(self, __sequence: Reversible[_T]) -> None: ...
1547+
def __new__(cls, __sequence: Reversible[_T]) -> Iterator[_T]: ... # type: ignore[misc]
15481548
@overload
1549-
def __init__(self, __sequence: SupportsLenAndGetItem[_T]) -> None: ...
1549+
def __new__(cls, __sequence: SupportsLenAndGetItem[_T]) -> Iterator[_T]: ... # type: ignore[misc]
15501550
def __iter__(self) -> Self: ...
15511551
def __next__(self) -> _T: ...
15521552
def __length_hint__(self) -> int: ...

mypy/typeshed/stdlib/cProfile.pyi

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import _lsprof
12
from _typeshed import StrOrBytesPath, Unused
23
from collections.abc import Callable
34
from types import CodeType
@@ -15,13 +16,8 @@ _T = TypeVar("_T")
1516
_P = ParamSpec("_P")
1617
_Label: TypeAlias = tuple[str, int, str]
1718

18-
class Profile:
19+
class Profile(_lsprof.Profiler):
1920
stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]] # undocumented
20-
def __init__(
21-
self, timer: Callable[[], float] = ..., timeunit: float = ..., subcalls: bool = ..., builtins: bool = ...
22-
) -> None: ...
23-
def enable(self) -> None: ...
24-
def disable(self) -> None: ...
2521
def print_stats(self, sort: str | int = -1) -> None: ...
2622
def dump_stats(self, file: StrOrBytesPath) -> None: ...
2723
def create_stats(self) -> None: ...

mypy/typeshed/stdlib/datetime.pyi

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
11
import sys
22
from abc import abstractmethod
33
from time import struct_time
4-
from typing import ClassVar, Literal, NamedTuple, NoReturn, SupportsIndex, TypeVar, final, overload
5-
from typing_extensions import Self, TypeAlias
4+
from typing import ClassVar, Literal, NamedTuple, NoReturn, SupportsIndex, final, overload
5+
from typing_extensions import Self, TypeAlias, deprecated
66

77
if sys.version_info >= (3, 11):
88
__all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR", "UTC")
99
elif sys.version_info >= (3, 9):
1010
__all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR")
1111

12-
_D = TypeVar("_D", bound=date)
13-
1412
MINYEAR: Literal[1]
1513
MAXYEAR: Literal[9999]
1614

@@ -90,11 +88,11 @@ class date:
9088
def __add__(self, __value: timedelta) -> Self: ...
9189
def __radd__(self, __value: timedelta) -> Self: ...
9290
@overload
93-
def __sub__(self, __value: timedelta) -> Self: ...
94-
@overload
9591
def __sub__(self, __value: datetime) -> NoReturn: ...
9692
@overload
97-
def __sub__(self: _D, __value: _D) -> timedelta: ...
93+
def __sub__(self, __value: Self) -> timedelta: ...
94+
@overload
95+
def __sub__(self, __value: timedelta) -> Self: ...
9896
def __hash__(self) -> int: ...
9997
def weekday(self) -> int: ...
10098
def isoweekday(self) -> int: ...
@@ -251,10 +249,12 @@ class datetime(date):
251249
def fromtimestamp(cls, __timestamp: float, tz: _TzInfo | None = ...) -> Self: ...
252250

253251
@classmethod
252+
@deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .fromtimestamp(datetime.UTC)")
254253
def utcfromtimestamp(cls, __t: float) -> Self: ...
255254
@classmethod
256255
def now(cls, tz: _TzInfo | None = None) -> Self: ...
257256
@classmethod
257+
@deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.UTC)")
258258
def utcnow(cls) -> Self: ...
259259
@classmethod
260260
def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo | None = ...) -> Self: ...
@@ -290,6 +290,6 @@ class datetime(date):
290290
def __eq__(self, __value: object) -> bool: ...
291291
def __hash__(self) -> int: ...
292292
@overload # type: ignore[override]
293-
def __sub__(self, __value: timedelta) -> Self: ...
293+
def __sub__(self, __value: Self) -> timedelta: ...
294294
@overload
295-
def __sub__(self: _D, __value: _D) -> timedelta: ...
295+
def __sub__(self, __value: timedelta) -> Self: ...

mypy/typeshed/stdlib/difflib.pyi

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import sys
22
from collections.abc import Callable, Iterable, Iterator, Sequence
3-
from typing import Any, AnyStr, Generic, NamedTuple, TypeVar, overload
3+
from typing import Any, AnyStr, Generic, Literal, NamedTuple, TypeVar, overload
44

55
if sys.version_info >= (3, 9):
66
from types import GenericAlias
@@ -49,7 +49,7 @@ class SequenceMatcher(Generic[_T]):
4949
def find_longest_match(self, alo: int, ahi: int, blo: int, bhi: int) -> Match: ...
5050

5151
def get_matching_blocks(self) -> list[Match]: ...
52-
def get_opcodes(self) -> list[tuple[str, int, int, int, int]]: ...
52+
def get_opcodes(self) -> list[tuple[Literal["replace", "delete", "insert", "equal"], int, int, int, int]]: ...
5353
def get_grouped_opcodes(self, n: int = 3) -> Iterable[list[tuple[str, int, int, int, int]]]: ...
5454
def ratio(self) -> float: ...
5555
def quick_ratio(self) -> float: ...

0 commit comments

Comments
 (0)