From 91a25e2e31ce0ad2823dd3391bbf19f28c3816ee Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Thu, 16 Jul 2026 11:45:34 +0200 Subject: [PATCH 01/12] Update typeshed patches --- ...redundant-inheritances-from-Iterator.patch | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/misc/typeshed_patches/0001-Revert-Remove-redundant-inheritances-from-Iterator.patch b/misc/typeshed_patches/0001-Revert-Remove-redundant-inheritances-from-Iterator.patch index 96779922b52f6..4673723087efb 100644 --- a/misc/typeshed_patches/0001-Revert-Remove-redundant-inheritances-from-Iterator.patch +++ b/misc/typeshed_patches/0001-Revert-Remove-redundant-inheritances-from-Iterator.patch @@ -1,4 +1,4 @@ -From d3dabcf7b7aaf0997b59f0a28bb41d17b6098f2c Mon Sep 17 00:00:00 2001 +From b5d1e4c76d8139e1a20f9178e8123f3ee39084d2 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] Revert Remove redundant inheritances from Iterator in @@ -15,7 +15,7 @@ Subject: [PATCH] Revert Remove redundant inheritances from Iterator in 7 files changed, 34 insertions(+), 34 deletions(-) diff --git a/mypy/typeshed/stdlib/_asyncio.pyi b/mypy/typeshed/stdlib/_asyncio.pyi -index 23b690a9c..0ce93a435 100644 +index 242093e1e..92bb4e5f4 100644 --- a/mypy/typeshed/stdlib/_asyncio.pyi +++ b/mypy/typeshed/stdlib/_asyncio.pyi @@ -1,6 +1,6 @@ @@ -36,10 +36,10 @@ index 23b690a9c..0ce93a435 100644 @property def _exception(self) -> BaseException | None: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi -index 1808e28e2..9db6f4fc7 100644 +index e63b74214..9ea382dd6 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi -@@ -1369,7 +1369,7 @@ class frozenset(AbstractSet[_T_co]): +@@ -1368,7 +1368,7 @@ class frozenset(AbstractSet[_T_co]): def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @disjoint_base @@ -48,7 +48,7 @@ index 1808e28e2..9db6f4fc7 100644 def __new__(cls, iterable: Iterable[_T], start: int = 0) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> tuple[int, _T]: ... -@@ -1635,7 +1635,7 @@ else: +@@ -1634,7 +1634,7 @@ else: exit: _sitebuiltins.Quitter @disjoint_base @@ -57,7 +57,7 @@ index 1808e28e2..9db6f4fc7 100644 @overload def __new__(cls, function: None, iterable: Iterable[_T | None], /) -> Self: ... @overload -@@ -1706,7 +1706,7 @@ license: _sitebuiltins._Printer +@@ -1705,7 +1705,7 @@ license: _sitebuiltins._Printer def locals() -> dict[str, Any]: ... @disjoint_base @@ -66,7 +66,7 @@ index 1808e28e2..9db6f4fc7 100644 # 3.14 adds `strict` argument. if sys.version_info >= (3, 14): @overload -@@ -2022,7 +2022,7 @@ def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex +@@ -2021,7 +2021,7 @@ def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex quit: _sitebuiltins.Quitter @disjoint_base @@ -75,7 +75,7 @@ index 1808e28e2..9db6f4fc7 100644 @overload def __new__(cls, sequence: Reversible[_T], /) -> Iterator[_T]: ... # type: ignore[misc] @overload -@@ -2100,7 +2100,7 @@ def vars(object: type, /) -> types.MappingProxyType[str, Any]: ... +@@ -2101,7 +2101,7 @@ def vars(object: type, /) -> types.MappingProxyType[str, Any]: ... def vars(object: Any = ..., /) -> dict[str, Any]: ... @disjoint_base @@ -131,10 +131,10 @@ index 37783254c..db9c228f5 100644 @overload def __init__( diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi -index d26a4e1da..9d1cd84da 100644 +index 60e79bc2e..fd7daf11e 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi -@@ -28,7 +28,7 @@ _Predicate: TypeAlias = Callable[[_T], object] +@@ -28,7 +28,7 @@ _Predicate = 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 @@ -295,13 +295,13 @@ index d26a4e1da..9d1cd84da 100644 @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 b79f9e773..f276372d0 100644 +index 5642e50d0..203c5887c 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 multiprocessing.context import DefaultContext, Process as _Process from types import GenericAlias, TracebackType from typing import Any, Final, Generic, TypeVar @@ -32,7 +32,7 @@ class MapResult(ApplyResult[list[_T]]): @@ -314,10 +314,10 @@ index b79f9e773..f276372d0 100644 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 7c033bdf4..7bf020558 100644 +index 80a02079d..d1065a509 100644 --- a/mypy/typeshed/stdlib/sqlite3/__init__.pyi +++ b/mypy/typeshed/stdlib/sqlite3/__init__.pyi -@@ -426,7 +426,7 @@ class Connection: +@@ -437,7 +437,7 @@ class Connection: ) -> Literal[False]: ... @disjoint_base @@ -327,5 +327,5 @@ index 7c033bdf4..7bf020558 100644 @property def connection(self) -> Connection: ... -- -2.54.0 +2.55.0 From a42f0133d44c7d8750e577bf88f6c5457b473bb5 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Thu, 16 Jul 2026 11:45:58 +0200 Subject: [PATCH 02/12] Sync typeshed Source commit: https://github.com/python/typeshed/commit/c6d107067232008558616e8d0a13d150567b29d0 --- mypy/typeshed/stdlib/__future__.pyi | 2 +- mypy/typeshed/stdlib/_asyncio.pyi | 6 +- mypy/typeshed/stdlib/_ctypes.pyi | 7 +- mypy/typeshed/stdlib/_curses_panel.pyi | 8 +- mypy/typeshed/stdlib/_operator.pyi | 58 +++++-- mypy/typeshed/stdlib/argparse.pyi | 8 +- mypy/typeshed/stdlib/asyncio/base_events.pyi | 4 +- mypy/typeshed/stdlib/asyncio/events.pyi | 4 +- mypy/typeshed/stdlib/builtins.pyi | 159 +++++++++++++++--- mypy/typeshed/stdlib/collections/__init__.pyi | 6 +- mypy/typeshed/stdlib/contextlib.pyi | 19 ++- mypy/typeshed/stdlib/csv.pyi | 4 +- mypy/typeshed/stdlib/dataclasses.pyi | 12 +- mypy/typeshed/stdlib/dis.pyi | 4 +- mypy/typeshed/stdlib/fileinput.pyi | 6 +- mypy/typeshed/stdlib/inspect.pyi | 4 +- mypy/typeshed/stdlib/itertools.pyi | 40 ++--- .../stdlib/multiprocessing/managers.pyi | 5 +- mypy/typeshed/stdlib/multiprocessing/pool.pyi | 8 +- mypy/typeshed/stdlib/os/__init__.pyi | 2 +- mypy/typeshed/stdlib/platform.pyi | 4 +- mypy/typeshed/stdlib/socket.pyi | 9 +- mypy/typeshed/stdlib/sqlite3/__init__.pyi | 33 ++-- mypy/typeshed/stdlib/ssl.pyi | 14 +- mypy/typeshed/stdlib/time.pyi | 6 +- mypy/typeshed/stdlib/types.pyi | 2 +- mypy/typeshed/stdlib/typing.pyi | 15 +- mypy/typeshed/stdlib/typing_extensions.pyi | 6 +- 28 files changed, 320 insertions(+), 135 deletions(-) diff --git a/mypy/typeshed/stdlib/__future__.pyi b/mypy/typeshed/stdlib/__future__.pyi index a90cf1eddab76..aa445d22bd20d 100644 --- a/mypy/typeshed/stdlib/__future__.pyi +++ b/mypy/typeshed/stdlib/__future__.pyi @@ -1,4 +1,4 @@ -from typing_extensions import TypeAlias +from typing import TypeAlias _VersionInfo: TypeAlias = tuple[int, int, int, str, int] diff --git a/mypy/typeshed/stdlib/_asyncio.pyi b/mypy/typeshed/stdlib/_asyncio.pyi index 1e36b515d408a..242093e1ec799 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, TypeAlias, 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: ... @@ -53,7 +53,7 @@ else: # since the only reason why `asyncio.Future` is invariant is the `set_result()` method, # and `asyncio.Task.set_result()` always raises. @disjoint_base -class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments] +class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments] # ty:ignore[invalid-generic-class] if sys.version_info >= (3, 12): def __init__( self, diff --git a/mypy/typeshed/stdlib/_ctypes.pyi b/mypy/typeshed/stdlib/_ctypes.pyi index 1efb119263ef1..d800ac5c20d03 100644 --- a/mypy/typeshed/stdlib/_ctypes.pyi +++ b/mypy/typeshed/stdlib/_ctypes.pyi @@ -324,7 +324,12 @@ class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): @_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/_curses_panel.pyi b/mypy/typeshed/stdlib/_curses_panel.pyi index a552a151ddf14..64205618bf41c 100644 --- a/mypy/typeshed/stdlib/_curses_panel.pyi +++ b/mypy/typeshed/stdlib/_curses_panel.pyi @@ -1,4 +1,4 @@ -from _curses import window +from _curses import window as _window from typing import Final, final __version__: Final[str] @@ -14,14 +14,14 @@ class panel: def hidden(self) -> bool: ... def hide(self) -> None: ... def move(self, y: int, x: int, /) -> None: ... - def replace(self, win: window, /) -> None: ... + def replace(self, win: _window, /) -> None: ... def set_userptr(self, obj: object, /) -> None: ... def show(self) -> None: ... def top(self) -> None: ... def userptr(self) -> object: ... - def window(self) -> window: ... + def window(self) -> _window: ... def bottom_panel() -> panel: ... -def new_panel(win: window, /) -> panel: ... +def new_panel(win: _window, /) -> panel: ... def top_panel() -> panel: ... def update_panels() -> panel: ... diff --git a/mypy/typeshed/stdlib/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi index 29a6d70572028..04dae79dcd52d 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, ParamSpec, Protocol, SupportsAbs, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only @@ -8,6 +18,7 @@ from typing_extensions import 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,43 @@ 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: ... diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index fa22f842de028..22d330a089ef5 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, TypeAlias, TypeVar, overload, type_check_only +from typing import IO, Any, ClassVar, Final, Generic, NoReturn, Protocol, TypeAlias, TypeVar, overload, type_check_only from typing_extensions import Self, 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,7 +79,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 | _SUPPRESS_T | None = None, + nargs: int | str | None = None, const: Any = ..., default: Any = ..., type: _ActionType = ..., diff --git a/mypy/typeshed/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi index 9a3367b6aa3b2..3c7d8c2ce02e5 100644 --- a/mypy/typeshed/stdlib/asyncio/base_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_events.pyi @@ -10,7 +10,7 @@ from asyncio.transports import BaseTransport, DatagramTransport, ReadTransport, from collections.abc import Callable, Iterable, Sequence from concurrent.futures import Executor, ThreadPoolExecutor from contextvars import Context -from socket import AddressFamily, AddressInfo, SocketKind, _Address, _RetAddress, socket +from socket import AddressFamily, AddressInfo, _Address, _GetAddrInfoResult, _RetAddress, socket from typing import IO, Any, Literal, TypeAlias, TypeVar, overload from typing_extensions import TypeVarTuple, Unpack @@ -115,7 +115,7 @@ class BaseEventLoop(AbstractEventLoop): type: int = 0, proto: int = 0, flags: int = 0, - ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]]: ... + ) -> _GetAddrInfoResult: ... async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = 0) -> tuple[str, str]: ... if sys.version_info >= (3, 12): diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index 5e561b09cd460..89da5dece9070 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -11,7 +11,7 @@ from abc import ABCMeta, abstractmethod from collections.abc import Callable, Sequence from concurrent.futures import Executor from contextvars import Context -from socket import AddressFamily, AddressInfo, SocketKind, _Address, _RetAddress, socket +from socket import AddressFamily, AddressInfo, _Address, _GetAddrInfoResult, _RetAddress, socket from typing import IO, Any, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only from typing_extensions import Self, TypeVarTuple, Unpack, deprecated @@ -205,7 +205,7 @@ class AbstractEventLoop: type: int = 0, proto: int = 0, flags: int = 0, - ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]]: ... + ) -> _GetAddrInfoResult: ... @abstractmethod async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = 0) -> tuple[str, str]: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 8497f9e2e1037..096d440ac38cd 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -65,7 +65,7 @@ from typing import ( # noqa: Y022,UP035 ) # we can't import `Literal` from typing or mypy crashes: see #11247 -from typing_extensions import Literal, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023, UP035 +from typing_extensions import Literal, LiteralString, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023, UP035 if sys.version_info >= (3, 14): from _typeshed import AnnotateFunc @@ -489,8 +489,20 @@ 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: ... @@ -498,9 +510,17 @@ class str(Sequence[str]): 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: ... @@ -517,38 +537,119 @@ 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] if sys.version_info >= (3, 15): @@ -576,25 +677,49 @@ 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]: ... @@ -1228,27 +1353,14 @@ class dict(MutableMapping[_KT, _VT]): __hash__: ClassVar[None] # type: ignore[assignment] def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... if sys.version_info >= (3, 15): - @overload - def __or__(self, value: dict[_KT, _VT] | frozendict[_KT, _VT], /) -> dict[_KT, _VT]: ... - @overload def __or__(self, value: dict[_T1, _T2] | frozendict[_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]: ... @overload - def __ror__(self, value: frozendict[_KT, _VT], /) -> frozendict[_KT, _VT]: ... - @overload def __ror__(self, value: frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... else: - @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() @@ -1302,18 +1414,11 @@ if sys.version_info >= (3, 15): def __iter__(self) -> Iterator[_KT]: ... def __hash__(self) -> int: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... - @overload - def __or__(self, value: dict[_KT, _VT] | frozendict[_KT, _VT], /) -> frozendict[_KT, _VT]: ... - @overload def __or__(self, value: dict[_T1, _T2] | frozendict[_T1, _T2], /) -> frozendict[_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]: ... @overload - def __ror__(self, value: frozendict[_KT, _VT], /) -> frozendict[_KT, _VT]: ... - @overload def __ror__(self, value: frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... @disjoint_base @@ -1388,7 +1493,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]: ... @@ -1654,7 +1759,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 @@ -1725,7 +1830,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 @@ -2041,7 +2146,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 @@ -2107,7 +2212,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 @@ -2121,7 +2226,7 @@ def vars(object: type, /) -> types.MappingProxyType[str, Any]: ... def vars(object: Any = ..., /) -> dict[str, Any]: ... @disjoint_base -class zip(Iterator[_T_co]): +class zip(Generic[_T_co]): @overload def __new__(cls, *, strict: bool = False) -> zip[Any]: ... @overload diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index d9c2e342c5871..39b8a3c9ab6a5 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -364,17 +364,17 @@ class _OrderedDictValuesView(ValuesView[_VT_co]): # pyright doesn't have a specific error code for subclassing error! @final @type_check_only -class _odict_keys(dict_keys[_KT_co, _VT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] +class _odict_keys(dict_keys[_KT_co, _VT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[subclass-of-final-class] def __reversed__(self) -> Iterator[_KT_co]: ... @final @type_check_only -class _odict_items(dict_items[_KT_co, _VT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] +class _odict_items(dict_items[_KT_co, _VT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[subclass-of-final-class] def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... @final @type_check_only -class _odict_values(dict_values[_KT_co, _VT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] +class _odict_values(dict_values[_KT_co, _VT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[subclass-of-final-class] def __reversed__(self) -> Iterator[_VT_co]: ... @disjoint_base diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index 73cdda3b8f342..dd601675265cc 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, ParamSpec, Protocol, TypeAlias, TypeVar, overload, runtime_checkable, type_check_only -from typing_extensions import Self +from typing_extensions import Self, deprecated __all__ = [ "aclosing", @@ -43,7 +43,7 @@ _CM_EF = TypeVar("_CM_EF", bound=AbstractContextManager[Any, Any] | _ExitFunc) # At runtime it inherits from ABC and is not a Protocol, but it is on the # allowlist for use as a Protocol. @runtime_checkable -class AbstractContextManager(ABC, Protocol[_T_co, _ExitT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] +class AbstractContextManager(ABC, Protocol[_T_co, _ExitT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-protocol] __slots__ = () def __enter__(self) -> _T_co: ... @abstractmethod @@ -55,7 +55,7 @@ class AbstractContextManager(ABC, Protocol[_T_co, _ExitT_co]): # type: ignore[m # At runtime it inherits from ABC and is not a Protocol, but it is on the # allowlist for use as a Protocol. @runtime_checkable -class AbstractAsyncContextManager(ABC, Protocol[_T_co, _ExitT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] +class AbstractAsyncContextManager(ABC, Protocol[_T_co, _ExitT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-protocol] __slots__ = () async def __aenter__(self) -> _T_co: ... @abstractmethod @@ -84,6 +84,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]]: ... _AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]]) @@ -101,6 +107,13 @@ class _AsyncGeneratorContextManager( 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 diff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi index f3b4286a6b495..f8ab5f000a043 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi @@ -21,7 +21,7 @@ if sys.version_info >= (3, 12): from _csv import QUOTE_NOTNULL as QUOTE_NOTNULL, QUOTE_STRINGS as QUOTE_STRINGS from _csv import Reader, 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 @@ -69,7 +69,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/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index 1a7b8fd645589..fd5588e034903 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -298,7 +298,7 @@ def fields(class_or_instance: DataclassInstance | type[DataclassInstance]) -> tu # HACK: `obj: Never` typing matches if object argument is using `Any` type. @overload -def is_dataclass(obj: Never) -> TypeIs[DataclassInstance | type[DataclassInstance]]: ... # type: ignore[narrowed-type-not-subtype] # pyright: ignore[reportGeneralTypeIssues] +def is_dataclass(obj: Never) -> TypeIs[DataclassInstance | type[DataclassInstance]]: ... # type: ignore[narrowed-type-not-subtype] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-type-guard-definition] @overload def is_dataclass(obj: type) -> TypeIs[type[DataclassInstance]]: ... @overload @@ -308,13 +308,17 @@ class FrozenInstanceError(AttributeError): ... class InitVar(Generic[_T]): __slots__ = ("type",) - type: Type[_T] + type: Type[_T] # ty:ignore[unbound-type-variable] def __init__(self, type: Type[_T]) -> None: ... @overload - def __class_getitem__(cls, type: Type[_T]) -> InitVar[_T]: ... # pyright: ignore[reportInvalidTypeForm] + def __class_getitem__( + cls, type: Type[_T] + ) -> InitVar[_T]: ... # pyright: ignore[reportInvalidTypeForm] # ty:ignore[invalid-type-form] @overload - def __class_getitem__(cls, type: Any) -> InitVar[Any]: ... # pyright: ignore[reportInvalidTypeForm] + def __class_getitem__( + cls, type: Any + ) -> InitVar[Any]: ... # pyright: ignore[reportInvalidTypeForm] # ty:ignore[invalid-type-form] if sys.version_info >= (3, 14): def make_dataclass( diff --git a/mypy/typeshed/stdlib/dis.pyi b/mypy/typeshed/stdlib/dis.pyi index 0ad928934671b..984f932e33115 100644 --- a/mypy/typeshed/stdlib/dis.pyi +++ b/mypy/typeshed/stdlib/dis.pyi @@ -2,7 +2,7 @@ import sys import types from collections.abc import Callable, Iterator from opcode import * # `dis` re-exports it as a part of public API -from typing import IO, Any, Final, NamedTuple, overload +from typing import IO, Any, Final, NamedTuple, TypeAlias, overload from typing_extensions import Self, deprecated, disjoint_base __all__ = [ @@ -41,7 +41,7 @@ else: # Strictly this should not have to include Callable, but mypy doesn't use FunctionType # for functions (python/mypy#3171) -_HaveCodeType = types.MethodType | types.FunctionType | types.CodeType | type | Callable[..., Any] +_HaveCodeType: TypeAlias = types.MethodType | types.FunctionType | types.CodeType | type | Callable[..., Any] if sys.version_info >= (3, 11): class Positions(NamedTuple): diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index db9c228f5f28e..37783254c70fa 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, TypeAlias, overload, type_check_only +from typing import IO, Any, AnyStr, Generic, Literal, Protocol, TypeAlias, overload, type_check_only from typing_extensions import Self, deprecated __all__ = [ @@ -74,7 +74,7 @@ def fileno() -> int: ... def isfirstline() -> bool: ... def isstdin() -> bool: ... -class FileInput(Iterator[AnyStr]): +class FileInput(Generic[AnyStr]): # encoding and errors are added @overload def __init__( diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index 1bd2b9dee325b..c3110ce28d8ea 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -195,8 +195,8 @@ if sys.version_info >= (3, 14): modulesbyfile: dict[str, Any] -_GetMembersPredicateTypeGuard = Callable[[Any], TypeGuard[_T]] -_GetMembersPredicateTypeIs = Callable[[Any], TypeIs[_T]] +_GetMembersPredicateTypeGuard: TypeAlias = Callable[[Any], TypeGuard[_T]] +_GetMembersPredicateTypeIs: TypeAlias = Callable[[Any], TypeIs[_T]] _GetMembersPredicate: TypeAlias = Callable[[Any], bool] _GetMembersReturn: TypeAlias = list[tuple[str, _T]] diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index fd7daf11e8086..d26a4e1da21e4 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -23,12 +23,12 @@ _T10 = TypeVar("_T10") _Step: TypeAlias = SupportsFloat | SupportsInt | SupportsIndex | SupportsComplex -_Predicate = Callable[[_T], object] +_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 @@ -40,13 +40,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 @@ -57,7 +57,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 @@ -67,7 +67,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: ... @@ -77,25 +77,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 @@ -105,7 +105,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 @@ -115,13 +115,13 @@ 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: ... @@ -129,7 +129,7 @@ class takewhile(Iterator[_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]]: ... @@ -209,7 +209,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 @@ -296,7 +296,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 @@ -312,7 +312,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 @@ -328,7 +328,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 @@ -344,14 +344,14 @@ class combinations_with_replacement(Iterator[_T_co]): def __next__(self) -> _T_co: ... @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/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi index 40639e8678348..0f1d4e87b0dcb 100644 --- a/mypy/typeshed/stdlib/multiprocessing/managers.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/managers.pyi @@ -1,3 +1,4 @@ +import builtins import queue import sys import threading @@ -359,9 +360,9 @@ class SyncManager(BaseManager): @overload def dict(self, iterable: Iterable[tuple[str, _VT]], /, **kwargs: _VT) -> DictProxy[str, _VT]: ... @overload - def dict(self, iterable: Iterable[list[str]], /) -> DictProxy[str, str]: ... + def dict(self, iterable: Iterable[builtins.list[str]], /) -> DictProxy[str, str]: ... @overload - def dict(self, iterable: Iterable[list[bytes]], /) -> DictProxy[bytes, bytes]: ... + def dict(self, iterable: Iterable[builtins.list[bytes]], /) -> DictProxy[bytes, bytes]: ... # Overloads are copied from builtins.list.__init__ @overload diff --git a/mypy/typeshed/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi index f276372d09039..5642e50d0e768 100644 --- a/mypy/typeshed/stdlib/multiprocessing/pool.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/pool.pyi @@ -1,5 +1,5 @@ -from collections.abc import Callable, Iterable, Iterator, Mapping -from multiprocessing.context import DefaultContext, Process +from collections.abc import Callable, Iterable, Mapping +from multiprocessing.context import DefaultContext, Process as _Process from types import GenericAlias, TracebackType from typing import Any, Final, Generic, TypeVar from typing_extensions import Self @@ -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: ... @@ -50,7 +50,7 @@ class Pool: context: Any | None = None, ) -> None: ... @staticmethod - def Process(ctx: DefaultContext, *args: Any, **kwds: Any) -> Process: ... + def Process(ctx: DefaultContext, *args: Any, **kwds: Any) -> _Process: ... def apply(self, func: Callable[..., _T], args: Iterable[Any] = (), kwds: Mapping[str, Any] = {}) -> _T: ... def apply_async( self, diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 726e9702fb16b..00c155956fb01 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -940,7 +940,7 @@ In the future, this property will contain the last metadata change time.""") # At runtime it inherits from ABC and is not a Protocol, but it will be # on the allowlist for use as a Protocol starting in 3.14. @runtime_checkable -class PathLike(ABC, Protocol[AnyStr_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] +class PathLike(ABC, Protocol[AnyStr_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-protocol] __slots__ = () @abstractmethod def __fspath__(self) -> AnyStr_co: ... diff --git a/mypy/typeshed/stdlib/platform.pyi b/mypy/typeshed/stdlib/platform.pyi index 7d837436ef794..07100d3bd592d 100644 --- a/mypy/typeshed/stdlib/platform.pyi +++ b/mypy/typeshed/stdlib/platform.pyi @@ -44,7 +44,7 @@ if sys.version_info >= (3, 12): def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self: ... @property - def processor(self) -> str: ... + def processor(self) -> str: ... # ty:ignore[invalid-named-tuple-override] else: @disjoint_base @@ -52,7 +52,7 @@ else: __match_args__ = ("system", "node", "release", "version", "machine") # pyright: ignore[reportAssignmentType] def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self: ... @property - def processor(self) -> str: ... + def processor(self) -> str: ... # ty:ignore[invalid-named-tuple-override] def uname() -> uname_result: ... def system() -> str: ... diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index 87e2bd353730e..ed2873726ff1a 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -137,7 +137,7 @@ from _typeshed import ReadableBuffer, Unused, WriteableBuffer from collections.abc import Iterable from enum import IntEnum, IntFlag from io import BufferedReader, BufferedRWPair, BufferedWriter, IOBase, RawIOBase, TextIOWrapper -from typing import Any, Final, Literal, Protocol, SupportsIndex, overload, type_check_only +from typing import Any, Final, Literal, Protocol, SupportsIndex, TypeAlias, overload, type_check_only from typing_extensions import Self __all__ = [ @@ -1576,6 +1576,11 @@ def create_server( ) -> socket: ... # The 5th tuple item is the socket address, for IP4, IP6, or IP6 if Python is compiled with --disable-ipv6, respectively. +_GetAddrInfoResult: TypeAlias = list[ + tuple[Literal[AddressFamily.AF_INET], SocketKind, int, str, tuple[str, int]] + | tuple[Literal[AddressFamily.AF_INET6], SocketKind, int, str, tuple[str, int, int, int] | tuple[int, bytes]] +] + def getaddrinfo( host: bytes | str | None, port: bytes | str | int | None, family: int = 0, type: int = 0, proto: int = 0, flags: int = 0 -) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]]: ... +) -> _GetAddrInfoResult: ... diff --git a/mypy/typeshed/stdlib/sqlite3/__init__.pyi b/mypy/typeshed/stdlib/sqlite3/__init__.pyi index 7bf020558199e..80a02079dd054 100644 --- a/mypy/typeshed/stdlib/sqlite3/__init__.pyi +++ b/mypy/typeshed/stdlib/sqlite3/__init__.pyi @@ -269,28 +269,39 @@ class OperationalError(DatabaseError): ... class ProgrammingError(DatabaseError): ... class Warning(Exception): ... +_DataError: TypeAlias = DataError +_DatabaseError: TypeAlias = DatabaseError +_Error: TypeAlias = Error +_IntegrityError: TypeAlias = IntegrityError +_InterfaceError: TypeAlias = InterfaceError +_InternalError: TypeAlias = InternalError +_NotSupportedError: TypeAlias = NotSupportedError +_OperationalError: TypeAlias = OperationalError +_ProgrammingError: TypeAlias = ProgrammingError +_Warning: TypeAlias = Warning + @disjoint_base class Connection: @property - def DataError(self) -> type[DataError]: ... + def DataError(self) -> type[_DataError]: ... @property - def DatabaseError(self) -> type[DatabaseError]: ... + def DatabaseError(self) -> type[_DatabaseError]: ... @property - def Error(self) -> type[Error]: ... + def Error(self) -> type[_Error]: ... @property - def IntegrityError(self) -> type[IntegrityError]: ... + def IntegrityError(self) -> type[_IntegrityError]: ... @property - def InterfaceError(self) -> type[InterfaceError]: ... + def InterfaceError(self) -> type[_InterfaceError]: ... @property - def InternalError(self) -> type[InternalError]: ... + def InternalError(self) -> type[_InternalError]: ... @property - def NotSupportedError(self) -> type[NotSupportedError]: ... + def NotSupportedError(self) -> type[_NotSupportedError]: ... @property - def OperationalError(self) -> type[OperationalError]: ... + def OperationalError(self) -> type[_OperationalError]: ... @property - def ProgrammingError(self) -> type[ProgrammingError]: ... + def ProgrammingError(self) -> type[_ProgrammingError]: ... @property - def Warning(self) -> type[Warning]: ... + def Warning(self) -> type[_Warning]: ... @property def in_transaction(self) -> bool: ... isolation_level: _IsolationLevel @@ -426,7 +437,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 590642d99607d..8d71e47639592 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -262,8 +262,18 @@ class Purpose(_ASN1Object, enum.Enum): # because this is an enum, the inherited __new__ is replaced at runtime with # Enum.__new__. def __new__(cls, value: object) -> Self: ... - SERVER_AUTH = (129, "serverAuth", "TLS Web Server Authentication", "1.3.6.1.5.5.7.3.2") # pyright: ignore[reportCallIssue] - CLIENT_AUTH = (130, "clientAuth", "TLS Web Client Authentication", "1.3.6.1.5.5.7.3.1") # pyright: ignore[reportCallIssue] + SERVER_AUTH = ( # ty:ignore[invalid-assignment] + 129, + "serverAuth", + "TLS Web Server Authentication", + "1.3.6.1.5.5.7.3.2", + ) # pyright: ignore[reportCallIssue] + CLIENT_AUTH = ( # ty:ignore[invalid-assignment] + 130, + "clientAuth", + "TLS Web Client Authentication", + "1.3.6.1.5.5.7.3.1", + ) # pyright: ignore[reportCallIssue] class SSLSocket(socket.socket): context: SSLContext diff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi index 9b5344b326cec..ac53089b8d82c 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -1,15 +1,15 @@ import sys from _typeshed import structseq -from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, TypeAlias, Union, final, type_check_only +from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, TypeAlias, final, type_check_only _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/types.pyi b/mypy/typeshed/stdlib/types.pyi index 68b6b3fbe41d7..328bb7552538c 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -268,7 +268,7 @@ class CodeType: __replace__ = replace @final -class MappingProxyType(Mapping[_KT_co, _VT_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments] +class MappingProxyType(Mapping[_KT_co, _VT_co]): # type: ignore[type-var] # pyright: ignore[reportInvalidTypeArguments] # ty:ignore[invalid-generic-class] __hash__: ClassVar[None] # type: ignore[assignment] def __new__(cls, mapping: SupportsKeysAndGetItem[_KT_co, _VT_co]) -> Self: ... def __getitem__(self, key: _KT_co, /) -> _VT_co: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 811a77df84b76..8c1fb9d28d7c0 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -663,14 +663,17 @@ class AsyncGenerator(AsyncIterator[_YieldT_co], Protocol[_YieldT_co, _SendT_cont 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: ... @@ -1060,13 +1063,13 @@ class NamedTuple(tuple[Any, ...]): @final @classmethod - def _make(cls, iterable: Iterable[Any]) -> typing_extensions.Self: ... + def _make(cls, iterable: Iterable[Any]) -> typing_extensions.Self: ... # ty:ignore[invalid-type-form] @final def _asdict(self) -> dict[str, Any]: ... @final - def _replace(self, **kwargs: Any) -> typing_extensions.Self: ... + def _replace(self, **kwargs: Any) -> typing_extensions.Self: ... # ty:ignore[invalid-type-form] if sys.version_info >= (3, 13): - def __replace__(self, **kwargs: Any) -> typing_extensions.Self: ... + def __replace__(self, **kwargs: Any) -> typing_extensions.Self: ... # ty:ignore[invalid-type-form] # Internal mypy fallback type for all typed dicts (does not exist at runtime) # N.B. Keep this mostly in sync with typing_extensions._TypedDict/mypy_extensions._TypedDict diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index 80341175e6e14..5a8848e9151d8 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -356,9 +356,9 @@ else: def __init__(self, typename: str, fields: None = None, **kwargs: Any) -> None: ... @classmethod - def _make(cls, iterable: Iterable[Any]) -> Self: ... + def _make(cls, iterable: Iterable[Any]) -> Self: ... # ty:ignore[invalid-type-form] def _asdict(self) -> dict[str, Any]: ... - def _replace(self, **kwargs: Any) -> Self: ... + def _replace(self, **kwargs: Any) -> Self: ... # ty:ignore[invalid-type-form] class NewType: def __init__(self, name: str, tp: AnnotationForm) -> None: ... @@ -389,7 +389,7 @@ else: # At runtime it inherits from ABC and is not a Protocol, but it is on the # allowlist for use as a Protocol. @runtime_checkable - class Buffer(Protocol, abc.ABC): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] + class Buffer(Protocol, abc.ABC): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # ty:ignore[invalid-protocol] # Not actually a Protocol at runtime; see # https://github.com/python/typeshed/issues/10224 for why we're defining it this way def __buffer__(self, flags: int, /) -> memoryview: ... From 4d12f3cc7e2d3f1a3c913f64e560b0b5e40b07c6 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Mon, 18 May 2026 17:33:09 +0200 Subject: [PATCH 03/12] Adjust stubs to fix mypy lookup error due to circular dependencies in stubs --- mypy/typeshed/stdlib/__future__.pyi | 2 +- mypy/typeshed/stdlib/dis.pyi | 4 ++-- mypy/typeshed/stdlib/inspect.pyi | 4 ++-- mypy/typeshed/stdlib/itertools.pyi | 2 +- mypy/typeshed/stdlib/time.pyi | 6 +++--- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/mypy/typeshed/stdlib/__future__.pyi b/mypy/typeshed/stdlib/__future__.pyi index aa445d22bd20d..a90cf1eddab76 100644 --- a/mypy/typeshed/stdlib/__future__.pyi +++ b/mypy/typeshed/stdlib/__future__.pyi @@ -1,4 +1,4 @@ -from typing import TypeAlias +from typing_extensions import TypeAlias _VersionInfo: TypeAlias = tuple[int, int, int, str, int] diff --git a/mypy/typeshed/stdlib/dis.pyi b/mypy/typeshed/stdlib/dis.pyi index 984f932e33115..0ad928934671b 100644 --- a/mypy/typeshed/stdlib/dis.pyi +++ b/mypy/typeshed/stdlib/dis.pyi @@ -2,7 +2,7 @@ import sys import types from collections.abc import Callable, Iterator from opcode import * # `dis` re-exports it as a part of public API -from typing import IO, Any, Final, NamedTuple, TypeAlias, overload +from typing import IO, Any, Final, NamedTuple, overload from typing_extensions import Self, deprecated, disjoint_base __all__ = [ @@ -41,7 +41,7 @@ else: # Strictly this should not have to include Callable, but mypy doesn't use FunctionType # for functions (python/mypy#3171) -_HaveCodeType: TypeAlias = types.MethodType | types.FunctionType | types.CodeType | type | Callable[..., Any] +_HaveCodeType = types.MethodType | types.FunctionType | types.CodeType | type | Callable[..., Any] if sys.version_info >= (3, 11): class Positions(NamedTuple): diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index c3110ce28d8ea..1bd2b9dee325b 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -195,8 +195,8 @@ if sys.version_info >= (3, 14): modulesbyfile: dict[str, Any] -_GetMembersPredicateTypeGuard: TypeAlias = Callable[[Any], TypeGuard[_T]] -_GetMembersPredicateTypeIs: TypeAlias = Callable[[Any], TypeIs[_T]] +_GetMembersPredicateTypeGuard = Callable[[Any], TypeGuard[_T]] +_GetMembersPredicateTypeIs = Callable[[Any], TypeIs[_T]] _GetMembersPredicate: TypeAlias = Callable[[Any], bool] _GetMembersReturn: TypeAlias = list[tuple[str, _T]] diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index d26a4e1da21e4..60e79bc2e4113 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -23,7 +23,7 @@ _T10 = TypeVar("_T10") _Step: TypeAlias = SupportsFloat | SupportsInt | SupportsIndex | SupportsComplex -_Predicate: TypeAlias = Callable[[_T], object] +_Predicate = 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 diff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi index ac53089b8d82c..9b5344b326cec 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -1,15 +1,15 @@ import sys from _typeshed import structseq -from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, TypeAlias, final, type_check_only +from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, TypeAlias, Union, final, type_check_only _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 bae07068597999bbd2814516ce85dbc6eb591f31 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 04/12] 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 22d330a089ef5..fa22f842de028 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, TypeAlias, TypeVar, overload, type_check_only +from typing import IO, Any, ClassVar, Final, Generic, NewType, NoReturn, Protocol, TypeAlias, TypeVar, overload, type_check_only from typing_extensions import Self, 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 1d9d77873bc0ee2325d34160b233585d3c212ac5 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 05/12] Remove use of LiteralString in builtins (#13743) --- mypy/typeshed/stdlib/builtins.pyi | 127 +----------------------------- 1 file changed, 1 insertion(+), 126 deletions(-) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 096d440ac38cd..e63b7421463b9 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -65,7 +65,7 @@ from typing import ( # noqa: Y022,UP035 ) # we can't import `Literal` from typing or mypy crashes: see #11247 -from typing_extensions import Literal, LiteralString, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023, UP035 +from typing_extensions import Literal, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023, UP035 if sys.version_info >= (3, 14): from _typeshed import AnnotateFunc @@ -489,20 +489,8 @@ 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: ... @@ -510,17 +498,9 @@ class str(Sequence[str]): 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: ... @@ -537,119 +517,38 @@ 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] if sys.version_info >= (3, 15): @@ -677,49 +576,25 @@ 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]: ... From a3b8b4b40fa3bb318bf5af63ba5afe7b4a117628 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 06/12] 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 242093e1ec799..92bb4e5f41706 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, TypeAlias, 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 e63b7421463b9..9ea382dd60a83 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -1368,7 +1368,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]: ... @@ -1634,7 +1634,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 @@ -1705,7 +1705,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 @@ -2021,7 +2021,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 @@ -2101,7 +2101,7 @@ def vars(object: type, /) -> types.MappingProxyType[str, Any]: ... def vars(object: Any = ..., /) -> dict[str, Any]: ... @disjoint_base -class zip(Generic[_T_co]): +class zip(Iterator[_T_co]): @overload def __new__(cls, *, strict: bool = False) -> zip[Any]: ... @overload diff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi index f8ab5f000a043..f3b4286a6b495 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi @@ -21,7 +21,7 @@ if sys.version_info >= (3, 12): from _csv import QUOTE_NOTNULL as QUOTE_NOTNULL, QUOTE_STRINGS as QUOTE_STRINGS from _csv import Reader, 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 @@ -69,7 +69,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 37783254c70fa..db9c228f5f28e 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, TypeAlias, overload, type_check_only +from typing import IO, Any, AnyStr, Literal, Protocol, TypeAlias, overload, type_check_only from typing_extensions import Self, deprecated __all__ = [ @@ -74,7 +74,7 @@ def fileno() -> int: ... def isfirstline() -> bool: ... def isstdin() -> bool: ... -class FileInput(Generic[AnyStr]): +class FileInput(Iterator[AnyStr]): # encoding and errors are added @overload def __init__( diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index 60e79bc2e4113..fd7daf11e8086 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -28,7 +28,7 @@ _Predicate = 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 @@ -40,13 +40,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 @@ -57,7 +57,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 @@ -67,7 +67,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: ... @@ -77,25 +77,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 @@ -105,7 +105,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 @@ -115,13 +115,13 @@ 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: ... @@ -129,7 +129,7 @@ class takewhile(Generic[_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]]: ... @@ -209,7 +209,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 @@ -296,7 +296,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 @@ -312,7 +312,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 @@ -328,7 +328,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 @@ -344,14 +344,14 @@ class combinations_with_replacement(Generic[_T_co]): def __next__(self) -> _T_co: ... @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 5642e50d0e768..203c5887ca7ee 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 as _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 80a02079dd054..d1065a509af52 100644 --- a/mypy/typeshed/stdlib/sqlite3/__init__.pyi +++ b/mypy/typeshed/stdlib/sqlite3/__init__.pyi @@ -437,7 +437,7 @@ class Connection: ) -> Literal[False]: ... @disjoint_base -class Cursor: +class Cursor(Iterator[Any]): arraysize: int @property def connection(self) -> Connection: ... From d7de3d649d864a1eb55c3b9de60689f3fc2dc068 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 07/12] 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 8c1fb9d28d7c0..82389ec261232 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -663,17 +663,14 @@ class AsyncGenerator(AsyncIterator[_YieldT_co], Protocol[_YieldT_co, _SendT_cont 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 11cd0978e92386e5ed6af94726aebda3ec3392a1 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Wed, 8 Apr 2026 00:01:44 +0100 Subject: [PATCH 08/12] Revert dict.__or__ typeshed change --- mypy/typeshed/stdlib/builtins.pyi | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 9ea382dd60a83..b27f328578118 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -1228,14 +1228,27 @@ class dict(MutableMapping[_KT, _VT]): __hash__: ClassVar[None] # type: ignore[assignment] def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... if sys.version_info >= (3, 15): + @overload + def __or__(self, value: dict[_KT, _VT] | frozendict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload def __or__(self, value: dict[_T1, _T2] | frozendict[_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]: ... @overload + def __ror__(self, value: frozendict[_KT, _VT], /) -> frozendict[_KT, _VT]: ... + @overload def __ror__(self, value: frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... else: + @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() @@ -1289,11 +1302,18 @@ if sys.version_info >= (3, 15): def __iter__(self) -> Iterator[_KT]: ... def __hash__(self) -> int: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + @overload + def __or__(self, value: dict[_KT, _VT] | frozendict[_KT, _VT], /) -> frozendict[_KT, _VT]: ... + @overload def __or__(self, value: dict[_T1, _T2] | frozendict[_T1, _T2], /) -> frozendict[_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]: ... @overload + def __ror__(self, value: frozendict[_KT, _VT], /) -> frozendict[_KT, _VT]: ... + @overload def __ror__(self, value: frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... @disjoint_base From b6ff10fe0c288e9c769002333b0e300c695b9fef Mon Sep 17 00:00:00 2001 From: hauntsaninja Date: Wed, 6 May 2026 19:49:41 -0700 Subject: [PATCH 09/12] Revert operator changes --- mypy/typeshed/stdlib/_operator.pyi | 58 ++++++++---------------------- 1 file changed, 14 insertions(+), 44 deletions(-) diff --git a/mypy/typeshed/stdlib/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi index 04dae79dcd52d..29a6d70572028 100644 --- a/mypy/typeshed/stdlib/_operator.pyi +++ b/mypy/typeshed/stdlib/_operator.pyi @@ -1,15 +1,5 @@ import sys -from _typeshed import ( - SupportsAdd, - SupportsGetItem, - SupportsMod, - SupportsMul, - SupportsRAdd, - SupportsRMod, - SupportsRMul, - SupportsRSub, - SupportsSub, -) +from _typeshed import SupportsGetItem 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, ParamSpec, Protocol, SupportsAbs, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only @@ -18,7 +8,6 @@ from typing_extensions import 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") @@ -69,43 +58,24 @@ 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: ... - -@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 add(a: Any, b: Any, /) -> Any: ... +def and_(a: Any, b: Any, /) -> Any: ... +def floordiv(a: Any, b: Any, /) -> Any: ... def index(a: SupportsIndex, /) -> int: ... def inv(a: _SupportsInversion[_T_co], /) -> _T_co: ... def invert(a: _SupportsInversion[_T_co], /) -> _T_co: ... -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 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 neg(a: _SupportsNeg[_T_co], /) -> _T_co: ... -def or_(a, b, /): ... +def or_(a: Any, b: Any, /) -> Any: ... def pos(a: _SupportsPos[_T_co], /) -> _T_co: ... -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 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 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: ... From 76e71e0fe2d2e5336067f8737b3404a1aba1d9bd 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 10/12] 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 b27f328578118..8497f9e2e1037 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -2107,7 +2107,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 6f080732c2ef2f2df23ebe2aecb53b201f4953a2 Mon Sep 17 00:00:00 2001 From: AlexWaygood Date: Mon, 1 May 2023 20:34:55 +0100 Subject: [PATCH 11/12] 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 | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/mypy/typeshed/stdlib/_ctypes.pyi b/mypy/typeshed/stdlib/_ctypes.pyi index d800ac5c20d03..1efb119263ef1 100644 --- a/mypy/typeshed/stdlib/_ctypes.pyi +++ b/mypy/typeshed/stdlib/_ctypes.pyi @@ -324,12 +324,7 @@ class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): @_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 db6c4e2033e3be8a1aa94b71ed921b62506a4a5a Mon Sep 17 00:00:00 2001 From: Shantanu Jain Date: Sun, 22 Feb 2026 20:37:48 -0800 Subject: [PATCH 12/12] 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 dd601675265cc..ee577621c720d 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, ParamSpec, Protocol, TypeAlias, TypeVar, overload, runtime_checkable, type_check_only -from typing_extensions import Self, deprecated +from typing_extensions import Self __all__ = [ "aclosing", @@ -84,12 +84,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]]: ... _AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]]) @@ -107,13 +101,6 @@ class _AsyncGeneratorContextManager( 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