Skip to content

Commit d11db28

Browse files
Sync typeshed (#15334)
Co-authored-by: Shantanu <[email protected]> Co-authored-by: hauntsaninja <[email protected]>
1 parent 3d2f437 commit d11db28

33 files changed

+425
-171
lines changed

mypy/typeshed/stdlib/VERSIONS

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ antigravity: 2.7-
6161
argparse: 2.7-
6262
array: 2.7-
6363
ast: 2.7-
64-
asynchat: 2.7-
64+
asynchat: 2.7-3.11
6565
asyncio: 3.4-
6666
asyncio.mixins: 3.10-
6767
asyncio.exceptions: 3.8-
@@ -72,7 +72,7 @@ asyncio.taskgroups: 3.11-
7272
asyncio.threads: 3.9-
7373
asyncio.timeouts: 3.11-
7474
asyncio.trsock: 3.8-
75-
asyncore: 2.7-
75+
asyncore: 2.7-3.11
7676
atexit: 2.7-
7777
audioop: 2.7-
7878
base64: 2.7-
@@ -228,7 +228,7 @@ shlex: 2.7-
228228
shutil: 2.7-
229229
signal: 2.7-
230230
site: 2.7-
231-
smtpd: 2.7-
231+
smtpd: 2.7-3.11
232232
smtplib: 2.7-
233233
sndhdr: 2.7-
234234
socket: 2.7-

mypy/typeshed/stdlib/_collections_abc.pyi

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import sys
2+
from abc import abstractmethod
23
from types import MappingProxyType
34
from typing import ( # noqa: Y022,Y038
45
AbstractSet as Set,
@@ -23,11 +24,13 @@ from typing import ( # noqa: Y022,Y038
2324
MutableMapping as MutableMapping,
2425
MutableSequence as MutableSequence,
2526
MutableSet as MutableSet,
27+
Protocol,
2628
Reversible as Reversible,
2729
Sequence as Sequence,
2830
Sized as Sized,
2931
TypeVar,
3032
ValuesView as ValuesView,
33+
runtime_checkable,
3134
)
3235
from typing_extensions import final
3336

@@ -58,6 +61,8 @@ __all__ = [
5861
"MutableSequence",
5962
"ByteString",
6063
]
64+
if sys.version_info >= (3, 12):
65+
__all__ += ["Buffer"]
6166

6267
_KT_co = TypeVar("_KT_co", covariant=True) # Key type covariant containers.
6368
_VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers.
@@ -79,3 +84,9 @@ class dict_items(ItemsView[_KT_co, _VT_co], Generic[_KT_co, _VT_co]): # undocum
7984
if sys.version_info >= (3, 10):
8085
@property
8186
def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ...
87+
88+
if sys.version_info >= (3, 12):
89+
@runtime_checkable
90+
class Buffer(Protocol):
91+
@abstractmethod
92+
def __buffer__(self, __flags: int) -> memoryview: ...

mypy/typeshed/stdlib/_ctypes.pyi

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ class _CData(metaclass=_CDataMeta):
6363
def from_param(cls, obj: Any) -> Self | _CArgObject: ...
6464
@classmethod
6565
def in_dll(cls, library: CDLL, name: str) -> Self: ...
66+
def __buffer__(self, __flags: int) -> memoryview: ...
67+
def __release_buffer__(self, __buffer: memoryview) -> None: ...
6668

6769
class _SimpleCData(Generic[_T], _CData):
6870
value: _T

mypy/typeshed/stdlib/_typeshed/__init__.pyi

Lines changed: 29 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,13 @@
22
#
33
# See the README.md file in this directory for more information.
44

5-
import array
6-
import ctypes
7-
import mmap
8-
import pickle
95
import sys
10-
from collections.abc import Awaitable, Callable, Iterable, Set as AbstractSet
6+
from collections.abc import Awaitable, Callable, Iterable, Sequence, Set as AbstractSet, Sized
117
from dataclasses import Field
128
from os import PathLike
139
from types import FrameType, TracebackType
14-
from typing import Any, AnyStr, ClassVar, Generic, Protocol, TypeVar
15-
from typing_extensions import Final, Literal, LiteralString, TypeAlias, final
10+
from typing import Any, AnyStr, ClassVar, Generic, Protocol, TypeVar, overload
11+
from typing_extensions import Buffer, Final, Literal, LiteralString, TypeAlias, final
1612

1713
_KT = TypeVar("_KT")
1814
_KT_co = TypeVar("_KT_co", covariant=True)
@@ -227,42 +223,33 @@ class SupportsNoArgReadline(Protocol[_T_co]):
227223
class SupportsWrite(Protocol[_T_contra]):
228224
def write(self, __s: _T_contra) -> object: ...
229225

230-
ReadOnlyBuffer: TypeAlias = bytes # stable
226+
# Unfortunately PEP 688 does not allow us to distinguish read-only
227+
# from writable buffers. We use these aliases for readability for now.
228+
# Perhaps a future extension of the buffer protocol will allow us to
229+
# distinguish these cases in the type system.
230+
ReadOnlyBuffer: TypeAlias = Buffer # stable
231231
# Anything that implements the read-write buffer interface.
232-
# The buffer interface is defined purely on the C level, so we cannot define a normal Protocol
233-
# for it (until PEP 688 is implemented). Instead we have to list the most common stdlib buffer classes in a Union.
234-
if sys.version_info >= (3, 8):
235-
WriteableBuffer: TypeAlias = (
236-
bytearray | memoryview | array.array[Any] | mmap.mmap | ctypes._CData | pickle.PickleBuffer
237-
) # stable
238-
else:
239-
WriteableBuffer: TypeAlias = bytearray | memoryview | array.array[Any] | mmap.mmap | ctypes._CData # stable
240-
# Same as _WriteableBuffer, but also includes read-only buffer types (like bytes).
241-
ReadableBuffer: TypeAlias = ReadOnlyBuffer | WriteableBuffer # stable
242-
_BufferWithLen: TypeAlias = ReadableBuffer # not stable # noqa: Y047
243-
244-
# Anything that implements the read-write buffer interface, and can be sliced/indexed.
245-
SliceableBuffer: TypeAlias = bytes | bytearray | memoryview | array.array[Any] | mmap.mmap
246-
IndexableBuffer: TypeAlias = bytes | bytearray | memoryview | array.array[Any] | mmap.mmap
247-
# https://github.com/python/typeshed/pull/9115#issuecomment-1304905864
248-
# Post PEP 688, they should be rewritten as such:
249-
# from collections.abc import Sequence
250-
# from typing import Sized, overload
251-
# class SliceableBuffer(Protocol):
252-
# def __buffer__(self, __flags: int) -> memoryview: ...
253-
# def __getitem__(self, __slice: slice) -> Sequence[int]: ...
254-
# class IndexableBuffer(Protocol):
255-
# def __buffer__(self, __flags: int) -> memoryview: ...
256-
# def __getitem__(self, __i: int) -> int: ...
257-
# class SupportsGetItemBuffer(SliceableBuffer, IndexableBuffer, Protocol):
258-
# def __buffer__(self, __flags: int) -> memoryview: ...
259-
# def __contains__(self, __x: Any) -> bool: ...
260-
# @overload
261-
# def __getitem__(self, __slice: slice) -> Sequence[int]: ...
262-
# @overload
263-
# def __getitem__(self, __i: int) -> int: ...
264-
# class SizedBuffer(Sized, Protocol): # instead of _BufferWithLen
265-
# def __buffer__(self, __flags: int) -> memoryview: ...
232+
WriteableBuffer: TypeAlias = Buffer
233+
# Same as WriteableBuffer, but also includes read-only buffer types (like bytes).
234+
ReadableBuffer: TypeAlias = Buffer # stable
235+
236+
class SliceableBuffer(Buffer, Protocol):
237+
def __getitem__(self, __slice: slice) -> Sequence[int]: ...
238+
239+
class IndexableBuffer(Buffer, Protocol):
240+
def __getitem__(self, __i: int) -> int: ...
241+
242+
class SupportsGetItemBuffer(SliceableBuffer, IndexableBuffer, Protocol):
243+
def __contains__(self, __x: Any) -> bool: ...
244+
@overload
245+
def __getitem__(self, __slice: slice) -> Sequence[int]: ...
246+
@overload
247+
def __getitem__(self, __i: int) -> int: ...
248+
249+
class SizedBuffer(Sized, Buffer, Protocol): ...
250+
251+
# for compatibility with third-party stubs that may use this
252+
_BufferWithLen: TypeAlias = SizedBuffer # not stable # noqa: Y047
266253

267254
ExcInfo: TypeAlias = tuple[type[BaseException], BaseException, TracebackType]
268255
OptExcInfo: TypeAlias = ExcInfo | tuple[None, None, None]

mypy/typeshed/stdlib/argparse.pyi

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import sys
22
from collections.abc import Callable, Generator, Iterable, Sequence
33
from re import Pattern
44
from typing import IO, Any, Generic, NewType, NoReturn, Protocol, TypeVar, overload
5-
from typing_extensions import Literal, TypeAlias
5+
from typing_extensions import Literal, Self, TypeAlias
66

77
__all__ = [
88
"ArgumentParser",
@@ -236,11 +236,19 @@ class HelpFormatter:
236236
_current_indent: int
237237
_level: int
238238
_action_max_length: int
239-
_root_section: Any
240-
_current_section: Any
239+
_root_section: _Section
240+
_current_section: _Section
241241
_whitespace_matcher: Pattern[str]
242242
_long_break_matcher: Pattern[str]
243-
_Section: type[Any] # Nested class
243+
244+
class _Section:
245+
formatter: HelpFormatter
246+
heading: str | None
247+
parent: Self | None
248+
items: list[tuple[Callable[..., str], Iterable[Any]]]
249+
def __init__(self, formatter: HelpFormatter, parent: Self | None, heading: str | None = None) -> None: ...
250+
def format_help(self) -> str: ...
251+
244252
def __init__(self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None) -> None: ...
245253
def _indent(self) -> None: ...
246254
def _dedent(self) -> None: ...
@@ -249,16 +257,16 @@ class HelpFormatter:
249257
def end_section(self) -> None: ...
250258
def add_text(self, text: str | None) -> None: ...
251259
def add_usage(
252-
self, usage: str | None, actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: str | None = None
260+
self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None = None
253261
) -> None: ...
254262
def add_argument(self, action: Action) -> None: ...
255263
def add_arguments(self, actions: Iterable[Action]) -> None: ...
256264
def format_help(self) -> str: ...
257265
def _join_parts(self, part_strings: Iterable[str]) -> str: ...
258266
def _format_usage(
259-
self, usage: str | None, actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: str | None
267+
self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None
260268
) -> str: ...
261-
def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_ArgumentGroup]) -> str: ...
269+
def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup]) -> str: ...
262270
def _format_text(self, text: str) -> str: ...
263271
def _format_action(self, action: Action) -> str: ...
264272
def _format_action_invocation(self, action: Action) -> str: ...

