From fc2b0d104bfed41a8ea6c1057a71cd902259c038 Mon Sep 17 00:00:00 2001 From: mypybot <> Date: Wed, 15 Apr 2026 00:19:12 +0000 Subject: [PATCH 01/10] Sync typeshed Source commit: https://github.com/python/typeshed/commit/c03c2b926422c82ab680d27f3ad2491845000802 --- mypy/typeshed/stdlib/_asyncio.pyi | 4 +- mypy/typeshed/stdlib/_codecs.pyi | 4 +- mypy/typeshed/stdlib/_ctypes.pyi | 6 +- mypy/typeshed/stdlib/_operator.pyi | 79 +++++++----- mypy/typeshed/stdlib/_socket.pyi | 4 +- mypy/typeshed/stdlib/_sqlite3.pyi | 2 +- mypy/typeshed/stdlib/_ssl.pyi | 6 +- mypy/typeshed/stdlib/_typeshed/__init__.pyi | 6 + mypy/typeshed/stdlib/argparse.pyi | 44 ++++--- mypy/typeshed/stdlib/builtins.pyi | 116 ++++++++++++++++-- mypy/typeshed/stdlib/codecs.pyi | 4 +- .../stdlib/concurrent/futures/process.pyi | 2 +- .../concurrent/interpreters/__init__.pyi | 2 +- .../concurrent/interpreters/_crossinterp.pyi | 2 +- .../concurrent/interpreters/_queues.pyi | 2 +- mypy/typeshed/stdlib/configparser.pyi | 6 +- mypy/typeshed/stdlib/contextlib.pyi | 33 +++-- mypy/typeshed/stdlib/csv.pyi | 4 +- mypy/typeshed/stdlib/email/message.pyi | 2 +- mypy/typeshed/stdlib/fileinput.pyi | 6 +- mypy/typeshed/stdlib/itertools.pyi | 38 +++--- mypy/typeshed/stdlib/json/__init__.pyi | 6 +- .../stdlib/lib2to3/fixes/fix_except.pyi | 2 +- .../stdlib/lib2to3/fixes/fix_import.pyi | 2 +- .../stdlib/lib2to3/fixes/fix_imports.pyi | 2 +- .../stdlib/lib2to3/fixes/fix_metaclass.pyi | 2 +- .../stdlib/lib2to3/fixes/fix_renames.pyi | 2 +- .../stdlib/lib2to3/fixes/fix_urllib.pyi | 2 +- mypy/typeshed/stdlib/lib2to3/refactor.pyi | 4 +- mypy/typeshed/stdlib/multiprocessing/pool.pyi | 4 +- mypy/typeshed/stdlib/os/__init__.pyi | 42 ++++++- mypy/typeshed/stdlib/pathlib/__init__.pyi | 10 +- mypy/typeshed/stdlib/sqlite3/__init__.pyi | 6 +- mypy/typeshed/stdlib/ssl.pyi | 16 +-- mypy/typeshed/stdlib/time.pyi | 6 +- mypy/typeshed/stdlib/tokenize.pyi | 4 +- mypy/typeshed/stdlib/traceback.pyi | 10 +- mypy/typeshed/stdlib/typing.pyi | 9 +- mypy/typeshed/stdlib/typing_extensions.pyi | 2 +- .../typeshed/stdlib/xml/etree/ElementPath.pyi | 6 +- .../typeshed/stdlib/xml/etree/ElementTree.pyi | 10 +- 41 files changed, 349 insertions(+), 170 deletions(-) diff --git a/mypy/typeshed/stdlib/_asyncio.pyi b/mypy/typeshed/stdlib/_asyncio.pyi index f43178e4d7258..d663f5d935554 100644 --- a/mypy/typeshed/stdlib/_asyncio.pyi +++ b/mypy/typeshed/stdlib/_asyncio.pyi @@ -1,6 +1,6 @@ import sys from asyncio.events import AbstractEventLoop -from collections.abc import Awaitable, Callable, Coroutine, Generator, Iterable +from collections.abc import Awaitable, Callable, Coroutine, Generator from contextvars import Context from types import FrameType, GenericAlias from typing import Any, Literal, TextIO, TypeVar @@ -11,7 +11,7 @@ _T_co = TypeVar("_T_co", covariant=True) _TaskYieldType: TypeAlias = Future[object] | None @disjoint_base -class Future(Awaitable[_T], Iterable[_T]): +class Future(Awaitable[_T]): _state: str @property def _exception(self) -> BaseException | None: ... diff --git a/mypy/typeshed/stdlib/_codecs.pyi b/mypy/typeshed/stdlib/_codecs.pyi index 89f97edb9ba81..89cb78c33571d 100644 --- a/mypy/typeshed/stdlib/_codecs.pyi +++ b/mypy/typeshed/stdlib/_codecs.pyi @@ -77,7 +77,9 @@ def ascii_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[st def ascii_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... def charmap_decode(data: ReadableBuffer, errors: str | None = None, mapping: _CharMap | None = None, /) -> tuple[str, int]: ... def charmap_encode(str: str, errors: str | None = None, mapping: _CharMap | None = None, /) -> tuple[bytes, int]: ... -def escape_decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... + +# Docs say this accepts a bytes-like object, but in practice it also accepts str. +def escape_decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[bytes, int]: ... def escape_encode(data: bytes, errors: str | None = None, /) -> tuple[bytes, int]: ... def latin_1_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... def latin_1_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... diff --git a/mypy/typeshed/stdlib/_ctypes.pyi b/mypy/typeshed/stdlib/_ctypes.pyi index 0e02092a361c9..3c4308628c8c9 100644 --- a/mypy/typeshed/stdlib/_ctypes.pyi +++ b/mypy/typeshed/stdlib/_ctypes.pyi @@ -320,7 +320,11 @@ class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): def _type_(self) -> type[_CT]: ... @_type_.setter def _type_(self, value: type[_CT]) -> None: ... - raw: bytes # Note: only available if _CT == c_char + # Note: only available if _CT == c_char + @property + def raw(self) -> bytes: ... + @raw.setter + def raw(self, value: ReadableBuffer) -> None: ... value: Any # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise # TODO: These methods cannot be annotated correctly at the moment. # All of these "Any"s stand for the array's element type, but it's not possible to use _CT diff --git a/mypy/typeshed/stdlib/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi index e1ef5c4bf0678..e7d85f8115310 100644 --- a/mypy/typeshed/stdlib/_operator.pyi +++ b/mypy/typeshed/stdlib/_operator.pyi @@ -1,5 +1,15 @@ import sys -from _typeshed import SupportsGetItem +from _typeshed import ( + SupportsAdd, + SupportsGetItem, + SupportsMod, + SupportsMul, + SupportsRAdd, + SupportsRMod, + SupportsRMul, + SupportsRSub, + SupportsSub, +) from collections.abc import Callable, Container, Iterable, MutableMapping, MutableSequence, Sequence from operator import attrgetter as attrgetter, itemgetter as itemgetter, methodcaller as methodcaller from typing import Any, AnyStr, Protocol, SupportsAbs, SupportsIndex, TypeVar, overload, type_check_only @@ -8,6 +18,7 @@ from typing_extensions import ParamSpec, TypeAlias, TypeIs _R = TypeVar("_R") _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) +_T_contra = TypeVar("_T_contra", contravariant=True) _K = TypeVar("_K") _V = TypeVar("_V") _P = ParamSpec("_P") @@ -58,24 +69,36 @@ def truth(a: object, /) -> bool: ... def is_(a: object, b: object, /) -> bool: ... def is_not(a: object, b: object, /) -> bool: ... def abs(a: SupportsAbs[_T], /) -> _T: ... -def add(a: Any, b: Any, /) -> Any: ... -def and_(a: Any, b: Any, /) -> Any: ... -def floordiv(a: Any, b: Any, /) -> Any: ... +@overload +def add(a: SupportsAdd[_T_contra, _T_co], b: _T_contra, /) -> _T_co: ... +@overload +def add(a: _T_contra, b: SupportsRAdd[_T_contra, _T_co], /) -> _T_co: ... +def and_(a, b, /): ... +def floordiv(a, b, /): ... def index(a: SupportsIndex, /) -> int: ... def inv(a: _SupportsInversion[_T_co], /) -> _T_co: ... def invert(a: _SupportsInversion[_T_co], /) -> _T_co: ... -def lshift(a: Any, b: Any, /) -> Any: ... -def mod(a: Any, b: Any, /) -> Any: ... -def mul(a: Any, b: Any, /) -> Any: ... -def matmul(a: Any, b: Any, /) -> Any: ... +def lshift(a, b, /): ... +@overload +def mod(a: SupportsMod[_T_contra, _T_co], b: _T_contra, /) -> _T_co: ... +@overload +def mod(a: _T_contra, b: SupportsRMod[_T_contra, _T_co], /) -> _T_co: ... +@overload +def mul(a: SupportsMul[_T_contra, _T_co], b: _T_contra, /) -> _T_co: ... +@overload +def mul(a: _T_contra, b: SupportsRMul[_T_contra, _T_co], /) -> _T_co: ... +def matmul(a, b, /): ... def neg(a: _SupportsNeg[_T_co], /) -> _T_co: ... -def or_(a: Any, b: Any, /) -> Any: ... +def or_(a, b, /): ... def pos(a: _SupportsPos[_T_co], /) -> _T_co: ... -def pow(a: Any, b: Any, /) -> Any: ... -def rshift(a: Any, b: Any, /) -> Any: ... -def sub(a: Any, b: Any, /) -> Any: ... -def truediv(a: Any, b: Any, /) -> Any: ... -def xor(a: Any, b: Any, /) -> Any: ... +def pow(a, b, /): ... +def rshift(a, b, /): ... +@overload +def sub(a: SupportsSub[_T_contra, _T_co], b: _T_contra, /) -> _T_co: ... +@overload +def sub(a: _T_contra, b: SupportsRSub[_T_contra, _T_co], /) -> _T_co: ... +def truediv(a, b, /): ... +def xor(a, b, /): ... def concat(a: Sequence[_T], b: Sequence[_T], /) -> Sequence[_T]: ... def contains(a: Container[object], b: object, /) -> bool: ... def countOf(a: Iterable[object], b: object, /) -> int: ... @@ -97,20 +120,20 @@ def setitem(a: MutableSequence[_T], b: slice[int | None], c: Sequence[_T], /) -> @overload def setitem(a: MutableMapping[_K, _V], b: _K, c: _V, /) -> None: ... def length_hint(obj: object, default: int = 0, /) -> int: ... -def iadd(a: Any, b: Any, /) -> Any: ... -def iand(a: Any, b: Any, /) -> Any: ... -def iconcat(a: Any, b: Any, /) -> Any: ... -def ifloordiv(a: Any, b: Any, /) -> Any: ... -def ilshift(a: Any, b: Any, /) -> Any: ... -def imod(a: Any, b: Any, /) -> Any: ... -def imul(a: Any, b: Any, /) -> Any: ... -def imatmul(a: Any, b: Any, /) -> Any: ... -def ior(a: Any, b: Any, /) -> Any: ... -def ipow(a: Any, b: Any, /) -> Any: ... -def irshift(a: Any, b: Any, /) -> Any: ... -def isub(a: Any, b: Any, /) -> Any: ... -def itruediv(a: Any, b: Any, /) -> Any: ... -def ixor(a: Any, b: Any, /) -> Any: ... +def iadd(a, b, /): ... +def iand(a, b, /): ... +def iconcat(a, b, /): ... +def ifloordiv(a, b, /): ... +def ilshift(a, b, /): ... +def imod(a, b, /): ... +def imul(a, b, /): ... +def imatmul(a, b, /): ... +def ior(a, b, /): ... +def ipow(a, b, /): ... +def irshift(a, b, /): ... +def isub(a, b, /): ... +def itruediv(a, b, /): ... +def ixor(a, b, /): ... if sys.version_info >= (3, 11): def call(obj: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ... diff --git a/mypy/typeshed/stdlib/_socket.pyi b/mypy/typeshed/stdlib/_socket.pyi index 372b35f22f175..918bffc7f9085 100644 --- a/mypy/typeshed/stdlib/_socket.pyi +++ b/mypy/typeshed/stdlib/_socket.pyi @@ -741,7 +741,7 @@ class socket: def proto(self) -> int: ... # F811: "Redefinition of unused `timeout`" @property - def timeout(self) -> float | None: ... # noqa: F811 + def timeout(self) -> float | None: ... if sys.platform == "win32": def __init__( self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | bytes | None = None @@ -838,7 +838,7 @@ def inet_ntop(address_family: int, packed_ip: ReadableBuffer, /) -> str: ... def getdefaulttimeout() -> float | None: ... # F811: "Redefinition of unused `timeout`" -def setdefaulttimeout(timeout: float | None, /) -> None: ... # noqa: F811 +def setdefaulttimeout(timeout: float | None, /) -> None: ... if sys.platform != "win32": def sethostname(name: str, /) -> None: ... diff --git a/mypy/typeshed/stdlib/_sqlite3.pyi b/mypy/typeshed/stdlib/_sqlite3.pyi index 437a9c9766829..5361584d6b184 100644 --- a/mypy/typeshed/stdlib/_sqlite3.pyi +++ b/mypy/typeshed/stdlib/_sqlite3.pyi @@ -171,7 +171,7 @@ if sys.version_info >= (3, 11): SQLITE_IOERR_VNODE: Final = 6922 SQLITE_IOERR_WRITE: Final = 778 SQLITE_LIMIT_ATTACHED: Final = 7 - SQLITE_LIMIT_COLUMN: Final = 22 + SQLITE_LIMIT_COLUMN: Final = 2 SQLITE_LIMIT_COMPOUND_SELECT: Final = 4 SQLITE_LIMIT_EXPR_DEPTH: Final = 3 SQLITE_LIMIT_FUNCTION_ARG: Final = 6 diff --git a/mypy/typeshed/stdlib/_ssl.pyi b/mypy/typeshed/stdlib/_ssl.pyi index d8cb9d49e7820..e84b24e8f4db7 100644 --- a/mypy/typeshed/stdlib/_ssl.pyi +++ b/mypy/typeshed/stdlib/_ssl.pyi @@ -183,8 +183,8 @@ CERT_REQUIRED: Final = 2 # verify flags VERIFY_DEFAULT: Final = 0 -VERIFY_CRL_CHECK_LEAF: Final = 0x4 -VERIFY_CRL_CHECK_CHAIN: Final = 0x8 +VERIFY_CRL_CHECK_LEAF: Final = 0x04 +VERIFY_CRL_CHECK_CHAIN: Final = 0x0C VERIFY_X509_STRICT: Final = 0x20 VERIFY_X509_TRUSTED_FIRST: Final = 0x8000 if sys.version_info >= (3, 10): @@ -230,7 +230,7 @@ PROTOCOL_TLSv1_1: Final = 4 PROTOCOL_TLSv1_2: Final = 5 # protocol options -OP_ALL: Final = 0x80000050 +OP_ALL: Final[int] OP_NO_SSLv2: Final = 0x0 OP_NO_SSLv3: Final = 0x2000000 OP_NO_TLSv1: Final = 0x4000000 diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index 89e93ab027069..c006322b81451 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -126,6 +126,12 @@ class SupportsMul(Protocol[_T_contra, _T_co]): class SupportsRMul(Protocol[_T_contra, _T_co]): def __rmul__(self, x: _T_contra, /) -> _T_co: ... +class SupportsMod(Protocol[_T_contra, _T_co]): + def __mod__(self, other: _T_contra, /) -> _T_co: ... + +class SupportsRMod(Protocol[_T_contra, _T_co]): + def __rmod__(self, other: _T_contra, /) -> _T_co: ... + class SupportsDivMod(Protocol[_T_contra, _T_co]): def __divmod__(self, other: _T_contra, /) -> _T_co: ... diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index c2a6f36911968..e1ad7cbc4570d 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import SupportsWrite, sentinel from collections.abc import Callable, Generator, Iterable, Sequence from re import Pattern -from typing import IO, Any, ClassVar, Final, Generic, NewType, NoReturn, Protocol, TypeVar, overload, type_check_only +from typing import IO, Any, ClassVar, Final, Generic, NoReturn, Protocol, TypeVar, overload, type_check_only from typing_extensions import Self, TypeAlias, deprecated __all__ = [ @@ -36,9 +36,7 @@ ONE_OR_MORE: Final = "+" OPTIONAL: Final = "?" PARSER: Final = "A..." REMAINDER: Final = "..." -_SUPPRESS_T = NewType("_SUPPRESS_T", str) -SUPPRESS: _SUPPRESS_T | str # not using Literal because argparse sometimes compares SUPPRESS with is -# the | str is there so that foo = argparse.SUPPRESS; foo = "test" checks out in mypy +SUPPRESS: Final = "==SUPPRESS==" ZERO_OR_MORE: Final = "*" _UNRECOGNIZED_ARGS_ATTR: Final = "_unrecognized_args" # undocumented @@ -81,11 +79,11 @@ class _ActionsContainer: # more precisely, Literal["?", "*", "+", "...", "A...", "==SUPPRESS=="], # but using this would make it hard to annotate callers that don't use a # literal argument and for subclasses to override this method. - nargs: int | str | _SUPPRESS_T | None = None, + nargs: int | str | None = None, const: Any = ..., default: Any = ..., type: _ActionType = ..., - choices: Iterable[_T] | None = ..., + choices: Iterable[Any] | None = ..., # choices must match the type specified required: bool = ..., help: str | None = ..., metavar: str | tuple[str, ...] | None = ..., @@ -170,7 +168,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): usage: str | None = None, description: str | None = None, epilog: str | None = None, - parents: Sequence[ArgumentParser] = [], + parents: Iterable[ArgumentParser] = [], formatter_class: _FormatterClass = ..., prefix_chars: str = "-", fromfile_prefix_chars: str | None = None, @@ -190,7 +188,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): usage: str | None = None, description: str | None = None, epilog: str | None = None, - parents: Sequence[ArgumentParser] = [], + parents: Iterable[ArgumentParser] = [], formatter_class: _FormatterClass = ..., prefix_chars: str = "-", fromfile_prefix_chars: str | None = None, @@ -202,9 +200,9 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): ) -> None: ... @overload - def parse_args(self, args: Sequence[str] | None = None, namespace: None = None) -> Namespace: ... + def parse_args(self, args: Iterable[str] | None = None, namespace: None = None) -> Namespace: ... @overload - def parse_args(self, args: Sequence[str] | None, namespace: _N) -> _N: ... + def parse_args(self, args: Iterable[str] | None, namespace: _N) -> _N: ... @overload def parse_args(self, *, namespace: _N) -> _N: ... @overload @@ -241,26 +239,26 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): def format_usage(self) -> str: ... def format_help(self) -> str: ... @overload - def parse_known_args(self, args: Sequence[str] | None = None, namespace: None = None) -> tuple[Namespace, list[str]]: ... + def parse_known_args(self, args: Iterable[str] | None = None, namespace: None = None) -> tuple[Namespace, list[str]]: ... @overload - def parse_known_args(self, args: Sequence[str] | None, namespace: _N) -> tuple[_N, list[str]]: ... + def parse_known_args(self, args: Iterable[str] | None, namespace: _N) -> tuple[_N, list[str]]: ... @overload def parse_known_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ... def convert_arg_line_to_args(self, arg_line: str) -> list[str]: ... def exit(self, status: int = 0, message: str | None = None) -> NoReturn: ... def error(self, message: str) -> NoReturn: ... @overload - def parse_intermixed_args(self, args: Sequence[str] | None = None, namespace: None = None) -> Namespace: ... + def parse_intermixed_args(self, args: Iterable[str] | None = None, namespace: None = None) -> Namespace: ... @overload - def parse_intermixed_args(self, args: Sequence[str] | None, namespace: _N) -> _N: ... + def parse_intermixed_args(self, args: Iterable[str] | None, namespace: _N) -> _N: ... @overload def parse_intermixed_args(self, *, namespace: _N) -> _N: ... @overload def parse_known_intermixed_args( - self, args: Sequence[str] | None = None, namespace: None = None + self, args: Iterable[str] | None = None, namespace: None = None ) -> tuple[Namespace, list[str]]: ... @overload - def parse_known_intermixed_args(self, args: Sequence[str] | None, namespace: _N) -> tuple[_N, list[str]]: ... + def parse_known_intermixed_args(self, args: Iterable[str] | None, namespace: _N) -> tuple[_N, list[str]]: ... @overload def parse_known_intermixed_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ... # undocumented @@ -346,7 +344,7 @@ class HelpFormatter: def _metavar_formatter(self, action: Action, default_metavar: str) -> Callable[[int], tuple[str, ...]]: ... def _format_args(self, action: Action, default_metavar: str) -> str: ... def _expand_help(self, action: Action) -> str: ... - def _iter_indented_subactions(self, action: Action) -> Generator[Action, None, None]: ... + def _iter_indented_subactions(self, action: Action) -> Generator[Action]: ... def _split_lines(self, text: str, width: int) -> list[str]: ... def _fill_text(self, text: str, width: int, indent: str) -> str: ... def _get_help_string(self, action: Action) -> str | None: ... @@ -785,13 +783,13 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]): *, deprecated: bool = False, help: str | None = ..., - aliases: Sequence[str] = ..., + aliases: Iterable[str] = ..., # Kwargs from ArgumentParser constructor prog: str | None = ..., usage: str | None = ..., description: str | None = ..., epilog: str | None = ..., - parents: Sequence[_ArgumentParserT] = ..., + parents: Iterable[_ArgumentParserT] = ..., formatter_class: _FormatterClass = ..., prefix_chars: str = ..., fromfile_prefix_chars: str | None = ..., @@ -811,13 +809,13 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]): *, deprecated: bool = False, help: str | None = ..., - aliases: Sequence[str] = ..., + aliases: Iterable[str] = ..., # Kwargs from ArgumentParser constructor prog: str | None = ..., usage: str | None = ..., description: str | None = ..., epilog: str | None = ..., - parents: Sequence[_ArgumentParserT] = ..., + parents: Iterable[_ArgumentParserT] = ..., formatter_class: _FormatterClass = ..., prefix_chars: str = ..., fromfile_prefix_chars: str | None = ..., @@ -834,13 +832,13 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]): name: str, *, help: str | None = ..., - aliases: Sequence[str] = ..., + aliases: Iterable[str] = ..., # Kwargs from ArgumentParser constructor prog: str | None = ..., usage: str | None = ..., description: str | None = ..., epilog: str | None = ..., - parents: Sequence[_ArgumentParserT] = ..., + parents: Iterable[_ArgumentParserT] = ..., formatter_class: _FormatterClass = ..., prefix_chars: str = ..., fromfile_prefix_chars: str | None = ..., diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 25b21ba971540..5657ac74a9acf 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -64,6 +64,7 @@ from typing import ( # noqa: Y022,UP035,RUF100 from typing_extensions import ( # noqa: Y023 Concatenate, Literal, + LiteralString, ParamSpec, Self, TypeAlias, @@ -481,16 +482,31 @@ class str(Sequence[str]): def __new__(cls, object: object = "") -> Self: ... @overload def __new__(cls, object: ReadableBuffer, encoding: str = "utf-8", errors: str = "strict") -> Self: ... + @overload + def capitalize(self: LiteralString) -> LiteralString: ... + @overload def capitalize(self) -> str: ... # type: ignore[misc] + @overload + def casefold(self: LiteralString) -> LiteralString: ... + @overload def casefold(self) -> str: ... # type: ignore[misc] + @overload + def center(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... + @overload def center(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] def count(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... def endswith( self, suffix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> bool: ... + @overload + def expandtabs(self: LiteralString, tabsize: SupportsIndex = 8) -> LiteralString: ... + @overload def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ... # type: ignore[misc] def find(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... + @overload + def format(self: LiteralString, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... + @overload def format(self, *args: object, **kwargs: object) -> str: ... def format_map(self, mapping: _FormatMapMapping, /) -> str: ... def index(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... @@ -506,34 +522,98 @@ class str(Sequence[str]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... + @overload + def join(self: LiteralString, iterable: Iterable[LiteralString], /) -> LiteralString: ... + @overload def join(self, iterable: Iterable[str], /) -> str: ... # type: ignore[misc] + @overload + def ljust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... + @overload def ljust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] + @overload + def lower(self: LiteralString) -> LiteralString: ... + @overload def lower(self) -> str: ... # type: ignore[misc] + @overload + def lstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... + @overload def lstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] + @overload + def partition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ... + @overload def partition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] if sys.version_info >= (3, 13): + @overload + def replace( + self: LiteralString, old: LiteralString, new: LiteralString, /, count: SupportsIndex = -1 + ) -> LiteralString: ... + @overload def replace(self, old: str, new: str, /, count: SupportsIndex = -1) -> str: ... # type: ignore[misc] else: + @overload + def replace( + self: LiteralString, old: LiteralString, new: LiteralString, count: SupportsIndex = -1, / + ) -> LiteralString: ... + @overload def replace(self, old: str, new: str, count: SupportsIndex = -1, /) -> str: ... # type: ignore[misc] + @overload + def removeprefix(self: LiteralString, prefix: LiteralString, /) -> LiteralString: ... + @overload def removeprefix(self, prefix: str, /) -> str: ... # type: ignore[misc] + @overload + def removesuffix(self: LiteralString, suffix: LiteralString, /) -> LiteralString: ... + @overload def removesuffix(self, suffix: str, /) -> str: ... # type: ignore[misc] def rfind(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... def rindex(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... + @overload + def rjust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... + @overload def rjust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] + @overload + def rpartition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ... + @overload def rpartition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] + @overload + def rsplit(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... + @overload def rsplit(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] + @overload + def rstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... + @overload def rstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] + @overload + def split(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... + @overload def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] + @overload + def splitlines(self: LiteralString, keepends: bool = False) -> list[LiteralString]: ... + @overload def splitlines(self, keepends: bool = False) -> list[str]: ... # type: ignore[misc] def startswith( self, prefix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> bool: ... + @overload + def strip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... + @overload def strip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] + @overload + def swapcase(self: LiteralString) -> LiteralString: ... + @overload def swapcase(self) -> str: ... # type: ignore[misc] + @overload + def title(self: LiteralString) -> LiteralString: ... + @overload def title(self) -> str: ... # type: ignore[misc] def translate(self, table: _TranslateTable, /) -> str: ... + @overload + def upper(self: LiteralString) -> LiteralString: ... + @overload def upper(self) -> str: ... # type: ignore[misc] + @overload + def zfill(self: LiteralString, width: SupportsIndex, /) -> LiteralString: ... + @overload def zfill(self, width: SupportsIndex, /) -> str: ... # type: ignore[misc] @staticmethod @overload @@ -544,21 +624,39 @@ class str(Sequence[str]): @staticmethod @overload def maketrans(x: str, y: str, z: str, /) -> dict[int, int | None]: ... + @overload + def __add__(self: LiteralString, value: LiteralString, /) -> LiteralString: ... + @overload def __add__(self, value: str, /) -> str: ... # type: ignore[misc] # Incompatible with Sequence.__contains__ def __contains__(self, key: str, /) -> bool: ... # type: ignore[override] def __eq__(self, value: object, /) -> bool: ... def __ge__(self, value: str, /) -> bool: ... + @overload + def __getitem__(self: LiteralString, key: SupportsIndex | slice[SupportsIndex | None], /) -> LiteralString: ... + @overload def __getitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> str: ... # type: ignore[misc] def __gt__(self, value: str, /) -> bool: ... def __hash__(self) -> int: ... + @overload + def __iter__(self: LiteralString) -> Iterator[LiteralString]: ... + @overload def __iter__(self) -> Iterator[str]: ... # type: ignore[misc] def __le__(self, value: str, /) -> bool: ... def __len__(self) -> int: ... def __lt__(self, value: str, /) -> bool: ... + @overload + def __mod__(self: LiteralString, value: LiteralString | tuple[LiteralString, ...], /) -> LiteralString: ... + @overload def __mod__(self, value: Any, /) -> str: ... + @overload + def __mul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... + @overload def __mul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] def __ne__(self, value: object, /) -> bool: ... + @overload + def __rmul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... + @overload def __rmul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] def __getnewargs__(self) -> tuple[str]: ... def __format__(self, format_spec: str, /) -> str: ... @@ -1142,13 +1240,7 @@ class dict(MutableMapping[_KT, _VT]): def __reversed__(self) -> Iterator[_KT]: ... __hash__: ClassVar[None] # type: ignore[assignment] def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... - @overload - def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... - @overload def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... - @overload - def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... - @overload def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... # dict.__ior__ should be kept roughly in line with MutableMapping.update() @overload # type: ignore[misc] @@ -1226,7 +1318,7 @@ class frozenset(AbstractSet[_T_co]): def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @disjoint_base -class enumerate(Iterator[tuple[int, _T]]): +class enumerate(Generic[_T]): def __new__(cls, iterable: Iterable[_T], start: int = 0) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> tuple[int, _T]: ... @@ -1413,7 +1505,7 @@ else: exit: _sitebuiltins.Quitter @disjoint_base -class filter(Iterator[_T]): +class filter(Generic[_T]): @overload def __new__(cls, function: None, iterable: Iterable[_T | None], /) -> Self: ... @overload @@ -1477,7 +1569,7 @@ license: _sitebuiltins._Printer def locals() -> dict[str, Any]: ... @disjoint_base -class map(Iterator[_S]): +class map(Generic[_S]): # 3.14 adds `strict` argument. if sys.version_info >= (3, 14): @overload @@ -1784,7 +1876,7 @@ def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex quit: _sitebuiltins.Quitter @disjoint_base -class reversed(Iterator[_T]): +class reversed(Generic[_T]): @overload def __new__(cls, sequence: Reversible[_T], /) -> Iterator[_T]: ... # type: ignore[misc] @overload @@ -1835,7 +1927,7 @@ _SupportsSumNoDefaultT = TypeVar("_SupportsSumNoDefaultT", bound=_SupportsSumWit # without creating many false-positive errors (see #7578). # Instead, we special-case the most common examples of this: bool and literal integers. @overload -def sum(iterable: Iterable[bool], /, start: int = 0) -> int: ... +def sum(iterable: Iterable[bool | _LiteralInteger], /, start: int = 0) -> int: ... @overload def sum(iterable: Iterable[_SupportsSumNoDefaultT], /) -> _SupportsSumNoDefaultT | Literal[0]: ... @overload @@ -1848,7 +1940,7 @@ def vars(object: type, /) -> types.MappingProxyType[str, Any]: ... @overload def vars(object: Any = ..., /) -> dict[str, Any]: ... @disjoint_base -class zip(Iterator[_T_co]): +class zip(Generic[_T_co]): if sys.version_info >= (3, 10): @overload def __new__(cls, *, strict: bool = False) -> zip[Any]: ... diff --git a/mypy/typeshed/stdlib/codecs.pyi b/mypy/typeshed/stdlib/codecs.pyi index 4dfe3fd9e8510..9164a4a626d4f 100644 --- a/mypy/typeshed/stdlib/codecs.pyi +++ b/mypy/typeshed/stdlib/codecs.pyi @@ -196,8 +196,8 @@ def open( filename: str, mode: str = "r", encoding: str | None = None, errors: str = "strict", buffering: int = -1 ) -> StreamReaderWriter: ... def EncodedFile(file: _Stream, data_encoding: str, file_encoding: str | None = None, errors: str = "strict") -> StreamRecoder: ... -def iterencode(iterator: Iterable[str], encoding: str, errors: str = "strict") -> Generator[bytes, None, None]: ... -def iterdecode(iterator: Iterable[bytes], encoding: str, errors: str = "strict") -> Generator[str, None, None]: ... +def iterencode(iterator: Iterable[str], encoding: str, errors: str = "strict") -> Generator[bytes]: ... +def iterdecode(iterator: Iterable[bytes], encoding: str, errors: str = "strict") -> Generator[str]: ... BOM: Final[Literal[b"\xff\xfe", b"\xfe\xff"]] # depends on `sys.byteorder` BOM_BE: Final = b"\xfe\xff" diff --git a/mypy/typeshed/stdlib/concurrent/futures/process.pyi b/mypy/typeshed/stdlib/concurrent/futures/process.pyi index 071b3aba5d330..282bafa0b611c 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/process.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/process.pyi @@ -97,7 +97,7 @@ class _SafeQueue(Queue[Future[Any]]): def _on_queue_feeder_error(self, e: Exception, obj: _CallItem) -> None: ... -def _get_chunks(*iterables: Any, chunksize: int) -> Generator[tuple[Any, ...], None, None]: ... +def _get_chunks(*iterables: Any, chunksize: int) -> Generator[tuple[Any, ...]]: ... def _process_chunk(fn: Callable[..., _T], chunk: Iterable[tuple[Any, ...]]) -> list[_T]: ... if sys.version_info >= (3, 11): diff --git a/mypy/typeshed/stdlib/concurrent/interpreters/__init__.pyi b/mypy/typeshed/stdlib/concurrent/interpreters/__init__.pyi index 3839e6bef09b6..171fadb2202be 100644 --- a/mypy/typeshed/stdlib/concurrent/interpreters/__init__.pyi +++ b/mypy/typeshed/stdlib/concurrent/interpreters/__init__.pyi @@ -5,7 +5,7 @@ from collections.abc import Callable from typing import Any, Literal, TypeVar from typing_extensions import ParamSpec, Self -if sys.version_info >= (3, 13): # needed to satisfy pyright checks for Python <3.13 +if sys.version_info >= (3, 14): # needed to satisfy pyright checks for Python <= 3.13 from _interpreters import ( InterpreterError as InterpreterError, InterpreterNotFoundError as InterpreterNotFoundError, diff --git a/mypy/typeshed/stdlib/concurrent/interpreters/_crossinterp.pyi b/mypy/typeshed/stdlib/concurrent/interpreters/_crossinterp.pyi index 7cf1ea34786ed..50fe7cf0b4ba4 100644 --- a/mypy/typeshed/stdlib/concurrent/interpreters/_crossinterp.pyi +++ b/mypy/typeshed/stdlib/concurrent/interpreters/_crossinterp.pyi @@ -3,7 +3,7 @@ from collections.abc import Callable from typing import Final, NewType from typing_extensions import Never, Self, TypeAlias -if sys.version_info >= (3, 13): # needed to satisfy pyright checks for Python <3.13 +if sys.version_info >= (3, 14): # needed to satisfy pyright checks for Python <= 3.13 from _interpqueues import _UnboundOp class ItemInterpreterDestroyed(Exception): ... diff --git a/mypy/typeshed/stdlib/concurrent/interpreters/_queues.pyi b/mypy/typeshed/stdlib/concurrent/interpreters/_queues.pyi index bdf08d93d1e00..b4a4fd56dd45d 100644 --- a/mypy/typeshed/stdlib/concurrent/interpreters/_queues.pyi +++ b/mypy/typeshed/stdlib/concurrent/interpreters/_queues.pyi @@ -3,7 +3,7 @@ import sys from typing import Final, SupportsIndex from typing_extensions import Self -if sys.version_info >= (3, 13): # needed to satisfy pyright checks for Python <3.13 +if sys.version_info >= (3, 14): # needed to satisfy pyright checks for Python <= 3.13 from _interpqueues import QueueError as QueueError, QueueNotFoundError as QueueNotFoundError from . import _crossinterp diff --git a/mypy/typeshed/stdlib/configparser.pyi b/mypy/typeshed/stdlib/configparser.pyi index 1e11088c3ae7a..9b3f02324b7fd 100644 --- a/mypy/typeshed/stdlib/configparser.pyi +++ b/mypy/typeshed/stdlib/configparser.pyi @@ -289,19 +289,19 @@ class RawConfigParser(_Parser): def getint(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> int: ... @overload def getint( - self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T = ... + self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T ) -> int | _T: ... @overload def getfloat(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> float: ... @overload def getfloat( - self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T = ... + self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T ) -> float | _T: ... @overload def getboolean(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> bool: ... @overload def getboolean( - self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T = ... + self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T ) -> bool | _T: ... def _get_conv( self, diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index cf831e5dcae81..dff34474d2f5b 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -5,7 +5,7 @@ from abc import ABC, abstractmethod from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Generator, Iterator from types import TracebackType from typing import Any, Generic, Protocol, TypeVar, overload, runtime_checkable, type_check_only -from typing_extensions import ParamSpec, Self, TypeAlias +from typing_extensions import ParamSpec, Self, TypeAlias, deprecated __all__ = [ "contextmanager", @@ -86,6 +86,12 @@ class _GeneratorContextManager( self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> bool | None: ... +@overload +def contextmanager(func: Callable[_P, Generator[_T_co, None, object]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ... +@overload +@deprecated( + "Annotating the return type as `-> Iterator[Foo]` with `@contextmanager` is deprecated. Use `-> Generator[Foo]` instead." +) def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ... if sys.version_info >= (3, 10): @@ -112,6 +118,13 @@ else: self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> bool | None: ... +@overload +def asynccontextmanager(func: Callable[_P, AsyncGenerator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ... +@overload +@deprecated( + "Annotating the return type as `-> AsyncIterator[Foo]` with `@asynccontextmanager` is deprecated. " + "Use `-> AsyncGenerator[Foo]` instead." +) def asynccontextmanager(func: Callable[_P, AsyncIterator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ... @type_check_only class _SupportsClose(Protocol): @@ -165,9 +178,15 @@ class _BaseExitStack(Generic[_ExitT_co]): def callback(self, callback: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> Callable[_P, _T]: ... def pop_all(self) -> Self: ... -# In reality this is a subclass of `AbstractContextManager`; -# see #7961 for why we don't do that in the stub -class ExitStack(_BaseExitStack[_ExitT_co], metaclass=abc.ABCMeta): +# this class is to avoid putting `metaclass=abc.ABCMeta` on the implementations directly, as this would make them +# appear explicitly abstract to some tools. this is due to the implementations not subclassing `AbstractContextManager` +# see note on the subclasses +@type_check_only +class _BaseExitStackAbstract(_BaseExitStack[_ExitT_co], metaclass=abc.ABCMeta): ... + +# In reality this is a subclass of `AbstractContextManager`, but we can't provide `Self` as the argument for `__enter__` +# https://discuss.python.org/t/self-as-typevar-default/90939 +class ExitStack(_BaseExitStackAbstract[_ExitT_co]): def close(self) -> None: ... def __enter__(self) -> Self: ... def __exit__( @@ -179,9 +198,9 @@ _ExitCoroFunc: TypeAlias = Callable[ ] _ACM_EF = TypeVar("_ACM_EF", bound=AbstractAsyncContextManager[Any, Any] | _ExitCoroFunc) -# In reality this is a subclass of `AbstractAsyncContextManager`; -# see #7961 for why we don't do that in the stub -class AsyncExitStack(_BaseExitStack[_ExitT_co], metaclass=abc.ABCMeta): +# In reality this is a subclass of `AbstractContextManager`, but we can't provide `Self` as the argument for `__enter__` +# https://discuss.python.org/t/self-as-typevar-default/90939 +class AsyncExitStack(_BaseExitStackAbstract[_ExitT_co]): async def enter_async_context(self, cm: AbstractAsyncContextManager[_T, _ExitT_co]) -> _T: ... def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: ... def push_async_callback( diff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi index 4ed0ab1d83b82..2c8e7109cdfc3 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi @@ -25,7 +25,7 @@ else: from _csv import _reader as Reader, _writer as Writer from _typeshed import SupportsWrite -from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence +from collections.abc import Collection, Iterable, Mapping, Sequence from types import GenericAlias from typing import Any, Generic, Literal, TypeVar, overload from typing_extensions import Self @@ -73,7 +73,7 @@ class excel(Dialect): ... class excel_tab(excel): ... class unix_dialect(Dialect): ... -class DictReader(Iterator[dict[_T | Any, str | Any]], Generic[_T]): +class DictReader(Generic[_T]): fieldnames: Sequence[_T] | None restkey: _T | None restval: str | Any | None diff --git a/mypy/typeshed/stdlib/email/message.pyi b/mypy/typeshed/stdlib/email/message.pyi index 794882b140e61..c586c23b9e926 100644 --- a/mypy/typeshed/stdlib/email/message.pyi +++ b/mypy/typeshed/stdlib/email/message.pyi @@ -130,7 +130,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): def get_charsets(self, failobj: None = None) -> list[str | None]: ... @overload def get_charsets(self, failobj: _T) -> list[str | _T]: ... - def walk(self) -> Generator[Self, None, None]: ... + def walk(self) -> Generator[Self]: ... def get_content_disposition(self) -> str | None: ... def as_string(self, unixfrom: bool = False, maxheaderlen: int = 0, policy: Policy[Any] | None = None) -> str: ... def as_bytes(self, unixfrom: bool = False, policy: Policy[Any] | None = None) -> bytes: ... diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index 95164de2f0107..6778b764810bd 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -1,8 +1,8 @@ import sys from _typeshed import AnyStr_co, StrOrBytesPath -from collections.abc import Callable, Iterable, Iterator +from collections.abc import Callable, Iterable from types import GenericAlias, TracebackType -from typing import IO, Any, AnyStr, Literal, Protocol, overload, type_check_only +from typing import IO, Any, AnyStr, Generic, Literal, Protocol, overload, type_check_only from typing_extensions import Self, TypeAlias, deprecated __all__ = [ @@ -105,7 +105,7 @@ def fileno() -> int: ... def isfirstline() -> bool: ... def isstdin() -> bool: ... -class FileInput(Iterator[AnyStr]): +class FileInput(Generic[AnyStr]): if sys.version_info >= (3, 10): # encoding and errors are added @overload diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index 4713d62cc346f..8a924ad8b1e71 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -28,7 +28,7 @@ _Predicate: TypeAlias = Callable[[_T], object] # Technically count can take anything that implements a number protocol and has an add method # but we can't enforce the add method @disjoint_base -class count(Iterator[_N]): +class count(Generic[_N]): @overload def __new__(cls) -> count[int]: ... @overload @@ -39,13 +39,13 @@ class count(Iterator[_N]): def __iter__(self) -> Self: ... @disjoint_base -class cycle(Iterator[_T]): +class cycle(Generic[_T]): def __new__(cls, iterable: Iterable[_T], /) -> Self: ... def __next__(self) -> _T: ... def __iter__(self) -> Self: ... @disjoint_base -class repeat(Iterator[_T]): +class repeat(Generic[_T]): @overload def __new__(cls, object: _T) -> Self: ... @overload @@ -55,7 +55,7 @@ class repeat(Iterator[_T]): def __length_hint__(self) -> int: ... @disjoint_base -class accumulate(Iterator[_T]): +class accumulate(Generic[_T]): @overload def __new__(cls, iterable: Iterable[_T], func: None = None, *, initial: _T | None = None) -> Self: ... @overload @@ -64,7 +64,7 @@ class accumulate(Iterator[_T]): def __next__(self) -> _T: ... @disjoint_base -class chain(Iterator[_T]): +class chain(Generic[_T]): def __new__(cls, *iterables: Iterable[_T]) -> Self: ... def __next__(self) -> _T: ... def __iter__(self) -> Self: ... @@ -74,25 +74,25 @@ class chain(Iterator[_T]): def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @disjoint_base -class compress(Iterator[_T]): +class compress(Generic[_T]): def __new__(cls, data: Iterable[_T], selectors: Iterable[Any]) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... @disjoint_base -class dropwhile(Iterator[_T]): +class dropwhile(Generic[_T]): def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... @disjoint_base -class filterfalse(Iterator[_T]): +class filterfalse(Generic[_T]): def __new__(cls, function: _Predicate[_T] | None, iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... @disjoint_base -class groupby(Iterator[tuple[_T_co, Iterator[_S_co]]], Generic[_T_co, _S_co]): +class groupby(Generic[_T_co, _S_co]): @overload def __new__(cls, iterable: Iterable[_T1], key: None = None) -> groupby[_T1, _T1]: ... @overload @@ -101,7 +101,7 @@ class groupby(Iterator[tuple[_T_co, Iterator[_S_co]]], Generic[_T_co, _S_co]): def __next__(self) -> tuple[_T_co, Iterator[_S_co]]: ... @disjoint_base -class islice(Iterator[_T]): +class islice(Generic[_T]): @overload def __new__(cls, iterable: Iterable[_T], stop: int | None, /) -> Self: ... @overload @@ -110,20 +110,20 @@ class islice(Iterator[_T]): def __next__(self) -> _T: ... @disjoint_base -class starmap(Iterator[_T_co]): +class starmap(Generic[_T_co]): def __new__(cls, function: Callable[..., _T], iterable: Iterable[Iterable[Any]], /) -> starmap[_T]: ... def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... @disjoint_base -class takewhile(Iterator[_T]): +class takewhile(Generic[_T]): def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... def tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]: ... @disjoint_base -class zip_longest(Iterator[_T_co]): +class zip_longest(Generic[_T_co]): # one iterable (fillvalue doesn't matter) @overload def __new__(cls, iter1: Iterable[_T1], /, *, fillvalue: object = None) -> zip_longest[tuple[_T1]]: ... @@ -202,7 +202,7 @@ class zip_longest(Iterator[_T_co]): def __next__(self) -> _T_co: ... @disjoint_base -class product(Iterator[_T_co]): +class product(Generic[_T_co]): @overload def __new__(cls, iter1: Iterable[_T1], /) -> product[tuple[_T1]]: ... @overload @@ -288,7 +288,7 @@ class product(Iterator[_T_co]): def __next__(self) -> _T_co: ... @disjoint_base -class permutations(Iterator[_T_co]): +class permutations(Generic[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> permutations[tuple[_T, _T]]: ... @overload @@ -303,7 +303,7 @@ class permutations(Iterator[_T_co]): def __next__(self) -> _T_co: ... @disjoint_base -class combinations(Iterator[_T_co]): +class combinations(Generic[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations[tuple[_T, _T]]: ... @overload @@ -318,7 +318,7 @@ class combinations(Iterator[_T_co]): def __next__(self) -> _T_co: ... @disjoint_base -class combinations_with_replacement(Iterator[_T_co]): +class combinations_with_replacement(Generic[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations_with_replacement[tuple[_T, _T]]: ... @overload @@ -334,14 +334,14 @@ class combinations_with_replacement(Iterator[_T_co]): if sys.version_info >= (3, 10): @disjoint_base - class pairwise(Iterator[_T_co]): + class pairwise(Generic[_T_co]): def __new__(cls, iterable: Iterable[_T], /) -> pairwise[tuple[_T, _T]]: ... def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... if sys.version_info >= (3, 12): @disjoint_base - class batched(Iterator[_T_co], Generic[_T_co]): + class batched(Generic[_T_co]): if sys.version_info >= (3, 13): @overload def __new__(cls, iterable: Iterable[_T], n: Literal[1], *, strict: Literal[True]) -> batched[tuple[_T]]: ... diff --git a/mypy/typeshed/stdlib/json/__init__.pyi b/mypy/typeshed/stdlib/json/__init__.pyi index 63e9718ee1512..454a235ecf703 100644 --- a/mypy/typeshed/stdlib/json/__init__.pyi +++ b/mypy/typeshed/stdlib/json/__init__.pyi @@ -1,6 +1,6 @@ from _typeshed import SupportsRead, SupportsWrite from collections.abc import Callable -from typing import Any +from typing import Any, Literal from .decoder import JSONDecodeError as JSONDecodeError, JSONDecoder as JSONDecoder from .encoder import JSONEncoder as JSONEncoder @@ -58,4 +58,6 @@ def load( object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, **kwds: Any, ) -> Any: ... -def detect_encoding(b: bytes | bytearray) -> str: ... # undocumented +def detect_encoding( + b: bytes | bytearray, +) -> Literal["utf-8", "utf-8-sig", "utf-16", "utf-16-be", "utf-16-le", "utf-32", "utf-32-be", "utf-32-le"]: ... # undocumented diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_except.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_except.pyi index 30930a2c381e9..0d856e6b0b7d2 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_except.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_except.pyi @@ -6,7 +6,7 @@ from ..pytree import Base _N = TypeVar("_N", bound=Base) -def find_excepts(nodes: Iterable[_N]) -> Generator[tuple[_N, _N], None, None]: ... +def find_excepts(nodes: Iterable[_N]) -> Generator[tuple[_N, _N]]: ... class FixExcept(fixer_base.BaseFix): BM_compatible: ClassVar[Literal[True]] diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_import.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_import.pyi index bf4b2d00925eb..2daa18327ec09 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_import.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_import.pyi @@ -5,7 +5,7 @@ from typing import ClassVar, Literal from .. import fixer_base from ..pytree import Node -def traverse_imports(names) -> Generator[str, None, None]: ... +def traverse_imports(names) -> Generator[str]: ... class FixImport(fixer_base.BaseFix): BM_compatible: ClassVar[Literal[True]] diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_imports.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_imports.pyi index c747af529f440..d86ebbe215a14 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_imports.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_imports.pyi @@ -8,7 +8,7 @@ from ..pytree import Node MAPPING: Final[dict[str, str]] def alternates(members): ... -def build_pattern(mapping=...) -> Generator[str, None, None]: ... +def build_pattern(mapping=...) -> Generator[str]: ... class FixImports(fixer_base.BaseFix): BM_compatible: ClassVar[Literal[True]] diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi index 1b1ec82032b4f..6ad25e9aac368 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi @@ -8,7 +8,7 @@ def has_metaclass(parent): ... def fixup_parse_tree(cls_node) -> None: ... def fixup_simple_stmt(parent, i, stmt_node) -> None: ... def remove_trailing_newline(node) -> None: ... -def find_metas(cls_node) -> Generator[tuple[Base, int, Base], None, None]: ... +def find_metas(cls_node) -> Generator[tuple[Base, int, Base]]: ... def fixup_indent(suite) -> None: ... class FixMetaclass(fixer_base.BaseFix): diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_renames.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_renames.pyi index 652d8f15ea1a9..f095b3083ba8b 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_renames.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_renames.pyi @@ -7,7 +7,7 @@ MAPPING: Final[dict[str, dict[str, str]]] LOOKUP: Final[dict[tuple[str, str], str]] def alternates(members): ... -def build_pattern() -> Generator[str, None, None]: ... +def build_pattern() -> Generator[str]: ... class FixRenames(fixer_base.BaseFix): BM_compatible: ClassVar[Literal[True]] diff --git a/mypy/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi b/mypy/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi index abdcc0f62970f..ab84114f90ea3 100644 --- a/mypy/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi +++ b/mypy/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi @@ -5,7 +5,7 @@ from .fix_imports import FixImports MAPPING: Final[dict[str, list[tuple[Literal["urllib.request", "urllib.parse", "urllib.error"], list[str]]]]] -def build_pattern() -> Generator[str, None, None]: ... +def build_pattern() -> Generator[str]: ... class FixUrllib(FixImports): def build_pattern(self): ... diff --git a/mypy/typeshed/stdlib/lib2to3/refactor.pyi b/mypy/typeshed/stdlib/lib2to3/refactor.pyi index a7f3825406488..c33347ede38fd 100644 --- a/mypy/typeshed/stdlib/lib2to3/refactor.pyi +++ b/mypy/typeshed/stdlib/lib2to3/refactor.pyi @@ -69,8 +69,8 @@ class RefactoringTool: def parse_block(self, block: Iterable[str], lineno: int, indent: int) -> Node: ... def wrap_toks( self, block: Iterable[str], lineno: int, indent: int - ) -> Generator[tuple[int, str, tuple[int, int], tuple[int, int], str], None, None]: ... - def gen_lines(self, block: Iterable[str], indent: int) -> Generator[str, None, None]: ... + ) -> Generator[tuple[int, str, tuple[int, int], tuple[int, int], str]]: ... + def gen_lines(self, block: Iterable[str], indent: int) -> Generator[str]: ... class MultiprocessingUnsupported(Exception): ... diff --git a/mypy/typeshed/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi index f276372d09039..b79f9e77359ae 100644 --- a/mypy/typeshed/stdlib/multiprocessing/pool.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/pool.pyi @@ -1,4 +1,4 @@ -from collections.abc import Callable, Iterable, Iterator, Mapping +from collections.abc import Callable, Iterable, Mapping from multiprocessing.context import DefaultContext, Process from types import GenericAlias, TracebackType from typing import Any, Final, Generic, TypeVar @@ -32,7 +32,7 @@ class MapResult(ApplyResult[list[_T]]): error_callback: Callable[[BaseException], object] | None, ) -> None: ... -class IMapIterator(Iterator[_T]): +class IMapIterator(Generic[_T]): def __init__(self, pool: Pool) -> None: ... def __iter__(self) -> Self: ... def next(self, timeout: float | None = None) -> _T: ... diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 9e02fbf9e1066..66a9d1dd3bc6d 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -614,9 +614,12 @@ if sys.platform == "darwin" and sys.version_info >= (3, 12): SEEK_SET: Final = 0 SEEK_CUR: Final = 1 SEEK_END: Final = 2 -if sys.platform != "win32": +if sys.platform == "linux": SEEK_DATA: Final = 3 SEEK_HOLE: Final = 4 +elif sys.platform == "darwin": + SEEK_HOLE: Final = 3 + SEEK_DATA: Final = 4 O_RDONLY: Final[int] O_WRONLY: Final[int] @@ -826,11 +829,9 @@ class stat_result(structseq[float], tuple[int, int, int, int, int, int, int, flo # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) if sys.version_info >= (3, 12) and sys.platform == "win32": @property - @deprecated( - """\ + @deprecated("""\ Use st_birthtime instead to retrieve the file creation time. \ -In the future, this property will contain the last metadata change time.""" - ) +In the future, this property will contain the last metadata change time.""") def st_ctime(self) -> float: ... else: @property @@ -1531,7 +1532,36 @@ else: def WSTOPSIG(status: int) -> int: ... def WTERMSIG(status: int) -> int: ... - if sys.version_info >= (3, 13): + if sys.version_info >= (3, 15): + def posix_spawn( + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv | None, + /, + *, + file_actions: Sequence[tuple[Any, ...]] | None = (), + setpgroup: int | None = None, # None allowed starting in 3.15 + resetids: bool = False, + setsid: bool = False, + setsigmask: Iterable[int] = (), + setsigdef: Iterable[int] = (), + scheduler: tuple[Any, sched_param] | None = None, # None allowed starting in 3.15 + ) -> int: ... + def posix_spawnp( + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv | None, + /, + *, + file_actions: Sequence[tuple[Any, ...]] | None = (), + setpgroup: int | None = None, # None allowed starting in 3.15 + resetids: bool = False, + setsid: bool = False, + setsigmask: Iterable[int] = (), + setsigdef: Iterable[int] = (), + scheduler: tuple[Any, sched_param] | None = None, # None allowed starting in 3.15 + ) -> int: ... + elif sys.version_info >= (3, 13): def posix_spawn( path: StrOrBytesPath, argv: _ExecVArgs, diff --git a/mypy/typeshed/stdlib/pathlib/__init__.pyi b/mypy/typeshed/stdlib/pathlib/__init__.pyi index 26dde2accd8dd..4f094130665c8 100644 --- a/mypy/typeshed/stdlib/pathlib/__init__.pyi +++ b/mypy/typeshed/stdlib/pathlib/__init__.pyi @@ -189,11 +189,11 @@ class Path(PurePath): self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False ) -> Iterator[Self]: ... elif sys.version_info >= (3, 12): - def glob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]: ... - def rglob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]: ... + def glob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self]: ... + def rglob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self]: ... else: - def glob(self, pattern: str) -> Generator[Self, None, None]: ... - def rglob(self, pattern: str) -> Generator[Self, None, None]: ... + def glob(self, pattern: str) -> Generator[Self]: ... + def rglob(self, pattern: str) -> Generator[Self]: ... if sys.version_info >= (3, 12): def exists(self, *, follow_symlinks: bool = True) -> bool: ... @@ -208,7 +208,7 @@ class Path(PurePath): if sys.version_info >= (3, 12): def is_junction(self) -> bool: ... - def iterdir(self) -> Generator[Self, None, None]: ... + def iterdir(self) -> Generator[Self]: ... def lchmod(self, mode: int) -> None: ... def lstat(self) -> stat_result: ... def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None: ... diff --git a/mypy/typeshed/stdlib/sqlite3/__init__.pyi b/mypy/typeshed/stdlib/sqlite3/__init__.pyi index f12f80a35a975..86ae7bccdb113 100644 --- a/mypy/typeshed/stdlib/sqlite3/__init__.pyi +++ b/mypy/typeshed/stdlib/sqlite3/__init__.pyi @@ -365,9 +365,9 @@ class Connection: def executescript(self, sql_script: str, /) -> Cursor: ... def interrupt(self) -> None: ... if sys.version_info >= (3, 13): - def iterdump(self, *, filter: str | None = None) -> Generator[str, None, None]: ... + def iterdump(self, *, filter: str | None = None) -> Generator[str]: ... else: - def iterdump(self) -> Generator[str, None, None]: ... + def iterdump(self) -> Generator[str]: ... def rollback(self) -> None: ... def set_authorizer( @@ -408,7 +408,7 @@ class Connection: ) -> Literal[False]: ... @disjoint_base -class Cursor(Iterator[Any]): +class Cursor: arraysize: int @property def connection(self) -> Connection: ... diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index 2053005f1ba69..57952cf19bbed 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -103,14 +103,14 @@ CERT_OPTIONAL: Final = VerifyMode.CERT_OPTIONAL CERT_REQUIRED: Final = VerifyMode.CERT_REQUIRED class VerifyFlags(enum.IntFlag): - VERIFY_DEFAULT = 0 - VERIFY_CRL_CHECK_LEAF = 4 - VERIFY_CRL_CHECK_CHAIN = 12 - VERIFY_X509_STRICT = 32 - VERIFY_X509_TRUSTED_FIRST = 32768 + VERIFY_DEFAULT = 0x00 + VERIFY_CRL_CHECK_LEAF = 0x04 + VERIFY_CRL_CHECK_CHAIN = 0x0C + VERIFY_X509_STRICT = 0x20 + VERIFY_X509_TRUSTED_FIRST = 0x8000 if sys.version_info >= (3, 10): - VERIFY_ALLOW_PROXY_CERTS = 64 - VERIFY_X509_PARTIAL_CHAIN = 524288 + VERIFY_ALLOW_PROXY_CERTS = 0x40 + VERIFY_X509_PARTIAL_CHAIN = 0x80000 VERIFY_DEFAULT: Final = VerifyFlags.VERIFY_DEFAULT VERIFY_CRL_CHECK_LEAF: Final = VerifyFlags.VERIFY_CRL_CHECK_LEAF @@ -144,7 +144,7 @@ PROTOCOL_TLS_CLIENT: Final = _SSLMethod.PROTOCOL_TLS_CLIENT PROTOCOL_TLS_SERVER: Final = _SSLMethod.PROTOCOL_TLS_SERVER class Options(enum.IntFlag): - OP_ALL = 2147483728 + OP_ALL: int OP_NO_SSLv2 = 0 OP_NO_SSLv3 = 33554432 OP_NO_TLSv1 = 67108864 diff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi index d0853792b636d..64a009318894b 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -1,16 +1,16 @@ import sys from _typeshed import structseq -from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, Union, final, type_check_only +from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, final, type_check_only from typing_extensions import TypeAlias _TimeTuple: TypeAlias = tuple[int, int, int, int, int, int, int, int, int] if sys.version_info >= (3, 15): # anticipate on https://github.com/python/cpython/pull/139224 - _SupportsFloatOrIndex: TypeAlias = Union[SupportsFloat, SupportsIndex] + _SupportsFloatOrIndex: TypeAlias = SupportsFloat | SupportsIndex else: # before, time functions only accept (subclass of) float, *not* SupportsFloat - _SupportsFloatOrIndex: TypeAlias = Union[float, SupportsIndex] + _SupportsFloatOrIndex: TypeAlias = float | SupportsIndex altzone: int daylight: int diff --git a/mypy/typeshed/stdlib/tokenize.pyi b/mypy/typeshed/stdlib/tokenize.pyi index 00a24b4eea07d..0df8062d56891 100644 --- a/mypy/typeshed/stdlib/tokenize.pyi +++ b/mypy/typeshed/stdlib/tokenize.pyi @@ -151,8 +151,8 @@ class Untokenizer: # Returns str, unless the ENCODING token is present, in which case it returns bytes. def untokenize(iterable: Iterable[_Token]) -> str | Any: ... def detect_encoding(readline: Callable[[], bytes | bytearray]) -> tuple[str, Sequence[bytes]]: ... -def tokenize(readline: Callable[[], bytes | bytearray]) -> Generator[TokenInfo, None, None]: ... -def generate_tokens(readline: Callable[[], str]) -> Generator[TokenInfo, None, None]: ... +def tokenize(readline: Callable[[], bytes | bytearray]) -> Generator[TokenInfo]: ... +def generate_tokens(readline: Callable[[], str]) -> Generator[TokenInfo]: ... def open(filename: FileDescriptorOrPath) -> TextIO: ... def group(*choices: str) -> str: ... # undocumented def any(*choices: str) -> str: ... # undocumented diff --git a/mypy/typeshed/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi index 4305706afa20b..f9d88f25afd97 100644 --- a/mypy/typeshed/stdlib/traceback.pyi +++ b/mypy/typeshed/stdlib/traceback.pyi @@ -111,7 +111,7 @@ def walk_tb(tb: TracebackType | None) -> Iterator[tuple[FrameType, int]]: ... if sys.version_info >= (3, 11): class _ExceptionPrintContext: def indent(self) -> str: ... - def emit(self, text_gen: str | Iterable[str], margin_char: str | None = None) -> Generator[str, None, None]: ... + def emit(self, text_gen: str | Iterable[str], margin_char: str | None = None) -> Generator[str]: ... class TracebackException: __cause__: TracebackException | None @@ -232,14 +232,14 @@ class TracebackException: def __eq__(self, other: object) -> bool: ... __hash__: ClassVar[None] # type: ignore[assignment] if sys.version_info >= (3, 11): - def format(self, *, chain: bool = True, _ctx: _ExceptionPrintContext | None = None) -> Generator[str, None, None]: ... + def format(self, *, chain: bool = True, _ctx: _ExceptionPrintContext | None = None) -> Generator[str]: ... else: - def format(self, *, chain: bool = True) -> Generator[str, None, None]: ... + def format(self, *, chain: bool = True) -> Generator[str]: ... if sys.version_info >= (3, 13): - def format_exception_only(self, *, show_group: bool = False, _depth: int = 0) -> Generator[str, None, None]: ... + def format_exception_only(self, *, show_group: bool = False, _depth: int = 0) -> Generator[str]: ... else: - def format_exception_only(self) -> Generator[str, None, None]: ... + def format_exception_only(self) -> Generator[str]: ... if sys.version_info >= (3, 11): def print(self, *, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: ... diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 0bced03866439..af1d1650da411 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -640,14 +640,17 @@ class AsyncGenerator(AsyncIterator[_YieldT_co], Protocol[_YieldT_co, _SendT_cont ) -> Coroutine[Any, Any, _YieldT_co]: ... def aclose(self) -> Coroutine[Any, Any, None]: ... +_ContainerT_contra = TypeVar("_ContainerT_contra", contravariant=True, default=Any) + @runtime_checkable -class Container(Protocol[_T_co]): +class Container(Protocol[_ContainerT_contra]): # This is generic more on vibes than anything else @abstractmethod - def __contains__(self, x: object, /) -> bool: ... + def __contains__(self, x: _ContainerT_contra, /) -> bool: ... @runtime_checkable -class Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): +class Collection(Iterable[_T_co], Container[Any], Protocol[_T_co]): + # Note: need to use Container[Any] instead of Container[_T_co] to ensure covariance. # Implement Sized (but don't have it as a base class). @abstractmethod def __len__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index 16cf0611a58ad..406005cc4c561 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -220,7 +220,7 @@ def runtime_checkable(cls: _TC) -> _TC: ... runtime = runtime_checkable Final: _SpecialForm -def final(f: _F) -> _F: ... +def final(f: _T) -> _T: ... def disjoint_base(cls: _TC) -> _TC: ... Literal: _SpecialForm diff --git a/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi b/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi index 80f3c55c14899..5c03dd014b639 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi @@ -8,10 +8,10 @@ xpath_tokenizer_re: Final[Pattern[str]] _Token: TypeAlias = tuple[str, str] _Next: TypeAlias = Callable[[], _Token] -_Callback: TypeAlias = Callable[[_SelectorContext, Iterable[Element]], Generator[Element, None, None]] +_Callback: TypeAlias = Callable[[_SelectorContext, Iterable[Element]], Generator[Element]] _T = TypeVar("_T") -def xpath_tokenizer(pattern: str, namespaces: dict[str, str] | None = None) -> Generator[_Token, None, None]: ... +def xpath_tokenizer(pattern: str, namespaces: dict[str, str] | None = None) -> Generator[_Token]: ... def get_parent_map(context: _SelectorContext) -> dict[Element, Element]: ... def prepare_child(next: _Next, token: _Token) -> _Callback: ... def prepare_star(next: _Next, token: _Token) -> _Callback: ... @@ -32,7 +32,7 @@ def iterfind( # type: ignore[overload-overlap] elem: Element[Any], path: Literal[""], namespaces: dict[str, str] | None = None ) -> None: ... @overload -def iterfind(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> Generator[Element, None, None]: ... +def iterfind(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> Generator[Element]: ... def find(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> Element | None: ... def findall(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ... @overload diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index d728fb975bfb9..6340a44bd51c8 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -106,12 +106,12 @@ class Element(Generic[_Tag]): def get(self, key: str, default: _T) -> str | _T: ... def insert(self, index: int, subelement: Element[Any], /) -> None: ... def items(self) -> ItemsView[str, str]: ... - def iter(self, tag: str | None = None) -> Generator[Element, None, None]: ... + def iter(self, tag: str | None = None) -> Generator[Element]: ... @overload def iterfind(self, path: Literal[""], namespaces: dict[str, str] | None = None) -> None: ... # type: ignore[overload-overlap] @overload - def iterfind(self, path: str, namespaces: dict[str, str] | None = None) -> Generator[Element, None, None]: ... - def itertext(self) -> Generator[str, None, None]: ... + def iterfind(self, path: str, namespaces: dict[str, str] | None = None) -> Generator[Element]: ... + def itertext(self) -> Generator[str]: ... def keys(self) -> dict_keys[str, str]: ... # makeelement returns the type of self in Python impl, but not in C impl def makeelement(self, tag: _OtherTag, attrib: dict[str, str], /) -> Element[_OtherTag]: ... @@ -159,7 +159,7 @@ class ElementTree(Generic[_Root]): def getroot(self) -> _Root: ... def _setroot(self, element: Element[Any]) -> None: ... def parse(self, source: _FileRead, parser: XMLParser | None = None) -> Element: ... - def iter(self, tag: str | None = None) -> Generator[Element, None, None]: ... + def iter(self, tag: str | None = None) -> Generator[Element]: ... def find(self, path: str, namespaces: dict[str, str] | None = None) -> Element | None: ... @overload def findtext(self, path: str, default: None = None, namespaces: dict[str, str] | None = None) -> str | None: ... @@ -169,7 +169,7 @@ class ElementTree(Generic[_Root]): @overload def iterfind(self, path: Literal[""], namespaces: dict[str, str] | None = None) -> None: ... # type: ignore[overload-overlap] @overload - def iterfind(self, path: str, namespaces: dict[str, str] | None = None) -> Generator[Element, None, None]: ... + def iterfind(self, path: str, namespaces: dict[str, str] | None = None) -> Generator[Element]: ... def write( self, file_or_filename: _FileWrite, From 46c81f51d87c40d935e43e547b6e993e33fc25ef Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Wed, 18 Feb 2026 13:11:02 +0100 Subject: [PATCH 02/10] Adjust stubs to fix mypy lookup error due to circular dependencies in stubs --- mypy/typeshed/stdlib/time.pyi | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi index 64a009318894b..d0853792b636d 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -1,16 +1,16 @@ import sys from _typeshed import structseq -from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, final, type_check_only +from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, Union, final, type_check_only from typing_extensions import TypeAlias _TimeTuple: TypeAlias = tuple[int, int, int, int, int, int, int, int, int] if sys.version_info >= (3, 15): # anticipate on https://github.com/python/cpython/pull/139224 - _SupportsFloatOrIndex: TypeAlias = SupportsFloat | SupportsIndex + _SupportsFloatOrIndex: TypeAlias = Union[SupportsFloat, SupportsIndex] else: # before, time functions only accept (subclass of) float, *not* SupportsFloat - _SupportsFloatOrIndex: TypeAlias = float | SupportsIndex + _SupportsFloatOrIndex: TypeAlias = Union[float, SupportsIndex] altzone: int daylight: int From 042e0b002a84500037fbf98d8a8895a1926ba1c3 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Sat, 15 Feb 2025 20:11:06 +0100 Subject: [PATCH 03/10] Partially revert Clean up argparse hacks --- mypy/typeshed/stdlib/argparse.pyi | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index e1ad7cbc4570d..7d4bd1a3a8418 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import SupportsWrite, sentinel from collections.abc import Callable, Generator, Iterable, Sequence from re import Pattern -from typing import IO, Any, ClassVar, Final, Generic, NoReturn, Protocol, TypeVar, overload, type_check_only +from typing import IO, Any, ClassVar, Final, Generic, NewType, NoReturn, Protocol, TypeVar, overload, type_check_only from typing_extensions import Self, TypeAlias, deprecated __all__ = [ @@ -36,7 +36,9 @@ ONE_OR_MORE: Final = "+" OPTIONAL: Final = "?" PARSER: Final = "A..." REMAINDER: Final = "..." -SUPPRESS: Final = "==SUPPRESS==" +_SUPPRESS_T = NewType("_SUPPRESS_T", str) +SUPPRESS: _SUPPRESS_T | str # not using Literal because argparse sometimes compares SUPPRESS with is +# the | str is there so that foo = argparse.SUPPRESS; foo = "test" checks out in mypy ZERO_OR_MORE: Final = "*" _UNRECOGNIZED_ARGS_ATTR: Final = "_unrecognized_args" # undocumented @@ -79,7 +81,7 @@ class _ActionsContainer: # more precisely, Literal["?", "*", "+", "...", "A...", "==SUPPRESS=="], # but using this would make it hard to annotate callers that don't use a # literal argument and for subclasses to override this method. - nargs: int | str | None = None, + nargs: int | str | _SUPPRESS_T | None = None, const: Any = ..., default: Any = ..., type: _ActionType = ..., From 68047c4e519d741bbb0b3c4ef2b888c074eb298d Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Mon, 26 Sep 2022 12:55:07 -0700 Subject: [PATCH 04/10] Remove use of LiteralString in builtins (#13743) --- mypy/typeshed/stdlib/builtins.pyi | 98 ------------------------------- 1 file changed, 98 deletions(-) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 5657ac74a9acf..2acf400263dcf 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -64,7 +64,6 @@ from typing import ( # noqa: Y022,UP035,RUF100 from typing_extensions import ( # noqa: Y023 Concatenate, Literal, - LiteralString, ParamSpec, Self, TypeAlias, @@ -482,31 +481,16 @@ class str(Sequence[str]): def __new__(cls, object: object = "") -> Self: ... @overload def __new__(cls, object: ReadableBuffer, encoding: str = "utf-8", errors: str = "strict") -> Self: ... - @overload - def capitalize(self: LiteralString) -> LiteralString: ... - @overload def capitalize(self) -> str: ... # type: ignore[misc] - @overload - def casefold(self: LiteralString) -> LiteralString: ... - @overload def casefold(self) -> str: ... # type: ignore[misc] - @overload - def center(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... - @overload def center(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] def count(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... def endswith( self, suffix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> bool: ... - @overload - def expandtabs(self: LiteralString, tabsize: SupportsIndex = 8) -> LiteralString: ... - @overload def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ... # type: ignore[misc] def find(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... - @overload - def format(self: LiteralString, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... - @overload def format(self, *args: object, **kwargs: object) -> str: ... def format_map(self, mapping: _FormatMapMapping, /) -> str: ... def index(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... @@ -522,98 +506,34 @@ class str(Sequence[str]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - @overload - def join(self: LiteralString, iterable: Iterable[LiteralString], /) -> LiteralString: ... - @overload def join(self, iterable: Iterable[str], /) -> str: ... # type: ignore[misc] - @overload - def ljust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... - @overload def ljust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] - @overload - def lower(self: LiteralString) -> LiteralString: ... - @overload def lower(self) -> str: ... # type: ignore[misc] - @overload - def lstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... - @overload def lstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] - @overload - def partition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ... - @overload def partition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] if sys.version_info >= (3, 13): - @overload - def replace( - self: LiteralString, old: LiteralString, new: LiteralString, /, count: SupportsIndex = -1 - ) -> LiteralString: ... - @overload def replace(self, old: str, new: str, /, count: SupportsIndex = -1) -> str: ... # type: ignore[misc] else: - @overload - def replace( - self: LiteralString, old: LiteralString, new: LiteralString, count: SupportsIndex = -1, / - ) -> LiteralString: ... - @overload def replace(self, old: str, new: str, count: SupportsIndex = -1, /) -> str: ... # type: ignore[misc] - @overload - def removeprefix(self: LiteralString, prefix: LiteralString, /) -> LiteralString: ... - @overload def removeprefix(self, prefix: str, /) -> str: ... # type: ignore[misc] - @overload - def removesuffix(self: LiteralString, suffix: LiteralString, /) -> LiteralString: ... - @overload def removesuffix(self, suffix: str, /) -> str: ... # type: ignore[misc] def rfind(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... def rindex(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... - @overload - def rjust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... - @overload def rjust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] - @overload - def rpartition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ... - @overload def rpartition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] - @overload - def rsplit(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... - @overload def rsplit(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] - @overload - def rstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... - @overload def rstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] - @overload - def split(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... - @overload def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] - @overload - def splitlines(self: LiteralString, keepends: bool = False) -> list[LiteralString]: ... - @overload def splitlines(self, keepends: bool = False) -> list[str]: ... # type: ignore[misc] def startswith( self, prefix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> bool: ... - @overload - def strip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... - @overload def strip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] - @overload - def swapcase(self: LiteralString) -> LiteralString: ... - @overload def swapcase(self) -> str: ... # type: ignore[misc] - @overload - def title(self: LiteralString) -> LiteralString: ... - @overload def title(self) -> str: ... # type: ignore[misc] def translate(self, table: _TranslateTable, /) -> str: ... - @overload - def upper(self: LiteralString) -> LiteralString: ... - @overload def upper(self) -> str: ... # type: ignore[misc] - @overload - def zfill(self: LiteralString, width: SupportsIndex, /) -> LiteralString: ... - @overload def zfill(self, width: SupportsIndex, /) -> str: ... # type: ignore[misc] @staticmethod @overload @@ -624,39 +544,21 @@ class str(Sequence[str]): @staticmethod @overload def maketrans(x: str, y: str, z: str, /) -> dict[int, int | None]: ... - @overload - def __add__(self: LiteralString, value: LiteralString, /) -> LiteralString: ... - @overload def __add__(self, value: str, /) -> str: ... # type: ignore[misc] # Incompatible with Sequence.__contains__ def __contains__(self, key: str, /) -> bool: ... # type: ignore[override] def __eq__(self, value: object, /) -> bool: ... def __ge__(self, value: str, /) -> bool: ... - @overload - def __getitem__(self: LiteralString, key: SupportsIndex | slice[SupportsIndex | None], /) -> LiteralString: ... - @overload def __getitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> str: ... # type: ignore[misc] def __gt__(self, value: str, /) -> bool: ... def __hash__(self) -> int: ... - @overload - def __iter__(self: LiteralString) -> Iterator[LiteralString]: ... - @overload def __iter__(self) -> Iterator[str]: ... # type: ignore[misc] def __le__(self, value: str, /) -> bool: ... def __len__(self) -> int: ... def __lt__(self, value: str, /) -> bool: ... - @overload - def __mod__(self: LiteralString, value: LiteralString | tuple[LiteralString, ...], /) -> LiteralString: ... - @overload def __mod__(self, value: Any, /) -> str: ... - @overload - def __mul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... - @overload def __mul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] def __ne__(self, value: object, /) -> bool: ... - @overload - def __rmul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... - @overload def __rmul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] def __getnewargs__(self) -> tuple[str]: ... def __format__(self, format_spec: str, /) -> str: ... From bbd1965efe2ead4e1cfb0df2bb8d36331c7a1fda Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Sat, 21 Dec 2024 22:36:38 +0100 Subject: [PATCH 05/10] Revert Remove redundant inheritances from Iterator in builtins --- mypy/typeshed/stdlib/_asyncio.pyi | 4 +- mypy/typeshed/stdlib/builtins.pyi | 10 ++--- mypy/typeshed/stdlib/csv.pyi | 4 +- mypy/typeshed/stdlib/fileinput.pyi | 6 +-- mypy/typeshed/stdlib/itertools.pyi | 38 +++++++++---------- mypy/typeshed/stdlib/multiprocessing/pool.pyi | 4 +- mypy/typeshed/stdlib/sqlite3/__init__.pyi | 2 +- 7 files changed, 34 insertions(+), 34 deletions(-) diff --git a/mypy/typeshed/stdlib/_asyncio.pyi b/mypy/typeshed/stdlib/_asyncio.pyi index d663f5d935554..f43178e4d7258 100644 --- a/mypy/typeshed/stdlib/_asyncio.pyi +++ b/mypy/typeshed/stdlib/_asyncio.pyi @@ -1,6 +1,6 @@ import sys from asyncio.events import AbstractEventLoop -from collections.abc import Awaitable, Callable, Coroutine, Generator +from collections.abc import Awaitable, Callable, Coroutine, Generator, Iterable from contextvars import Context from types import FrameType, GenericAlias from typing import Any, Literal, TextIO, TypeVar @@ -11,7 +11,7 @@ _T_co = TypeVar("_T_co", covariant=True) _TaskYieldType: TypeAlias = Future[object] | None @disjoint_base -class Future(Awaitable[_T]): +class Future(Awaitable[_T], Iterable[_T]): _state: str @property def _exception(self) -> BaseException | None: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 2acf400263dcf..f2990b89fc54c 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -1220,7 +1220,7 @@ class frozenset(AbstractSet[_T_co]): def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @disjoint_base -class enumerate(Generic[_T]): +class enumerate(Iterator[tuple[int, _T]]): def __new__(cls, iterable: Iterable[_T], start: int = 0) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> tuple[int, _T]: ... @@ -1407,7 +1407,7 @@ else: exit: _sitebuiltins.Quitter @disjoint_base -class filter(Generic[_T]): +class filter(Iterator[_T]): @overload def __new__(cls, function: None, iterable: Iterable[_T | None], /) -> Self: ... @overload @@ -1471,7 +1471,7 @@ license: _sitebuiltins._Printer def locals() -> dict[str, Any]: ... @disjoint_base -class map(Generic[_S]): +class map(Iterator[_S]): # 3.14 adds `strict` argument. if sys.version_info >= (3, 14): @overload @@ -1778,7 +1778,7 @@ def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex quit: _sitebuiltins.Quitter @disjoint_base -class reversed(Generic[_T]): +class reversed(Iterator[_T]): @overload def __new__(cls, sequence: Reversible[_T], /) -> Iterator[_T]: ... # type: ignore[misc] @overload @@ -1842,7 +1842,7 @@ def vars(object: type, /) -> types.MappingProxyType[str, Any]: ... @overload def vars(object: Any = ..., /) -> dict[str, Any]: ... @disjoint_base -class zip(Generic[_T_co]): +class zip(Iterator[_T_co]): if sys.version_info >= (3, 10): @overload def __new__(cls, *, strict: bool = False) -> zip[Any]: ... diff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi index 2c8e7109cdfc3..4ed0ab1d83b82 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi @@ -25,7 +25,7 @@ else: from _csv import _reader as Reader, _writer as Writer from _typeshed import SupportsWrite -from collections.abc import Collection, Iterable, Mapping, Sequence +from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence from types import GenericAlias from typing import Any, Generic, Literal, TypeVar, overload from typing_extensions import Self @@ -73,7 +73,7 @@ class excel(Dialect): ... class excel_tab(excel): ... class unix_dialect(Dialect): ... -class DictReader(Generic[_T]): +class DictReader(Iterator[dict[_T | Any, str | Any]], Generic[_T]): fieldnames: Sequence[_T] | None restkey: _T | None restval: str | Any | None diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index 6778b764810bd..95164de2f0107 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -1,8 +1,8 @@ import sys from _typeshed import AnyStr_co, StrOrBytesPath -from collections.abc import Callable, Iterable +from collections.abc import Callable, Iterable, Iterator from types import GenericAlias, TracebackType -from typing import IO, Any, AnyStr, Generic, Literal, Protocol, overload, type_check_only +from typing import IO, Any, AnyStr, Literal, Protocol, overload, type_check_only from typing_extensions import Self, TypeAlias, deprecated __all__ = [ @@ -105,7 +105,7 @@ def fileno() -> int: ... def isfirstline() -> bool: ... def isstdin() -> bool: ... -class FileInput(Generic[AnyStr]): +class FileInput(Iterator[AnyStr]): if sys.version_info >= (3, 10): # encoding and errors are added @overload diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index 8a924ad8b1e71..4713d62cc346f 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -28,7 +28,7 @@ _Predicate: TypeAlias = Callable[[_T], object] # Technically count can take anything that implements a number protocol and has an add method # but we can't enforce the add method @disjoint_base -class count(Generic[_N]): +class count(Iterator[_N]): @overload def __new__(cls) -> count[int]: ... @overload @@ -39,13 +39,13 @@ class count(Generic[_N]): def __iter__(self) -> Self: ... @disjoint_base -class cycle(Generic[_T]): +class cycle(Iterator[_T]): def __new__(cls, iterable: Iterable[_T], /) -> Self: ... def __next__(self) -> _T: ... def __iter__(self) -> Self: ... @disjoint_base -class repeat(Generic[_T]): +class repeat(Iterator[_T]): @overload def __new__(cls, object: _T) -> Self: ... @overload @@ -55,7 +55,7 @@ class repeat(Generic[_T]): def __length_hint__(self) -> int: ... @disjoint_base -class accumulate(Generic[_T]): +class accumulate(Iterator[_T]): @overload def __new__(cls, iterable: Iterable[_T], func: None = None, *, initial: _T | None = None) -> Self: ... @overload @@ -64,7 +64,7 @@ class accumulate(Generic[_T]): def __next__(self) -> _T: ... @disjoint_base -class chain(Generic[_T]): +class chain(Iterator[_T]): def __new__(cls, *iterables: Iterable[_T]) -> Self: ... def __next__(self) -> _T: ... def __iter__(self) -> Self: ... @@ -74,25 +74,25 @@ class chain(Generic[_T]): def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @disjoint_base -class compress(Generic[_T]): +class compress(Iterator[_T]): def __new__(cls, data: Iterable[_T], selectors: Iterable[Any]) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... @disjoint_base -class dropwhile(Generic[_T]): +class dropwhile(Iterator[_T]): def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... @disjoint_base -class filterfalse(Generic[_T]): +class filterfalse(Iterator[_T]): def __new__(cls, function: _Predicate[_T] | None, iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... @disjoint_base -class groupby(Generic[_T_co, _S_co]): +class groupby(Iterator[tuple[_T_co, Iterator[_S_co]]], Generic[_T_co, _S_co]): @overload def __new__(cls, iterable: Iterable[_T1], key: None = None) -> groupby[_T1, _T1]: ... @overload @@ -101,7 +101,7 @@ class groupby(Generic[_T_co, _S_co]): def __next__(self) -> tuple[_T_co, Iterator[_S_co]]: ... @disjoint_base -class islice(Generic[_T]): +class islice(Iterator[_T]): @overload def __new__(cls, iterable: Iterable[_T], stop: int | None, /) -> Self: ... @overload @@ -110,20 +110,20 @@ class islice(Generic[_T]): def __next__(self) -> _T: ... @disjoint_base -class starmap(Generic[_T_co]): +class starmap(Iterator[_T_co]): def __new__(cls, function: Callable[..., _T], iterable: Iterable[Iterable[Any]], /) -> starmap[_T]: ... def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... @disjoint_base -class takewhile(Generic[_T]): +class takewhile(Iterator[_T]): def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... def tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]: ... @disjoint_base -class zip_longest(Generic[_T_co]): +class zip_longest(Iterator[_T_co]): # one iterable (fillvalue doesn't matter) @overload def __new__(cls, iter1: Iterable[_T1], /, *, fillvalue: object = None) -> zip_longest[tuple[_T1]]: ... @@ -202,7 +202,7 @@ class zip_longest(Generic[_T_co]): def __next__(self) -> _T_co: ... @disjoint_base -class product(Generic[_T_co]): +class product(Iterator[_T_co]): @overload def __new__(cls, iter1: Iterable[_T1], /) -> product[tuple[_T1]]: ... @overload @@ -288,7 +288,7 @@ class product(Generic[_T_co]): def __next__(self) -> _T_co: ... @disjoint_base -class permutations(Generic[_T_co]): +class permutations(Iterator[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> permutations[tuple[_T, _T]]: ... @overload @@ -303,7 +303,7 @@ class permutations(Generic[_T_co]): def __next__(self) -> _T_co: ... @disjoint_base -class combinations(Generic[_T_co]): +class combinations(Iterator[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations[tuple[_T, _T]]: ... @overload @@ -318,7 +318,7 @@ class combinations(Generic[_T_co]): def __next__(self) -> _T_co: ... @disjoint_base -class combinations_with_replacement(Generic[_T_co]): +class combinations_with_replacement(Iterator[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations_with_replacement[tuple[_T, _T]]: ... @overload @@ -334,14 +334,14 @@ class combinations_with_replacement(Generic[_T_co]): if sys.version_info >= (3, 10): @disjoint_base - class pairwise(Generic[_T_co]): + class pairwise(Iterator[_T_co]): def __new__(cls, iterable: Iterable[_T], /) -> pairwise[tuple[_T, _T]]: ... def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... if sys.version_info >= (3, 12): @disjoint_base - class batched(Generic[_T_co]): + class batched(Iterator[_T_co], Generic[_T_co]): if sys.version_info >= (3, 13): @overload def __new__(cls, iterable: Iterable[_T], n: Literal[1], *, strict: Literal[True]) -> batched[tuple[_T]]: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi index b79f9e77359ae..f276372d09039 100644 --- a/mypy/typeshed/stdlib/multiprocessing/pool.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/pool.pyi @@ -1,4 +1,4 @@ -from collections.abc import Callable, Iterable, Mapping +from collections.abc import Callable, Iterable, Iterator, Mapping from multiprocessing.context import DefaultContext, Process from types import GenericAlias, TracebackType from typing import Any, Final, Generic, TypeVar @@ -32,7 +32,7 @@ class MapResult(ApplyResult[list[_T]]): error_callback: Callable[[BaseException], object] | None, ) -> None: ... -class IMapIterator(Generic[_T]): +class IMapIterator(Iterator[_T]): def __init__(self, pool: Pool) -> None: ... def __iter__(self) -> Self: ... def next(self, timeout: float | None = None) -> _T: ... diff --git a/mypy/typeshed/stdlib/sqlite3/__init__.pyi b/mypy/typeshed/stdlib/sqlite3/__init__.pyi index 86ae7bccdb113..ec37eed8c9277 100644 --- a/mypy/typeshed/stdlib/sqlite3/__init__.pyi +++ b/mypy/typeshed/stdlib/sqlite3/__init__.pyi @@ -408,7 +408,7 @@ class Connection: ) -> Literal[False]: ... @disjoint_base -class Cursor: +class Cursor(Iterator[Any]): arraysize: int @property def connection(self) -> Connection: ... From fa4ba513d0df17781734c240f0ed812957c56df5 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Mon, 23 Feb 2026 12:00:18 +0100 Subject: [PATCH 06/10] Revert Use contravariant type variable in Container --- mypy/typeshed/stdlib/typing.pyi | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index af1d1650da411..0bced03866439 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -640,17 +640,14 @@ class AsyncGenerator(AsyncIterator[_YieldT_co], Protocol[_YieldT_co, _SendT_cont ) -> Coroutine[Any, Any, _YieldT_co]: ... def aclose(self) -> Coroutine[Any, Any, None]: ... -_ContainerT_contra = TypeVar("_ContainerT_contra", contravariant=True, default=Any) - @runtime_checkable -class Container(Protocol[_ContainerT_contra]): +class Container(Protocol[_T_co]): # This is generic more on vibes than anything else @abstractmethod - def __contains__(self, x: _ContainerT_contra, /) -> bool: ... + def __contains__(self, x: object, /) -> bool: ... @runtime_checkable -class Collection(Iterable[_T_co], Container[Any], Protocol[_T_co]): - # Note: need to use Container[Any] instead of Container[_T_co] to ensure covariance. +class Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): # Implement Sized (but don't have it as a base class). @abstractmethod def __len__(self) -> int: ... From 3d84558a4d9892a7cee51fe9a1a37a493b4e2532 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Wed, 8 Apr 2026 00:01:44 +0100 Subject: [PATCH 07/10] Revert dict.__or__ typeshed change --- mypy/typeshed/stdlib/builtins.pyi | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index f2990b89fc54c..e70e2500fb127 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -1142,7 +1142,13 @@ class dict(MutableMapping[_KT, _VT]): def __reversed__(self) -> Iterator[_KT]: ... __hash__: ClassVar[None] # type: ignore[assignment] def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + @overload + def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + @overload + def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... # dict.__ior__ should be kept roughly in line with MutableMapping.update() @overload # type: ignore[misc] From 533aa6b7b89784b25c777d07769ee09455a1d419 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Sat, 29 Oct 2022 12:47:21 -0700 Subject: [PATCH 08/10] Revert sum literal integer change (#13961) This is allegedly causing large performance problems, see 13821 typeshed/8231 had zero hits on mypy_primer, so it's not the worst thing to undo. Patching this in typeshed also feels weird, since there's a more general soundness issue. If a typevar has a bound or constraint, we might not want to solve it to a Literal. If we can confirm the performance regression or fix the unsoundness within mypy, I might pursue upstreaming this in typeshed. (Reminder: add this to the sync_typeshed script once merged) --- mypy/typeshed/stdlib/builtins.pyi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index e70e2500fb127..25b21ba971540 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -1835,7 +1835,7 @@ _SupportsSumNoDefaultT = TypeVar("_SupportsSumNoDefaultT", bound=_SupportsSumWit # without creating many false-positive errors (see #7578). # Instead, we special-case the most common examples of this: bool and literal integers. @overload -def sum(iterable: Iterable[bool | _LiteralInteger], /, start: int = 0) -> int: ... +def sum(iterable: Iterable[bool], /, start: int = 0) -> int: ... @overload def sum(iterable: Iterable[_SupportsSumNoDefaultT], /) -> _SupportsSumNoDefaultT | Literal[0]: ... @overload From 8c2b9833fe9d8e36aca6aef3e6d9c4f51a78e48a Mon Sep 17 00:00:00 2001 From: AlexWaygood Date: Mon, 1 May 2023 20:34:55 +0100 Subject: [PATCH 09/10] Revert typeshed ctypes change The plugin provides superior type checking: https://github.com/python/mypy/pull/13987#issuecomment-1310863427 A manual cherry-pick of e437cdf. --- mypy/typeshed/stdlib/_ctypes.pyi | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/mypy/typeshed/stdlib/_ctypes.pyi b/mypy/typeshed/stdlib/_ctypes.pyi index 3c4308628c8c9..0e02092a361c9 100644 --- a/mypy/typeshed/stdlib/_ctypes.pyi +++ b/mypy/typeshed/stdlib/_ctypes.pyi @@ -320,11 +320,7 @@ class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): def _type_(self) -> type[_CT]: ... @_type_.setter def _type_(self, value: type[_CT]) -> None: ... - # Note: only available if _CT == c_char - @property - def raw(self) -> bytes: ... - @raw.setter - def raw(self, value: ReadableBuffer) -> None: ... + raw: bytes # Note: only available if _CT == c_char value: Any # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise # TODO: These methods cannot be annotated correctly at the moment. # All of these "Any"s stand for the array's element type, but it's not possible to use _CT From 196e129e6b2c66c1565d5f854c5076d5669b3dd1 Mon Sep 17 00:00:00 2001 From: Shantanu Jain Date: Sun, 22 Feb 2026 20:37:48 -0800 Subject: [PATCH 10/10] Temporarily revert contextlib deprecation --- mypy/typeshed/stdlib/contextlib.pyi | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index dff34474d2f5b..0670787a5db1b 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -5,7 +5,7 @@ from abc import ABC, abstractmethod from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Generator, Iterator from types import TracebackType from typing import Any, Generic, Protocol, TypeVar, overload, runtime_checkable, type_check_only -from typing_extensions import ParamSpec, Self, TypeAlias, deprecated +from typing_extensions import ParamSpec, Self, TypeAlias __all__ = [ "contextmanager", @@ -86,12 +86,6 @@ class _GeneratorContextManager( self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> bool | None: ... -@overload -def contextmanager(func: Callable[_P, Generator[_T_co, None, object]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ... -@overload -@deprecated( - "Annotating the return type as `-> Iterator[Foo]` with `@contextmanager` is deprecated. Use `-> Generator[Foo]` instead." -) def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ... if sys.version_info >= (3, 10): @@ -118,13 +112,6 @@ else: self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> bool | None: ... -@overload -def asynccontextmanager(func: Callable[_P, AsyncGenerator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ... -@overload -@deprecated( - "Annotating the return type as `-> AsyncIterator[Foo]` with `@asynccontextmanager` is deprecated. " - "Use `-> AsyncGenerator[Foo]` instead." -) def asynccontextmanager(func: Callable[_P, AsyncIterator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ... @type_check_only class _SupportsClose(Protocol):