From d3f10e404cf3eb1932c00b33d807f040630471bf Mon Sep 17 00:00:00 2001 From: mypybot <> Date: Sun, 15 Nov 2026 00:07:01 +0000 Subject: [PATCH 01/11] Sync typeshed Source commit: https://github.com/python/typeshed/commit/37e85d128ccf13a304d8302b25c98f587ac9d119 --- mypy/typeshed/stdlib/__future__.pyi | 2 +- mypy/typeshed/stdlib/_asyncio.pyi | 4 +- mypy/typeshed/stdlib/_ctypes.pyi | 7 +- mypy/typeshed/stdlib/_operator.pyi | 59 +++-- mypy/typeshed/stdlib/_typeshed/__init__.pyi | 16 +- mypy/typeshed/stdlib/_weakrefset.pyi | 4 +- mypy/typeshed/stdlib/argparse.pyi | 8 +- mypy/typeshed/stdlib/ast.pyi | 2 +- mypy/typeshed/stdlib/builtins.pyi | 228 +++++++++++++++--- mypy/typeshed/stdlib/cmath.pyi | 2 +- mypy/typeshed/stdlib/contextlib.pyi | 15 +- mypy/typeshed/stdlib/csv.pyi | 4 +- mypy/typeshed/stdlib/datetime.pyi | 213 ++++++++++++++-- mypy/typeshed/stdlib/dis.pyi | 4 +- mypy/typeshed/stdlib/fileinput.pyi | 6 +- mypy/typeshed/stdlib/functools.pyi | 2 +- mypy/typeshed/stdlib/inspect.pyi | 4 +- mypy/typeshed/stdlib/itertools.pyi | 40 +-- .../stdlib/multiprocessing/context.pyi | 6 +- .../stdlib/multiprocessing/managers.pyi | 8 +- mypy/typeshed/stdlib/multiprocessing/pool.pyi | 4 +- mypy/typeshed/stdlib/optparse.pyi | 2 +- mypy/typeshed/stdlib/pydoc.pyi | 18 +- mypy/typeshed/stdlib/re.pyi | 2 + mypy/typeshed/stdlib/sqlite3/__init__.pyi | 2 +- mypy/typeshed/stdlib/time.pyi | 6 +- mypy/typeshed/stdlib/typing.pyi | 64 ++++- 27 files changed, 577 insertions(+), 155 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 386a96f38abdc..641c152d985b7 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: ... diff --git a/mypy/typeshed/stdlib/_ctypes.pyi b/mypy/typeshed/stdlib/_ctypes.pyi index 45cf0e9bad57e..83ac60fd0d42d 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/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi index ff419842ebfc6..565bb41697f1f 100644 --- a/mypy/typeshed/stdlib/_operator.pyi +++ b/mypy/typeshed/stdlib/_operator.pyi @@ -1,5 +1,16 @@ import sys -from _typeshed import ReadableBuffer, SupportsGetItem +from _typeshed import ( + ReadableBuffer, + 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, ParamSpec, Protocol, SupportsAbs, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only @@ -8,6 +19,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 +70,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/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index fa6ef8150e3a5..3eaf8df964934 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -59,12 +59,11 @@ Unused: TypeAlias = object # stable MaybeNone: TypeAlias = Any # stable # typeshed-internal type aliases to facilitate transition from -# `float` to either `float | int` or `float` (and similar for `complex`). -# When you encounter one of these type aliases, you are encouraged to -# replace them with the correct type. Please don't use them outside typeshed. +# `float` to either `float | int` or `float`. When you encounter this type +# alias, you are encouraged to replace it with the correct type. Please don't +# use it outside typeshed. # See https://github.com/python/typeshed/issues/16059 for details. FloatInt: TypeAlias = float | int -ComplexInt: TypeAlias = complex | float | int # Used to mark arguments that default to a sentinel value. This prevents # stubtest from complaining about the default value not matching. @@ -146,6 +145,15 @@ class SupportsDivMod(Protocol[_T_contra, _T_co]): class SupportsRDivMod(Protocol[_T_contra, _T_co]): def __rdivmod__(self, other: _T_contra, /) -> _T_co: ... +class SupportsRAnd(Protocol[_T_contra, _T_co]): + def __rand__(self, other: _T_contra, /) -> _T_co: ... + +class SupportsROr(Protocol[_T_contra, _T_co]): + def __ror__(self, other: _T_contra, /) -> _T_co: ... + +class SupportsRXor(Protocol[_T_contra, _T_co]): + def __rxor__(self, other: _T_contra, /) -> _T_co: ... + # This protocol is generic over the iterator type, while Iterable is # generic over the type that is iterated over. class SupportsIter(Protocol[_T_co]): diff --git a/mypy/typeshed/stdlib/_weakrefset.pyi b/mypy/typeshed/stdlib/_weakrefset.pyi index 82ffa4463f488..b2d0bbadbba78 100644 --- a/mypy/typeshed/stdlib/_weakrefset.pyi +++ b/mypy/typeshed/stdlib/_weakrefset.pyi @@ -27,11 +27,11 @@ class WeakSet(MutableSet[_T]): def difference(self, other: Iterable[_T]) -> Self: ... def __sub__(self, other: Iterable[Any]) -> Self: ... def difference_update(self, other: Iterable[Any]) -> None: ... - def __isub__(self, other: Iterable[Any]) -> Self: ... + def __isub__(self, other: Iterable[Any]) -> Self: ... # type: ignore[override] def intersection(self, other: Iterable[_T]) -> Self: ... def __and__(self, other: Iterable[Any]) -> Self: ... def intersection_update(self, other: Iterable[Any]) -> None: ... - def __iand__(self, other: Iterable[Any]) -> Self: ... + def __iand__(self, other: Iterable[Any]) -> Self: ... # type: ignore[override] def issubset(self, other: Iterable[_T]) -> bool: ... def __le__(self, other: Iterable[_T]) -> bool: ... def __lt__(self, other: Iterable[_T]) -> bool: ... diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index 2db7b8575744c..da8141e235e00 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, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing import IO, Any, ClassVar, Final, Generic, Protocol, TypeAlias, TypeVar, overload, type_check_only from typing_extensions import Never, 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/ast.pyi b/mypy/typeshed/stdlib/ast.pyi index f84c93e7953e5..000f84093604d 100644 --- a/mypy/typeshed/stdlib/ast.pyi +++ b/mypy/typeshed/stdlib/ast.pyi @@ -1711,7 +1711,7 @@ else: if sys.version_info < (3, 14): @deprecated("Removed in Python 3.14. Use `ast.Constant` instead.") class Num(Constant, metaclass=_ABC): - def __new__(cls, n: complex, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] + def __new__(cls, n: complex | float | int, **kwargs: Unpack[_Attributes]) -> Constant: ... # type: ignore[misc] # pyright: ignore[reportInconsistentConstructor] @deprecated("Removed in Python 3.14. Use `ast.Constant` instead.") class Str(Constant, metaclass=_ABC): diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index e5890b5025ef1..1442f0536f3bd 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -25,9 +25,13 @@ from _typeshed import ( SupportsLenAndGetItem, SupportsNext, SupportsRAdd, + SupportsRAnd, SupportsRDivMod, SupportsRichComparison, SupportsRichComparisonT, + SupportsROr, + SupportsRSub, + SupportsRXor, SupportsWrite, ) from collections.abc import Awaitable, Callable, Hashable, Iterable, Iterator, MutableSet, Set as AbstractSet, Sized @@ -66,7 +70,7 @@ from typing import ( # noqa: Y022 # ruff: ignore[deprecated-import] # we can't import `Literal` from typing or mypy crashes: see #11247 # ruff: ignore[deprecated-import] -from typing_extensions import Literal, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023 +from typing_extensions import Literal, LiteralString, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023 if sys.version_info >= (3, 14): from _typeshed import AnnotateFunc @@ -80,6 +84,7 @@ _KT = TypeVar("_KT") _VT = TypeVar("_VT") _VT_co = TypeVar("_VT_co", covariant=True) _S = TypeVar("_S") +_R = TypeVar("_R") _T1 = TypeVar("_T1") _T2 = TypeVar("_T2") _T3 = TypeVar("_T3") @@ -428,7 +433,7 @@ class float: def __format__(self, format_spec: str, /) -> str: ... if sys.version_info >= (3, 14): @classmethod - def from_number(cls, number: float | SupportsIndex | SupportsFloat, /) -> Self: ... + def from_number(cls, number: SupportsIndex | SupportsFloat, /) -> Self: ... @disjoint_base class complex: @@ -440,23 +445,23 @@ class complex: imag: complex | SupportsFloat | SupportsIndex = 0, ) -> Self: ... @overload - def __new__(cls, real: str | SupportsComplex | SupportsFloat | SupportsIndex | complex) -> Self: ... + def __new__(cls, real: str | SupportsComplex | SupportsFloat | SupportsIndex | complex | float | int) -> Self: ... @property def real(self) -> float: ... @property def imag(self) -> float: ... def conjugate(self) -> complex: ... - def __add__(self, value: complex, /) -> complex: ... - def __sub__(self, value: complex, /) -> complex: ... - def __mul__(self, value: complex, /) -> complex: ... - def __pow__(self, value: complex, mod: None = None, /) -> complex: ... - def __truediv__(self, value: complex, /) -> complex: ... - def __radd__(self, value: complex, /) -> complex: ... - def __rsub__(self, value: complex, /) -> complex: ... - def __rmul__(self, value: complex, /) -> complex: ... - def __rpow__(self, value: complex, mod: None = None, /) -> complex: ... - def __rtruediv__(self, value: complex, /) -> complex: ... + def __add__(self, value: complex | float | int, /) -> complex: ... + def __sub__(self, value: complex | float | int, /) -> complex: ... + def __mul__(self, value: complex | float | int, /) -> complex: ... + def __pow__(self, value: complex | float | int, mod: None = None, /) -> complex: ... + def __truediv__(self, value: complex | float | int, /) -> complex: ... + def __radd__(self, value: complex | float | int, /) -> complex: ... + def __rsub__(self, value: complex | float | int, /) -> complex: ... + def __rmul__(self, value: complex | float | int, /) -> complex: ... + def __rpow__(self, value: complex | float | int, mod: None = None, /) -> complex: ... + def __rtruediv__(self, value: complex | float | int, /) -> complex: ... def __eq__(self, value: object, /) -> bool: ... def __ne__(self, value: object, /) -> bool: ... def __neg__(self) -> complex: ... @@ -469,7 +474,7 @@ class complex: def __complex__(self) -> complex: ... if sys.version_info >= (3, 14): @classmethod - def from_number(cls, number: complex | SupportsComplex | SupportsFloat | SupportsIndex, /) -> Self: ... + def from_number(cls, number: SupportsComplex | SupportsFloat | SupportsIndex, /) -> Self: ... @type_check_only class _FormatMapMapping(Protocol): @@ -485,8 +490,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: ... @@ -494,9 +511,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: ... @@ -513,38 +538,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): @@ -572,26 +678,51 @@ 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: ... - def __mod__(self, value: Any, /) -> str: ... + + @overload + def __mod__(self: LiteralString, value: LiteralString | tuple[LiteralString, ...], /) -> LiteralString: ... + @overload + def __mod__(self, value: object, /) -> str: ... + def __rmod__(self, value: str, /) -> 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]: ... @@ -1294,6 +1425,8 @@ if sys.version_info >= (3, 15): def __getitem__(self, key: _KT, /) -> _VT_co: ... def __reversed__(self) -> Iterator[_KT]: ... def __iter__(self) -> Iterator[_KT]: ... + def __eq__(self, value: object, /) -> bool: ... + def __ne__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... def __or__(self, value: dict[_T1, _T2] | frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT_co | _T2]: ... @@ -1328,32 +1461,48 @@ class set(MutableSet[_T]): def __len__(self) -> int: ... def __contains__(self, o: object, /) -> bool: ... def __iter__(self) -> Iterator[_T]: ... - def __and__(self, value: AbstractSet[object], /) -> set[_T]: ... - def __iand__(self, value: AbstractSet[object], /) -> Self: ... + def __and__(self, value: set[Any] | frozenset[Any], /) -> set[_T]: ... # type: ignore[override] + @overload # type: ignore[misc] + def __iand__(self, value: set[Any] | frozenset[Any], /) -> Self: ... @overload + def __iand__(self, value: SupportsRAnd[set[_T], _R], /) -> _R: ... + + @overload # type: ignore[override] def __rand__(self, value: set[_S], /) -> set[_S]: ... @overload def __rand__(self, value: frozenset[_S], /) -> frozenset[_S]: ... - def __or__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... - def __ior__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] + def __or__(self, value: set[_S] | frozenset[_S], /) -> set[_T | _S]: ... # type: ignore[override] + @overload # type: ignore[override,misc] + def __ior__(self, value: set[_T] | frozenset[_T], /) -> Self: ... @overload + def __ior__(self, value: SupportsROr[set[_T], _R], /) -> _R: ... + + @overload # type: ignore[override] def __ror__(self, value: set[_S], /) -> set[_T | _S]: ... @overload def __ror__(self, value: frozenset[_S], /) -> frozenset[_T | _S]: ... - def __sub__(self, value: AbstractSet[object], /) -> set[_T]: ... - def __isub__(self, value: AbstractSet[object], /) -> Self: ... + def __sub__(self, value: set[Any] | frozenset[Any], /) -> set[_T]: ... # type: ignore[override] + @overload # type: ignore[misc] + def __isub__(self, value: set[Any] | frozenset[Any], /) -> Self: ... @overload + def __isub__(self, value: SupportsRSub[set[_T], _R], /) -> _R: ... + + @overload # type: ignore[override] def __rsub__(self, value: set[_S], /) -> set[_S]: ... @overload def __rsub__(self, value: frozenset[_S], /) -> frozenset[_S]: ... def __xor__(self, value: set[_S] | frozenset[_S], /) -> set[_T | _S]: ... # type: ignore[override] - def __ixor__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] + + @overload # type: ignore[override,misc] + def __ixor__(self, value: set[_T] | frozenset[_T], /) -> Self: ... + @overload + def __ixor__(self, value: SupportsRXor[set[_T], _R], /) -> _R: ... @overload # type: ignore[override] def __rxor__(self, value: set[_S], /) -> set[_T | _S]: ... @@ -1386,23 +1535,25 @@ class frozenset(AbstractSet[_T_co]): def __len__(self) -> int: ... def __contains__(self, o: object, /) -> bool: ... def __iter__(self) -> Iterator[_T_co]: ... - def __and__(self, value: AbstractSet[object], /) -> frozenset[_T_co]: ... + # The binary operators only support set and frozenset. For other operands, + # Python falls back to the operand's reflected method. + def __and__(self, value: set[Any] | frozenset[Any], /) -> frozenset[_T_co]: ... # type: ignore[override] - @overload + @overload # type: ignore[override] def __rand__(self, value: set[_S], /) -> set[_S]: ... @overload def __rand__(self, value: frozenset[_S], /) -> frozenset[_S]: ... - def __or__(self, value: AbstractSet[_S], /) -> frozenset[_T_co | _S]: ... + def __or__(self, value: set[_S] | frozenset[_S], /) -> frozenset[_T_co | _S]: ... # type: ignore[override] - @overload + @overload # type: ignore[override] def __ror__(self, value: set[_S], /) -> set[_T_co | _S]: ... @overload def __ror__(self, value: frozenset[_S], /) -> frozenset[_T_co | _S]: ... - def __sub__(self, value: AbstractSet[object], /) -> frozenset[_T_co]: ... + def __sub__(self, value: set[Any] | frozenset[Any], /) -> frozenset[_T_co]: ... # type: ignore[override] - @overload + @overload # type: ignore[override] def __rsub__(self, value: set[_S], /) -> set[_S]: ... @overload def __rsub__(self, value: frozenset[_S], /) -> frozenset[_S]: ... @@ -1423,7 +1574,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]: ... @@ -1474,6 +1625,7 @@ class property: fdel: Callable[[Any], None] | None = None, doc: str | None = None, ) -> None: ... + def __set_name__(self, owner: type, name: str, /) -> None: ... def getter(self, fget: Callable[[Any], Any], /) -> property: ... def setter(self, fset: Callable[[Any, Any], None], /) -> property: ... def deleter(self, fdel: Callable[[Any], None], /) -> property: ... @@ -1689,7 +1841,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 @@ -1760,7 +1912,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 @@ -2059,9 +2211,9 @@ def pow(base: float, exp: int, mod: None = None) -> float: ... # return type must be Any (same as complex base, complex exp), # as `float | complex` causes too many false-positive errors @overload -def pow(base: float, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> Any: ... +def pow(base: float, exp: complex | float | int | _SupportsSomeKindOfPow, mod: None = None) -> Any: ... @overload -def pow(base: complex, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> complex: ... +def pow(base: complex, exp: complex | float | int | _SupportsSomeKindOfPow, mod: None = None) -> complex: ... @overload def pow(base: _SupportsPow2[_E_contra, _T_co], exp: _E_contra, mod: None = None) -> _T_co: ... # type: ignore[overload-overlap] @overload @@ -2069,7 +2221,7 @@ def pow(base: _SupportsPow3NoneOnly[_E_contra, _T_co], exp: _E_contra, mod: None @overload def pow(base: _SupportsPow3[_E_contra, _M_contra, _T_co], exp: _E_contra, mod: _M_contra) -> _T_co: ... @overload -def pow(base: _SupportsSomeKindOfPow, exp: float, mod: None = None) -> Any: ... +def pow(base: _SupportsSomeKindOfPow, exp: float | int, mod: None = None) -> Any: ... @overload def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex: ... @@ -2080,7 +2232,7 @@ class _SupportsReversed(Protocol[_T_co]): def __reversed__(self) -> _T_co: ... @disjoint_base -class reversed(Iterator[_T_co]): +class reversed(Generic[_T_co]): @overload def __new__(cls, sequence: _SupportsReversed[_T], /) -> _T: ... # type: ignore[misc] @overload @@ -2146,7 +2298,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 @@ -2160,7 +2312,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 @@ -2221,7 +2373,7 @@ if sys.version_info >= (3, 15): locals: Mapping[str, object] | None = None, fromlist: Sequence[str] | None = (), level: int = 0, - ) -> Any: ... + ) -> types.LazyImportType: ... def __build_class__(func: Callable[[], CellType | Any], name: str, /, *bases: Any, metaclass: Any = ..., **kwds: Any) -> Any: ... diff --git a/mypy/typeshed/stdlib/cmath.pyi b/mypy/typeshed/stdlib/cmath.pyi index 554eb54e2e4cc..4898b1c00232b 100644 --- a/mypy/typeshed/stdlib/cmath.pyi +++ b/mypy/typeshed/stdlib/cmath.pyi @@ -9,7 +9,7 @@ nanj: Final[complex] tau: Final[float] _F: TypeAlias = SupportsFloat | SupportsIndex -_C: TypeAlias = SupportsFloat | SupportsComplex | SupportsIndex | complex +_C: TypeAlias = SupportsComplex | SupportsFloat | SupportsIndex | complex | float | int def acos(z: _C, /) -> complex: ... def acosh(z: _C, /) -> complex: ... diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index 461965f3868d6..c286514af2292 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", @@ -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 18b36b20160f4..751e85566f88e 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 @@ -73,7 +73,7 @@ class excel(Dialect): ... class excel_tab(excel): ... class unix_dialect(Dialect): ... -class DictReader(Iterator[dict[_T | Any, str | Any]], Generic[_T]): +class DictReader(Generic[_T]): fieldnames: Sequence[_T] | None restkey: _T | None restval: str | Any | None diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index 0a21f72b09de4..5272e3850fe73 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -1,7 +1,7 @@ import sys from abc import abstractmethod from time import struct_time -from typing import ClassVar, Final, SupportsIndex, TypeAlias, final, overload, type_check_only +from typing import Any, ClassVar, Final, Generic, SupportsIndex, TypeAlias, TypeVar, final, overload, type_check_only from typing_extensions import CapsuleType, Never, Self, deprecated, disjoint_base if sys.version_info >= (3, 11): @@ -266,10 +266,14 @@ class timedelta: def __bool__(self) -> bool: ... def __hash__(self) -> int: ... +_TzInfoT = TypeVar("_TzInfoT", bound=tzinfo | None, default=Any) + @disjoint_base -class datetime(date): - min: ClassVar[datetime] - max: ClassVar[datetime] +class datetime(date, Generic[_TzInfoT]): + min: ClassVar[datetime[None]] + max: ClassVar[datetime[None]] + + @overload def __new__( cls, year: SupportsIndex, @@ -279,10 +283,39 @@ class datetime(date): minute: SupportsIndex = 0, second: SupportsIndex = 0, microsecond: SupportsIndex = 0, - tzinfo: _TzInfo | None = None, + tzinfo: None = None, *, fold: int = 0, - ) -> Self: ... + ) -> datetime[None]: ... + @overload + def __new__( + cls, + year: SupportsIndex, + month: SupportsIndex, + day: SupportsIndex, + hour: SupportsIndex = 0, + minute: SupportsIndex = 0, + second: SupportsIndex = 0, + microsecond: SupportsIndex = 0, + *, + tzinfo: _TzInfo, + fold: int = 0, + ) -> datetime[_TzInfo]: ... + @overload + def __new__( + cls, + year: SupportsIndex, + month: SupportsIndex, + day: SupportsIndex, + hour: SupportsIndex, + minute: SupportsIndex, + second: SupportsIndex, + microsecond: SupportsIndex, + tzinfo: _TzInfo, + *, + fold: int = 0, + ) -> datetime[_TzInfo]: ... + @property def hour(self) -> int: ... @property @@ -292,32 +325,64 @@ class datetime(date): @property def microsecond(self) -> int: ... @property - def tzinfo(self) -> _TzInfo | None: ... + def tzinfo(self) -> _TzInfoT: ... @property def fold(self) -> int: ... # On <3.12, the name of the first parameter in the pure-Python implementation # didn't match the name in the C implementation, # meaning it is only *safe* to pass it as a keyword argument on 3.12+ if sys.version_info >= (3, 12): + @overload # type: ignore[override] + @classmethod + def fromtimestamp(cls, timestamp: float, tz: None = None) -> datetime[None]: ... + @overload @classmethod - def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None = None) -> Self: ... + def fromtimestamp(cls, timestamp: float, tz: _TzInfo) -> datetime[_TzInfo]: ... + @overload + @classmethod + def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None) -> datetime[_TzInfo] | datetime[None]: ... + else: + @overload # type: ignore[override] + @classmethod + def fromtimestamp(cls, timestamp: float, /, tz: None = None) -> datetime[None]: ... + @overload + @classmethod + def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo) -> datetime[_TzInfo]: ... + @overload + @classmethod + def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | None) -> datetime[_TzInfo] | datetime[None]: ... + + # fromisoformat returns Self, but we can't specialize "Self" + if sys.version_info >= (3, 15): + @classmethod + def fromisoformat(cls, string: str, /) -> datetime[_TzInfo] | datetime[None]: ... # type: ignore[override] else: @classmethod - def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | None = None) -> Self: ... + def fromisoformat(cls, date_string: str, /) -> datetime[_TzInfo] | datetime[None]: ... # type: ignore[override] @classmethod - @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .fromtimestamp(datetime.timezone.utc)") - def utcfromtimestamp(cls, t: float, /) -> Self: ... + @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .fromtimestamp(datetime.UTC)") + def utcfromtimestamp(cls, t: float, /) -> datetime[None]: ... + + @overload @classmethod - def now(cls, tz: _TzInfo | None = None) -> Self: ... + def now(cls, tz: None = None) -> datetime[None]: ... + @overload @classmethod - @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.timezone.utc)") - def utcnow(cls) -> Self: ... + def now(cls, tz: _TzInfo) -> datetime[_TzInfo]: ... + @classmethod - def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo | None = ...) -> Self: ... - if sys.version_info >= (3, 15): - @classmethod - def fromisoformat(cls, string: str, /) -> Self: ... + def today(cls) -> datetime[None]: ... # type: ignore[override] + @classmethod + @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.UTC)") + def utcnow(cls) -> datetime[None]: ... + + @overload + @classmethod + def combine(cls, date: _Date, time: _Time, tzinfo: None = None) -> datetime[None]: ... + @overload + @classmethod + def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo) -> datetime[_TzInfo]: ... def timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... @@ -340,6 +405,7 @@ class datetime(date): fold: int = ..., ) -> Self: ... + @overload def replace( self, year: SupportsIndex = ..., @@ -349,11 +415,67 @@ class datetime(date): minute: SupportsIndex = ..., second: SupportsIndex = ..., microsecond: SupportsIndex = ..., - tzinfo: _TzInfo | None = ..., *, fold: int = ..., ) -> Self: ... - def astimezone(self, tz: _TzInfo | None = None) -> Self: ... + @overload + def replace( + self, + year: SupportsIndex, + month: SupportsIndex, + day: SupportsIndex, + hour: SupportsIndex, + minute: SupportsIndex, + second: SupportsIndex, + microsecond: SupportsIndex, + tzinfo: _TzInfo, + *, + fold: int = ..., + ) -> datetime[_TzInfo]: ... + @overload + def replace( + self, + year: SupportsIndex = ..., + month: SupportsIndex = ..., + day: SupportsIndex = ..., + hour: SupportsIndex = ..., + minute: SupportsIndex = ..., + second: SupportsIndex = ..., + microsecond: SupportsIndex = ..., + *, + tzinfo: _TzInfo, + fold: int = ..., + ) -> datetime[_TzInfo]: ... + @overload + def replace( + self, + year: SupportsIndex, + month: SupportsIndex, + day: SupportsIndex, + hour: SupportsIndex, + minute: SupportsIndex, + second: SupportsIndex, + microsecond: SupportsIndex, + tzinfo: None, + *, + fold: int = ..., + ) -> datetime[None]: ... + @overload + def replace( + self, + year: SupportsIndex = ..., + month: SupportsIndex = ..., + day: SupportsIndex = ..., + hour: SupportsIndex = ..., + minute: SupportsIndex = ..., + second: SupportsIndex = ..., + microsecond: SupportsIndex = ..., + *, + tzinfo: None, + fold: int = ..., + ) -> datetime[None]: ... + + def astimezone(self, tz: _TzInfo | None = None) -> datetime[_TzInfo]: ... def isoformat(self, sep: str = "T", timespec: str = "auto") -> str: ... if sys.version_info >= (3, 15): @@ -366,15 +488,56 @@ class datetime(date): def utcoffset(self) -> timedelta | None: ... def tzname(self) -> str | None: ... def dst(self) -> timedelta | None: ... - def __le__(self, value: datetime, /) -> bool: ... # type: ignore[override] - def __lt__(self, value: datetime, /) -> bool: ... # type: ignore[override] - def __ge__(self, value: datetime, /) -> bool: ... # type: ignore[override] - def __gt__(self, value: datetime, /) -> bool: ... # type: ignore[override] + + @overload # type: ignore[override] + def __le__( # type: ignore[overload-overlap] + self: datetime[_TzInfo] | datetime[_TzInfo | None], value: datetime[_TzInfo] | datetime[_TzInfo | None], / + ) -> bool: ... # type: ignore[misc] + @overload + def __le__(self: datetime[None] | datetime[_TzInfo | None], value: datetime[None] | datetime[_TzInfo | None], /) -> bool: ... # type: ignore[misc] + @overload + def __le__(self: datetime[Any], value: datetime[Any], /) -> Never: ... + + @overload # type: ignore[override] + def __lt__( # type: ignore[overload-overlap] + self: datetime[_TzInfo] | datetime[_TzInfo | None], value: datetime[_TzInfo] | datetime[_TzInfo | None], / + ) -> bool: ... # type: ignore[misc] + @overload + def __lt__(self: datetime[None] | datetime[_TzInfo | None], value: datetime[None] | datetime[_TzInfo | None], /) -> bool: ... # type: ignore[misc] + @overload + def __lt__(self: datetime[Any], value: datetime[Any], /) -> Never: ... + + @overload # type: ignore[override] + def __ge__( # type: ignore[overload-overlap] + self: datetime[_TzInfo] | datetime[_TzInfo | None], value: datetime[_TzInfo] | datetime[_TzInfo | None], / + ) -> bool: ... # type: ignore[misc] + @overload + def __ge__(self: datetime[None] | datetime[_TzInfo | None], value: datetime[None] | datetime[_TzInfo | None], /) -> bool: ... # type: ignore[misc] + @overload + def __ge__(self: datetime[Any], value: datetime[Any], /) -> Never: ... + + @overload # type: ignore[override] + def __gt__( # type: ignore[overload-overlap] + self: datetime[_TzInfo] | datetime[_TzInfo | None], value: datetime[_TzInfo] | datetime[_TzInfo | None], / + ) -> bool: ... # type: ignore[misc] + @overload + def __gt__(self: datetime[None] | datetime[_TzInfo | None], value: datetime[None] | datetime[_TzInfo | None], /) -> bool: ... # type: ignore[misc] + @overload + def __gt__(self: datetime[Any], value: datetime[Any], /) -> Never: ... + def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... @overload # type: ignore[override] - def __sub__(self, value: Self, /) -> timedelta: ... + def __sub__( # type: ignore[overload-overlap] + self: datetime[_TzInfo] | datetime[_TzInfo | None], value: datetime[_TzInfo] | datetime[_TzInfo | None], / + ) -> timedelta: ... + @overload + def __sub__( # type: ignore[overload-overlap] + self: datetime[None] | datetime[_TzInfo | None], value: datetime[None] | datetime[_TzInfo | None], / + ) -> timedelta: ... + @overload + def __sub__(self: datetime[Any], value: datetime[Any], /) -> Never: ... @overload def __sub__(self, value: timedelta, /) -> Self: ... 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/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index 42041befd9999..25e75b4f18f01 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -233,7 +233,7 @@ class _SingleDispatchCallable(Generic[_T]): registry: types.MappingProxyType[Any, Callable[..., _T]] def dispatch(self, cls: Any) -> Callable[..., _T]: ... - # @fun.register(complex) + # @fun.register(complex | float | int) # def _(arg, verbose=False): ... @overload def register(self, cls: _RegType, func: None = None) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index 410264820ece0..9bca21ab2dfd7 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/context.pyi b/mypy/typeshed/stdlib/multiprocessing/context.pyi index 925f364f1826c..e86fd71ade4d6 100644 --- a/mypy/typeshed/stdlib/multiprocessing/context.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/context.pyi @@ -175,7 +175,11 @@ class DefaultContext(BaseContext): else: def __init__(self, context: BaseContext) -> None: ... - def get_start_method(self, allow_none: bool = False) -> str: ... + @overload + def get_start_method(self, allow_none: Literal[False] = False) -> str: ... + @overload + def get_start_method(self, allow_none: bool) -> str | None: ... + def get_all_start_methods(self) -> list[str]: ... _default_context: DefaultContext diff --git a/mypy/typeshed/stdlib/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi index 0727f60f10809..6768f16832ed3 100644 --- a/mypy/typeshed/stdlib/multiprocessing/managers.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/managers.pyi @@ -180,11 +180,11 @@ if sys.version_info >= (3, 14): def __contains__(self, o: object, /) -> bool: ... def __iter__(self) -> Iterator[_T]: ... def __and__(self, value: AbstractSet[object], /) -> set[_T]: ... - def __iand__(self, value: AbstractSet[object], /) -> Self: ... + def __iand__(self, value: AbstractSet[object], /) -> Self: ... # type: ignore[override] def __or__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... def __ior__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] def __sub__(self, value: AbstractSet[_T | None], /) -> set[_T]: ... - def __isub__(self, value: AbstractSet[object], /) -> Self: ... + def __isub__(self, value: AbstractSet[object], /) -> Self: ... # type: ignore[override] def __xor__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... def __ixor__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] def __le__(self, value: AbstractSet[object], /) -> bool: ... @@ -192,9 +192,9 @@ if sys.version_info >= (3, 14): def __ge__(self, value: AbstractSet[object], /) -> bool: ... def __gt__(self, value: AbstractSet[object], /) -> bool: ... def __eq__(self, value: object, /) -> bool: ... - def __rand__(self, value: AbstractSet[object], /) -> set[_T]: ... + def __rand__(self, value: AbstractSet[object], /) -> set[_T]: ... # type: ignore[override] def __ror__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... # type: ignore[misc] - def __rsub__(self, value: AbstractSet[_T], /) -> set[_T]: ... + def __rsub__(self, value: AbstractSet[_T], /) -> set[_T]: ... # type: ignore[override] def __rxor__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... # type: ignore[override,misc] def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi index 203c5887ca7ee..5642e50d0e768 100644 --- a/mypy/typeshed/stdlib/multiprocessing/pool.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/pool.pyi @@ -1,4 +1,4 @@ -from collections.abc import Callable, Iterable, Iterator, Mapping +from collections.abc import Callable, Iterable, Mapping from multiprocessing.context import DefaultContext, Process 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(Iterator[_T]): +class IMapIterator(Generic[_T]): def __init__(self, pool: Pool) -> None: ... def __iter__(self) -> Self: ... def next(self, timeout: float | None = None) -> _T: ... diff --git a/mypy/typeshed/stdlib/optparse.pyi b/mypy/typeshed/stdlib/optparse.pyi index 35dfc54a9d498..710a51c19c41b 100644 --- a/mypy/typeshed/stdlib/optparse.pyi +++ b/mypy/typeshed/stdlib/optparse.pyi @@ -29,7 +29,7 @@ SUPPRESS_HELP: Final = "SUPPRESSHELP" SUPPRESS_USAGE: Final = "SUPPRESSUSAGE" # Can return complex, float, or int depending on the option's type -def check_builtin(option: Option, opt: str, value: str) -> complex: ... +def check_builtin(option: Option, opt: str, value: str) -> complex | float | int: ... def check_choice(option: Option, opt: str, value: str) -> str: ... class OptParseError(Exception): diff --git a/mypy/typeshed/stdlib/pydoc.pyi b/mypy/typeshed/stdlib/pydoc.pyi index dd9a365dff0bc..9943aaa5e0d89 100644 --- a/mypy/typeshed/stdlib/pydoc.pyi +++ b/mypy/typeshed/stdlib/pydoc.pyi @@ -82,11 +82,11 @@ class HTMLRepr(Repr): def __init__(self) -> None: ... def escape(self, text: str) -> str: ... def repr(self, object: object) -> str: ... - def repr1(self, x: object, level: complex) -> str: ... - def repr_string(self, x: str, level: complex) -> str: ... - def repr_str(self, x: str, level: complex) -> str: ... - def repr_instance(self, x: object, level: complex) -> str: ... - def repr_unicode(self, x: AnyStr, level: complex) -> str: ... + def repr1(self, x: object, level: int) -> str: ... + def repr_string(self, x: str, level: int) -> str: ... + def repr_str(self, x: str, level: int) -> str: ... + def repr_instance(self, x: object, level: int) -> str: ... + def repr_unicode(self, x: AnyStr, level: int) -> str: ... class HTMLDoc(Doc): _repr_instance: HTMLRepr @@ -190,10 +190,10 @@ class HTMLDoc(Doc): class TextRepr(Repr): def __init__(self) -> None: ... - def repr1(self, x: object, level: complex) -> str: ... - def repr_string(self, x: str, level: complex) -> str: ... - def repr_str(self, x: str, level: complex) -> str: ... - def repr_instance(self, x: object, level: complex) -> str: ... + def repr1(self, x: object, level: int) -> str: ... + def repr_string(self, x: str, level: int) -> str: ... + def repr_str(self, x: str, level: int) -> str: ... + def repr_instance(self, x: object, level: int) -> str: ... class TextDoc(Doc): _repr_instance: TextRepr diff --git a/mypy/typeshed/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi index 42eb751498c08..bbfa2b333c0f1 100644 --- a/mypy/typeshed/stdlib/re.pyi +++ b/mypy/typeshed/stdlib/re.pyi @@ -343,6 +343,8 @@ def subn( def escape(pattern: AnyStr) -> AnyStr: ... @overload def escape(pattern: ReadableBuffer) -> bytes: ... +@overload +def escape(pattern: str | ReadableBuffer) -> str | bytes: ... def purge() -> None: ... diff --git a/mypy/typeshed/stdlib/sqlite3/__init__.pyi b/mypy/typeshed/stdlib/sqlite3/__init__.pyi index d1065a509af52..80a02079dd054 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(Iterator[Any]): +class Cursor: arraysize: int @property def connection(self) -> Connection: ... 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/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 0ea21c5dd7f1e..0f25cf38be2f7 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -5,7 +5,18 @@ import collections # ruff: ignore[unused-import] # pyright: ignore[reportUnuse import sys import typing_extensions from _collections_abc import dict_items, dict_keys, dict_values -from _typeshed import IdentityFunction, ReadableBuffer, SupportsGetItem, SupportsGetItemViewable, SupportsKeysAndGetItem, Viewable +from _typeshed import ( + IdentityFunction, + ReadableBuffer, + SupportsGetItem, + SupportsGetItemViewable, + SupportsKeysAndGetItem, + SupportsRAnd, + SupportsROr, + SupportsRSub, + SupportsRXor, + Viewable, +) from abc import ABCMeta, abstractmethod from re import Match as Match, Pattern as Pattern from types import ( @@ -411,6 +422,7 @@ _FT = TypeVar("_FT", bound=Callable[..., Any] | type) # These type variables are used by the container types. _S = TypeVar("_S") +_R = TypeVar("_R") _KT = TypeVar("_KT") # Key type. _VT = TypeVar("_VT") # Value type. _T_co = TypeVar("_T_co", covariant=True) # Any type covariant containers. @@ -665,14 +677,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: ... @@ -737,11 +752,20 @@ class AbstractSet(Collection[_T_co]): def __lt__(self, other: AbstractSet[Any], /) -> bool: ... def __gt__(self, other: AbstractSet[Any], /) -> bool: ... def __ge__(self, other: AbstractSet[Any], /) -> bool: ... + # These annotations describe what all implementations support, including + # set and frozenset, which don't use the mixin methods. While the mixin + # methods accept any iterable, set and frozenset only accept set and + # frozenset. The forward methods still accept any AbstractSet, because + # if one operand doesn't support the other, Python falls back to the + # other operand's reflected method, which always returns an AbstractSet. def __and__(self, other: AbstractSet[Any], /) -> AbstractSet[_T_co]: ... def __or__(self, other: AbstractSet[_T], /) -> AbstractSet[_T_co | _T]: ... def __sub__(self, other: AbstractSet[Any], /) -> AbstractSet[_T_co]: ... def __xor__(self, other: AbstractSet[_T], /) -> AbstractSet[_T_co | _T]: ... - def __rxor__(self, other: Iterable[_T], /) -> AbstractSet[_T_co | _T]: ... + def __rand__(self, other: AbstractSet[_T], /) -> AbstractSet[_T]: ... + def __ror__(self, other: AbstractSet[_T], /) -> AbstractSet[_T_co | _T]: ... + def __rsub__(self, other: AbstractSet[_T], /) -> AbstractSet[_T]: ... + def __rxor__(self, other: AbstractSet[_T], /) -> AbstractSet[_T_co | _T]: ... def __eq__(self, other: object, /) -> bool: ... def isdisjoint(self, other: Iterable[Any], /) -> bool: ... @@ -754,10 +778,32 @@ class MutableSet(AbstractSet[_T]): def clear(self) -> None: ... def pop(self) -> _T: ... def remove(self, value: _T, /) -> None: ... - def __ior__(self, it: AbstractSet[_T], /) -> typing_extensions.Self: ... # type: ignore[override,misc] - def __iand__(self, it: AbstractSet[Any], /) -> typing_extensions.Self: ... - def __ixor__(self, it: AbstractSet[_T], /) -> typing_extensions.Self: ... # type: ignore[override,misc] - def __isub__(self, it: AbstractSet[Any], /) -> typing_extensions.Self: ... + + # These annotations describe what all implementations support, including + # set, which doesn't use the mixin methods. While the mixin methods accept + # any iterable and always modify the set in place, set only does so for + # set and frozenset arguments. For other arguments, Python falls back to + # the argument's reflected method and rebinds the target to its result, + # which might not even be a mutable set. + @overload # type: ignore[override,misc] + def __ior__(self, it: set[_T] | frozenset[_T], /) -> typing_extensions.Self: ... + @overload + def __ior__(self, it: SupportsROr[MutableSet[_T], _R], /) -> typing_extensions.Self | _R: ... + + @overload # type: ignore[misc] + def __iand__(self, it: set[Any] | frozenset[Any], /) -> typing_extensions.Self: ... + @overload + def __iand__(self, it: SupportsRAnd[MutableSet[_T], _R], /) -> typing_extensions.Self | _R: ... + + @overload # type: ignore[override,misc] + def __ixor__(self, it: set[_T] | frozenset[_T], /) -> typing_extensions.Self: ... + @overload + def __ixor__(self, it: SupportsRXor[MutableSet[_T], _R], /) -> typing_extensions.Self | _R: ... + + @overload # type: ignore[misc] + def __isub__(self, it: set[Any] | frozenset[Any], /) -> typing_extensions.Self: ... + @overload + def __isub__(self, it: SupportsRSub[MutableSet[_T], _R], /) -> typing_extensions.Self | _R: ... class MappingView(Sized): __slots__ = ("_mapping",) From 5cb904560e44b88854a4f58f1d4ccac2609200a9 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 02/11] 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 9bca21ab2dfd7..410264820ece0 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 2837f5d42b15d792f701f50db84b80380599f885 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Sat, 15 Feb 2025 20:11:06 +0100 Subject: [PATCH 03/11] 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 da8141e235e00..2db7b8575744c 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, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing import IO, Any, ClassVar, Final, Generic, NewType, Protocol, TypeAlias, TypeVar, overload, type_check_only from typing_extensions import Never, 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 f514cdaaaf00fc5b5df4e73385a0919cb4ef2545 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Mon, 26 Sep 2022 12:55:07 -0700 Subject: [PATCH 04/11] Remove use of LiteralString in builtins (#13743) --- mypy/typeshed/stdlib/builtins.pyi | 130 +----------------------------- 1 file changed, 2 insertions(+), 128 deletions(-) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 1442f0536f3bd..63563b2616b3e 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -70,7 +70,7 @@ from typing import ( # noqa: Y022 # ruff: ignore[deprecated-import] # we can't import `Literal` from typing or mypy crashes: see #11247 # ruff: ignore[deprecated-import] -from typing_extensions import Literal, LiteralString, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023 +from typing_extensions import Literal, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023 if sys.version_info >= (3, 14): from _typeshed import AnnotateFunc @@ -490,20 +490,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: ... @@ -511,17 +499,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: ... @@ -538,119 +518,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): @@ -678,51 +577,26 @@ 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: object, /) -> str: ... - + def __mod__(self, value: Any, /) -> str: ... def __rmod__(self, value: str, /) -> 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 8e245e57591c9086159738fc0593f107314de319 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Sat, 21 Dec 2024 22:36:38 +0100 Subject: [PATCH 05/11] 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 641c152d985b7..386a96f38abdc 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 63563b2616b3e..d513c49b9b511 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -1448,7 +1448,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]: ... @@ -1715,7 +1715,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 @@ -1786,7 +1786,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 @@ -2106,7 +2106,7 @@ class _SupportsReversed(Protocol[_T_co]): def __reversed__(self) -> _T_co: ... @disjoint_base -class reversed(Generic[_T_co]): +class reversed(Iterator[_T_co]): @overload def __new__(cls, sequence: _SupportsReversed[_T], /) -> _T: ... # type: ignore[misc] @overload @@ -2186,7 +2186,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 751e85566f88e..18b36b20160f4 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 @@ -73,7 +73,7 @@ class excel(Dialect): ... class excel_tab(excel): ... class unix_dialect(Dialect): ... -class DictReader(Generic[_T]): +class DictReader(Iterator[dict[_T | Any, str | Any]], Generic[_T]): fieldnames: Sequence[_T] | None restkey: _T | None restval: str | Any | None diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index 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 f8a866997e9db2e8cd9fa206862cad8d00a48f80 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Mon, 23 Feb 2026 12:00:18 +0100 Subject: [PATCH 06/11] 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 0f25cf38be2f7..e5e30b0c248fe 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -677,17 +677,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 29de3977df32c7b987549126400094b6e082db2a Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Thu, 5 Nov 2026 13:08:55 +0100 Subject: [PATCH 07/11] Revert datetime generic tzinfo change --- mypy/typeshed/stdlib/datetime.pyi | 213 ++++-------------------------- 1 file changed, 25 insertions(+), 188 deletions(-) diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index 5272e3850fe73..0a21f72b09de4 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -1,7 +1,7 @@ import sys from abc import abstractmethod from time import struct_time -from typing import Any, ClassVar, Final, Generic, SupportsIndex, TypeAlias, TypeVar, final, overload, type_check_only +from typing import ClassVar, Final, SupportsIndex, TypeAlias, final, overload, type_check_only from typing_extensions import CapsuleType, Never, Self, deprecated, disjoint_base if sys.version_info >= (3, 11): @@ -266,28 +266,10 @@ class timedelta: def __bool__(self) -> bool: ... def __hash__(self) -> int: ... -_TzInfoT = TypeVar("_TzInfoT", bound=tzinfo | None, default=Any) - @disjoint_base -class datetime(date, Generic[_TzInfoT]): - min: ClassVar[datetime[None]] - max: ClassVar[datetime[None]] - - @overload - def __new__( - cls, - year: SupportsIndex, - month: SupportsIndex, - day: SupportsIndex, - hour: SupportsIndex = 0, - minute: SupportsIndex = 0, - second: SupportsIndex = 0, - microsecond: SupportsIndex = 0, - tzinfo: None = None, - *, - fold: int = 0, - ) -> datetime[None]: ... - @overload +class datetime(date): + min: ClassVar[datetime] + max: ClassVar[datetime] def __new__( cls, year: SupportsIndex, @@ -297,25 +279,10 @@ class datetime(date, Generic[_TzInfoT]): minute: SupportsIndex = 0, second: SupportsIndex = 0, microsecond: SupportsIndex = 0, - *, - tzinfo: _TzInfo, - fold: int = 0, - ) -> datetime[_TzInfo]: ... - @overload - def __new__( - cls, - year: SupportsIndex, - month: SupportsIndex, - day: SupportsIndex, - hour: SupportsIndex, - minute: SupportsIndex, - second: SupportsIndex, - microsecond: SupportsIndex, - tzinfo: _TzInfo, + tzinfo: _TzInfo | None = None, *, fold: int = 0, - ) -> datetime[_TzInfo]: ... - + ) -> Self: ... @property def hour(self) -> int: ... @property @@ -325,64 +292,32 @@ class datetime(date, Generic[_TzInfoT]): @property def microsecond(self) -> int: ... @property - def tzinfo(self) -> _TzInfoT: ... + def tzinfo(self) -> _TzInfo | None: ... @property def fold(self) -> int: ... # On <3.12, the name of the first parameter in the pure-Python implementation # didn't match the name in the C implementation, # meaning it is only *safe* to pass it as a keyword argument on 3.12+ if sys.version_info >= (3, 12): - @overload # type: ignore[override] - @classmethod - def fromtimestamp(cls, timestamp: float, tz: None = None) -> datetime[None]: ... - @overload @classmethod - def fromtimestamp(cls, timestamp: float, tz: _TzInfo) -> datetime[_TzInfo]: ... - @overload - @classmethod - def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None) -> datetime[_TzInfo] | datetime[None]: ... - else: - @overload # type: ignore[override] - @classmethod - def fromtimestamp(cls, timestamp: float, /, tz: None = None) -> datetime[None]: ... - @overload - @classmethod - def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo) -> datetime[_TzInfo]: ... - @overload - @classmethod - def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | None) -> datetime[_TzInfo] | datetime[None]: ... - - # fromisoformat returns Self, but we can't specialize "Self" - if sys.version_info >= (3, 15): - @classmethod - def fromisoformat(cls, string: str, /) -> datetime[_TzInfo] | datetime[None]: ... # type: ignore[override] + def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None = None) -> Self: ... else: @classmethod - def fromisoformat(cls, date_string: str, /) -> datetime[_TzInfo] | datetime[None]: ... # type: ignore[override] - - @classmethod - @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .fromtimestamp(datetime.UTC)") - def utcfromtimestamp(cls, t: float, /) -> datetime[None]: ... - - @overload - @classmethod - def now(cls, tz: None = None) -> datetime[None]: ... - @overload - @classmethod - def now(cls, tz: _TzInfo) -> datetime[_TzInfo]: ... + def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | None = None) -> Self: ... @classmethod - def today(cls) -> datetime[None]: ... # type: ignore[override] + @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .fromtimestamp(datetime.timezone.utc)") + def utcfromtimestamp(cls, t: float, /) -> Self: ... @classmethod - @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.UTC)") - def utcnow(cls) -> datetime[None]: ... - - @overload + def now(cls, tz: _TzInfo | None = None) -> Self: ... @classmethod - def combine(cls, date: _Date, time: _Time, tzinfo: None = None) -> datetime[None]: ... - @overload + @deprecated("Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.timezone.utc)") + def utcnow(cls) -> Self: ... @classmethod - def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo) -> datetime[_TzInfo]: ... + def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo | None = ...) -> Self: ... + if sys.version_info >= (3, 15): + @classmethod + def fromisoformat(cls, string: str, /) -> Self: ... def timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... @@ -405,7 +340,6 @@ class datetime(date, Generic[_TzInfoT]): fold: int = ..., ) -> Self: ... - @overload def replace( self, year: SupportsIndex = ..., @@ -415,67 +349,11 @@ class datetime(date, Generic[_TzInfoT]): minute: SupportsIndex = ..., second: SupportsIndex = ..., microsecond: SupportsIndex = ..., + tzinfo: _TzInfo | None = ..., *, fold: int = ..., ) -> Self: ... - @overload - def replace( - self, - year: SupportsIndex, - month: SupportsIndex, - day: SupportsIndex, - hour: SupportsIndex, - minute: SupportsIndex, - second: SupportsIndex, - microsecond: SupportsIndex, - tzinfo: _TzInfo, - *, - fold: int = ..., - ) -> datetime[_TzInfo]: ... - @overload - def replace( - self, - year: SupportsIndex = ..., - month: SupportsIndex = ..., - day: SupportsIndex = ..., - hour: SupportsIndex = ..., - minute: SupportsIndex = ..., - second: SupportsIndex = ..., - microsecond: SupportsIndex = ..., - *, - tzinfo: _TzInfo, - fold: int = ..., - ) -> datetime[_TzInfo]: ... - @overload - def replace( - self, - year: SupportsIndex, - month: SupportsIndex, - day: SupportsIndex, - hour: SupportsIndex, - minute: SupportsIndex, - second: SupportsIndex, - microsecond: SupportsIndex, - tzinfo: None, - *, - fold: int = ..., - ) -> datetime[None]: ... - @overload - def replace( - self, - year: SupportsIndex = ..., - month: SupportsIndex = ..., - day: SupportsIndex = ..., - hour: SupportsIndex = ..., - minute: SupportsIndex = ..., - second: SupportsIndex = ..., - microsecond: SupportsIndex = ..., - *, - tzinfo: None, - fold: int = ..., - ) -> datetime[None]: ... - - def astimezone(self, tz: _TzInfo | None = None) -> datetime[_TzInfo]: ... + def astimezone(self, tz: _TzInfo | None = None) -> Self: ... def isoformat(self, sep: str = "T", timespec: str = "auto") -> str: ... if sys.version_info >= (3, 15): @@ -488,56 +366,15 @@ class datetime(date, Generic[_TzInfoT]): def utcoffset(self) -> timedelta | None: ... def tzname(self) -> str | None: ... def dst(self) -> timedelta | None: ... - - @overload # type: ignore[override] - def __le__( # type: ignore[overload-overlap] - self: datetime[_TzInfo] | datetime[_TzInfo | None], value: datetime[_TzInfo] | datetime[_TzInfo | None], / - ) -> bool: ... # type: ignore[misc] - @overload - def __le__(self: datetime[None] | datetime[_TzInfo | None], value: datetime[None] | datetime[_TzInfo | None], /) -> bool: ... # type: ignore[misc] - @overload - def __le__(self: datetime[Any], value: datetime[Any], /) -> Never: ... - - @overload # type: ignore[override] - def __lt__( # type: ignore[overload-overlap] - self: datetime[_TzInfo] | datetime[_TzInfo | None], value: datetime[_TzInfo] | datetime[_TzInfo | None], / - ) -> bool: ... # type: ignore[misc] - @overload - def __lt__(self: datetime[None] | datetime[_TzInfo | None], value: datetime[None] | datetime[_TzInfo | None], /) -> bool: ... # type: ignore[misc] - @overload - def __lt__(self: datetime[Any], value: datetime[Any], /) -> Never: ... - - @overload # type: ignore[override] - def __ge__( # type: ignore[overload-overlap] - self: datetime[_TzInfo] | datetime[_TzInfo | None], value: datetime[_TzInfo] | datetime[_TzInfo | None], / - ) -> bool: ... # type: ignore[misc] - @overload - def __ge__(self: datetime[None] | datetime[_TzInfo | None], value: datetime[None] | datetime[_TzInfo | None], /) -> bool: ... # type: ignore[misc] - @overload - def __ge__(self: datetime[Any], value: datetime[Any], /) -> Never: ... - - @overload # type: ignore[override] - def __gt__( # type: ignore[overload-overlap] - self: datetime[_TzInfo] | datetime[_TzInfo | None], value: datetime[_TzInfo] | datetime[_TzInfo | None], / - ) -> bool: ... # type: ignore[misc] - @overload - def __gt__(self: datetime[None] | datetime[_TzInfo | None], value: datetime[None] | datetime[_TzInfo | None], /) -> bool: ... # type: ignore[misc] - @overload - def __gt__(self: datetime[Any], value: datetime[Any], /) -> Never: ... - + def __le__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __lt__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __ge__(self, value: datetime, /) -> bool: ... # type: ignore[override] + def __gt__(self, value: datetime, /) -> bool: ... # type: ignore[override] def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... @overload # type: ignore[override] - def __sub__( # type: ignore[overload-overlap] - self: datetime[_TzInfo] | datetime[_TzInfo | None], value: datetime[_TzInfo] | datetime[_TzInfo | None], / - ) -> timedelta: ... - @overload - def __sub__( # type: ignore[overload-overlap] - self: datetime[None] | datetime[_TzInfo | None], value: datetime[None] | datetime[_TzInfo | None], / - ) -> timedelta: ... - @overload - def __sub__(self: datetime[Any], value: datetime[Any], /) -> Never: ... + def __sub__(self, value: Self, /) -> timedelta: ... @overload def __sub__(self, value: timedelta, /) -> Self: ... From 1d30f3bb5d5ea50eb3f6a74d1570a3f5f7e20600 Mon Sep 17 00:00:00 2001 From: hauntsaninja Date: Wed, 6 May 2026 19:49:41 -0700 Subject: [PATCH 08/11] Revert operator changes --- mypy/typeshed/stdlib/_operator.pyi | 59 +++++++----------------------- 1 file changed, 14 insertions(+), 45 deletions(-) diff --git a/mypy/typeshed/stdlib/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi index 565bb41697f1f..ff419842ebfc6 100644 --- a/mypy/typeshed/stdlib/_operator.pyi +++ b/mypy/typeshed/stdlib/_operator.pyi @@ -1,16 +1,5 @@ import sys -from _typeshed import ( - ReadableBuffer, - SupportsAdd, - SupportsGetItem, - SupportsMod, - SupportsMul, - SupportsRAdd, - SupportsRMod, - SupportsRMul, - SupportsRSub, - SupportsSub, -) +from _typeshed import ReadableBuffer, 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, ParamSpec, Protocol, SupportsAbs, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only @@ -19,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") @@ -70,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 d999f534e5f165259e08e37a7148bd8ec35203a1 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 09/11] 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 d513c49b9b511..fcc236432bbde 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -2172,7 +2172,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 3e27f24e0e1d2dae65d932ea7ab50ea6db892749 Mon Sep 17 00:00:00 2001 From: AlexWaygood Date: Mon, 1 May 2023 20:34:55 +0100 Subject: [PATCH 10/11] 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 83ac60fd0d42d..45cf0e9bad57e 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 f973d7a6066c089c13c82d990781379e39cd45ee Mon Sep 17 00:00:00 2001 From: Shantanu Jain Date: Sun, 22 Feb 2026 20:37:48 -0800 Subject: [PATCH 11/11] 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 c286514af2292..461965f3868d6 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