mypy/typeshed/stdlib/array.pyi

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,5 +80,7 @@ class array(MutableSequence[_T], Generic[_T]):
8080
def __rmul__(self, __value: int) -> array[_T]: ...
8181
def __copy__(self) -> array[_T]: ...
8282
def __deepcopy__(self, __unused: Any) -> array[_T]: ...
83+
def __buffer__(self, __flags: int) -> memoryview: ...
84+
def __release_buffer__(self, __buffer: memoryview) -> None: ...
8385

8486
ArrayType = array

mypy/typeshed/stdlib/asyncio/__init__.pyi

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import sys
2-
from collections.abc import Coroutine, Generator
2+
from collections.abc import Awaitable, Coroutine, Generator
33
from typing import Any, TypeVar
44
from typing_extensions import TypeAlias
55

@@ -36,6 +36,8 @@ _T = TypeVar("_T")
3636

3737
# Aliases imported by multiple submodules in typeshed
3838
if sys.version_info >= (3, 12):
39+
_AwaitableLike: TypeAlias = Awaitable[_T]
3940
_CoroutineLike: TypeAlias = Coroutine[Any, Any, _T]
4041
else:
42+
_AwaitableLike: TypeAlias = Generator[Any, None, _T] | Awaitable[_T]
4143
_CoroutineLike: TypeAlias = Generator[Any, None, _T] | Coroutine[Any, Any, _T]

mypy/typeshed/stdlib/asyncio/base_events.pyi

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import ssl
22
import sys
33
from _typeshed import FileDescriptorLike, ReadableBuffer, WriteableBuffer
4-
from asyncio import _CoroutineLike
4+
from asyncio import _AwaitableLike, _CoroutineLike
55
from asyncio.events import AbstractEventLoop, AbstractServer, Handle, TimerHandle, _TaskFactory
66
from asyncio.futures import Future
77
from asyncio.protocols import BaseProtocol
88
from asyncio.tasks import Task
99
from asyncio.transports import BaseTransport, DatagramTransport, ReadTransport, SubprocessTransport, Transport, WriteTransport
10-
from collections.abc import Awaitable, Callable, Generator, Iterable, Sequence
10+
from collections.abc import Callable, Iterable, Sequence
1111
from contextvars import Context
1212
from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket
1313
from typing import IO, Any, TypeVar, overload
@@ -64,11 +64,7 @@ class Server(AbstractServer):
6464

6565
class BaseEventLoop(AbstractEventLoop):
6666
def run_forever(self) -> None: ...
67-
# Can't use a union, see mypy issue # 1873.
68-
@overload
69-
def run_until_complete(self, future: Generator[Any, None, _T]) -> _T: ...
70-
@overload
71-
def run_until_complete(self, future: Awaitable[_T]) -> _T: ...
67+
def run_until_complete(self, future: _AwaitableLike[_T]) -> _T: ...
7268
def stop(self) -> None: ...
7369
def is_running(self) -> bool: ...
7470
def is_closed(self) -> bool: ...

mypy/typeshed/stdlib/asyncio/events.pyi

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ import ssl
22
import sys
33
from _typeshed import FileDescriptorLike, ReadableBuffer, StrPath, Unused, WriteableBuffer
44
from abc import ABCMeta, abstractmethod
5-
from collections.abc import Awaitable, Callable, Coroutine, Generator, Sequence
5+
from collections.abc import Callable, Coroutine, Generator, Sequence
66
from contextvars import Context
77
from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket
88
from typing import IO, Any, Protocol, TypeVar, overload
99
from typing_extensions import Literal, Self, TypeAlias
1010

11-
from . import _CoroutineLike
11+
from . import _AwaitableLike, _CoroutineLike
1212
from .base_events import Server
1313
from .futures import Future
1414
from .protocols import BaseProtocol
@@ -113,13 +113,8 @@ class AbstractEventLoop:
113113
slow_callback_duration: float
114114
@abstractmethod
115115
def run_forever(self) -> None: ...
116-
# Can't use a union, see mypy issue # 1873.
117-
@overload
118116
@abstractmethod
119-
def run_until_complete(self, future: Generator[Any, None, _T]) -> _T: ...
120-
@overload
121-
@abstractmethod
122-
def run_until_complete(self, future: Awaitable[_T]) -> _T: ...
117+
def run_until_complete(self, future: _AwaitableLike[_T]) -> _T: ...
123118
@abstractmethod
124119
def stop(self) -> None: ...
125120
@abstractmethod

mypy/typeshed/stdlib/asyncio/tasks.pyi

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import concurrent.futures
22
import sys
3-
from collections.abc import Awaitable, Generator, Iterable, Iterator
3+
from collections.abc import Awaitable, Coroutine, Generator, Iterable, Iterator
44
from types import FrameType
55
from typing import Any, Generic, TextIO, TypeVar, overload
66
from typing_extensions import Literal, TypeAlias
@@ -275,25 +275,24 @@ else:
275275
) -> tuple[set[Task[_T]], set[Task[_T]]]: ...
276276
async def wait_for(fut: _FutureLike[_T], timeout: float | None, *, loop: AbstractEventLoop | None = None) -> _T: ...
277277

278+
if sys.version_info >= (3, 12):
279+
_TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co]
280+
else:
281+
_TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Awaitable[_T_co]
282+
278283
# mypy and pyright complain that a subclass of an invariant class shouldn't be covariant.
279284
# While this is true in general, here it's sort-of okay to have a covariant subclass,
280285
# since the only reason why `asyncio.Future` is invariant is the `set_result()` method,
281286
# and `asyncio.Task.set_result()` always raises.
282287
class Task(Future[_T_co], Generic[_T_co]): # type: ignore[type-var] # pyright: ignore[reportGeneralTypeIssues]
283288
if sys.version_info >= (3, 8):
284289
def __init__(
285-
self,
286-
coro: Generator[_TaskYieldType, None, _T_co] | Awaitable[_T_co],
287-
*,
288-
loop: AbstractEventLoop = ...,
289-
name: str | None = ...,
290+
self, coro: _TaskCompatibleCoro[_T_co], *, loop: AbstractEventLoop = ..., name: str | None = ...
290291
) -> None: ...
291292
else:
292-
def __init__(
293-
self, coro: Generator[_TaskYieldType, None, _T_co] | Awaitable[_T_co], *, loop: AbstractEventLoop = ...
294-
) -> None: ...
293+
def __init__(self, coro: _TaskCompatibleCoro[_T_co], *, loop: AbstractEventLoop = ...) -> None: ...
295294
if sys.version_info >= (3, 8):
296-
def get_coro(self) -> Generator[_TaskYieldType, None, _T_co] | Awaitable[_T_co]: ...
295+
def get_coro(self) -> _TaskCompatibleCoro[_T_co]: ...
297296
def get_name(self) -> str: ...
298297
def set_name(self, __value: object) -> None: ...
299298

mypy/typeshed/stdlib/binhex.pyi

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from _typeshed import _BufferWithLen
1+
from _typeshed import SizedBuffer
22
from typing import IO, Any
33
from typing_extensions import Literal, TypeAlias
44

@@ -28,9 +28,9 @@ class openrsrc:
2828

2929
class BinHex:
3030
def __init__(self, name_finfo_dlen_rlen: _FileInfoTuple, ofp: _FileHandleUnion) -> None: ...
31-
def write(self, data: _BufferWithLen) -> None: ...
31+
def write(self, data: SizedBuffer) -> None: ...
3232
def close_data(self) -> None: ...
33-
def write_rsrc(self, data: _BufferWithLen) -> None: ...
33+
def write_rsrc(self, data: SizedBuffer) -> None: ...
3434
def close(self) -> None: ...
3535

3636
def binhex(inp: str, out: str) -> None: ...

0 commit comments

Comments
 (0)