diff --git a/misc/typeshed_patches/0001-Adjust-stubs-to-fix-mypy-lookup-error-due-to-circula.patch b/misc/typeshed_patches/0001-Adjust-stubs-to-fix-mypy-lookup-error-due-to-circula.patch index d8c4e24af917b..87aed9de2bf78 100644 --- a/misc/typeshed_patches/0001-Adjust-stubs-to-fix-mypy-lookup-error-due-to-circula.patch +++ b/misc/typeshed_patches/0001-Adjust-stubs-to-fix-mypy-lookup-error-due-to-circula.patch @@ -1,23 +1,86 @@ -From 5c922a2484f2e18c7f901e62bb499b6414cf1090 Mon Sep 17 00:00:00 2001 +From 8985351bf6f917db1a7b15ffed95ec2357d9819d Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> -Date: Wed, 18 Feb 2026 13:11:02 +0100 +Date: Mon, 18 May 2026 17:33:09 +0200 Subject: [PATCH] Adjust stubs to fix mypy lookup error due to circular dependencies in stubs --- - mypy/typeshed/stdlib/time.pyi | 6 +++--- - 1 file changed, 3 insertions(+), 3 deletions(-) + 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 aa445d22b..a90cf1edd 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 984f932e3..0ad928934 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 cc39a7c9f..0ca4cff75 100644 +--- a/mypy/typeshed/stdlib/inspect.pyi ++++ b/mypy/typeshed/stdlib/inspect.pyi +@@ -196,8 +196,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 d26a4e1da..60e79bc2e 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 64a009318..d0853792b 100644 +index ac53089b8..9b5344b32 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi -@@ -1,16 +1,16 @@ +@@ -1,15 +1,15 @@ import sys from _typeshed import structseq --from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, final, type_check_only -+from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, Union, final, type_check_only - from typing_extensions import TypeAlias +-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] @@ -33,5 +96,5 @@ index 64a009318..d0853792b 100644 altzone: int daylight: int -- -2.53.0 +2.54.0 diff --git a/misc/typeshed_patches/0001-Partially-revert-Clean-up-argparse-hacks.patch b/misc/typeshed_patches/0001-Partially-revert-Clean-up-argparse-hacks.patch index a1b1966fea1e0..bd7cbae517543 100644 --- a/misc/typeshed_patches/0001-Partially-revert-Clean-up-argparse-hacks.patch +++ b/misc/typeshed_patches/0001-Partially-revert-Clean-up-argparse-hacks.patch @@ -1,4 +1,4 @@ -From b6d495c10e79fb56ff64f8fb90c87894090f9cbe Mon Sep 17 00:00:00 2001 +From 3fa6658041d3ccd7f2a4bd725e21fa9768bf6ebc 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] Partially revert Clean up argparse hacks @@ -8,16 +8,16 @@ Subject: [PATCH] Partially revert Clean up argparse hacks 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi -index ae99eb036..c87b8f4fc 100644 +index 22d330a08..fa22f842d 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import SupportsWrite, sentinel from collections.abc import Callable, Generator, Iterable, Sequence from re import Pattern --from typing import IO, Any, ClassVar, Final, Generic, NoReturn, Protocol, TypeVar, overload, type_check_only -+from typing import IO, Any, ClassVar, Final, Generic, NewType, NoReturn, Protocol, TypeVar, overload, type_check_only - from typing_extensions import Self, TypeAlias, deprecated +-from typing import IO, Any, ClassVar, Final, Generic, NoReturn, Protocol, TypeAlias, TypeVar, overload, type_check_only ++from typing import IO, Any, ClassVar, Final, Generic, NewType, NoReturn, Protocol, TypeAlias, TypeVar, overload, type_check_only + from typing_extensions import Self, deprecated __all__ = [ @@ -36,7 +36,9 @@ ONE_OR_MORE: Final = "+" @@ -41,5 +41,5 @@ index ae99eb036..c87b8f4fc 100644 default: Any = ..., type: _ActionType = ..., -- -2.52.0 +2.54.0 diff --git a/misc/typeshed_patches/0001-Remove-use-of-LiteralString-in-builtins-13743.patch b/misc/typeshed_patches/0001-Remove-use-of-LiteralString-in-builtins-13743.patch index 3ca8f4deec922..6794731274d14 100644 --- a/misc/typeshed_patches/0001-Remove-use-of-LiteralString-in-builtins-13743.patch +++ b/misc/typeshed_patches/0001-Remove-use-of-LiteralString-in-builtins-13743.patch @@ -1,80 +1,94 @@ -From b3021cdc4b4c2cf547c5bc2d1d21a5a00ffea001 Mon Sep 17 00:00:00 2001 +From 83cf9b2dcc569149510c3a9118b9a7dc44144232 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] Remove use of LiteralString in builtins (#13743) --- - mypy/typeshed/stdlib/builtins.pyi | 98 ------------------------------- - 1 file changed, 98 deletions(-) + mypy/typeshed/stdlib/builtins.pyi | 127 +----------------------------- + 1 file changed, 1 insertion(+), 126 deletions(-) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi -index efc51fe25..8600a372b 100644 +index 0fe6d9a69..1808e28e2 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi -@@ -64,7 +64,6 @@ from typing import ( # noqa: Y022,UP035 - from typing_extensions import ( # noqa: Y023 - Concatenate, - Literal, -- LiteralString, - ParamSpec, - Self, - TypeAlias, -@@ -482,31 +481,16 @@ class str(Sequence[str]): +@@ -65,7 +65,7 @@ from typing import ( # noqa: Y022,UP035 + ) + + # we can't import `Literal` from typing or mypy crashes: see #11247 +-from typing_extensions import Literal, LiteralString, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023, UP035 ++from typing_extensions import Literal, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023, UP035 + + if sys.version_info >= (3, 14): + from _typeshed import AnnotateFunc +@@ -489,20 +489,8 @@ class str(Sequence[str]): def __new__(cls, object: object = "") -> Self: ... @overload def __new__(cls, object: ReadableBuffer, encoding: str = "utf-8", errors: str = "strict") -> Self: ... +- - @overload - def capitalize(self: LiteralString) -> LiteralString: ... - @overload def capitalize(self) -> str: ... # type: ignore[misc] +- - @overload - def casefold(self: LiteralString) -> LiteralString: ... - @overload def casefold(self) -> str: ... # type: ignore[misc] +- - @overload - def center(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... - @overload def center(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] + def count(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... - def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... +@@ -510,17 +498,9 @@ class str(Sequence[str]): def endswith( self, suffix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> bool: ... +- - @overload - def expandtabs(self: LiteralString, tabsize: SupportsIndex = 8) -> LiteralString: ... - @overload def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ... # type: ignore[misc] + def find(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... +- - @overload - def format(self: LiteralString, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... - @overload def format(self, *args: object, **kwargs: object) -> str: ... + def format_map(self, mapping: _FormatMapMapping, /) -> str: ... - def index(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... -@@ -522,98 +506,34 @@ class str(Sequence[str]): +@@ -537,119 +517,38 @@ class str(Sequence[str]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... +- - @overload - def join(self: LiteralString, iterable: Iterable[LiteralString], /) -> LiteralString: ... - @overload def join(self, iterable: Iterable[str], /) -> str: ... # type: ignore[misc] +- - @overload - def ljust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... - @overload def ljust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] +- - @overload - def lower(self: LiteralString) -> LiteralString: ... - @overload def lower(self) -> str: ... # type: ignore[misc] +- - @overload - def lstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... - @overload def lstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] +- - @overload - def partition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ... - @overload def partition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] + if sys.version_info >= (3, 13): - @overload - def replace( @@ -94,102 +108,127 @@ index efc51fe25..8600a372b 100644 - def removeprefix(self: LiteralString, prefix: LiteralString, /) -> LiteralString: ... - @overload def removeprefix(self, prefix: str, /) -> str: ... # type: ignore[misc] +- - @overload - def removesuffix(self: LiteralString, suffix: LiteralString, /) -> LiteralString: ... - @overload def removesuffix(self, suffix: str, /) -> str: ... # type: ignore[misc] + def rfind(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... def rindex(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... +- - @overload - def rjust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = " ", /) -> LiteralString: ... - @overload def rjust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] +- - @overload - def rpartition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ... - @overload def rpartition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] +- - @overload - def rsplit(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... - @overload def rsplit(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] +- - @overload - def rstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... - @overload def rstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] +- - @overload - def split(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ... - @overload def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] +- - @overload - def splitlines(self: LiteralString, keepends: bool = False) -> list[LiteralString]: ... - @overload def splitlines(self, keepends: bool = False) -> list[str]: ... # type: ignore[misc] + def startswith( self, prefix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> bool: ... +- - @overload - def strip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ... - @overload def strip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] +- - @overload - def swapcase(self: LiteralString) -> LiteralString: ... - @overload def swapcase(self) -> str: ... # type: ignore[misc] +- - @overload - def title(self: LiteralString) -> LiteralString: ... - @overload def title(self) -> str: ... # type: ignore[misc] + def translate(self, table: _TranslateTable, /) -> str: ... +- - @overload - def upper(self: LiteralString) -> LiteralString: ... - @overload def upper(self) -> str: ... # type: ignore[misc] +- - @overload - def zfill(self: LiteralString, width: SupportsIndex, /) -> LiteralString: ... - @overload def zfill(self, width: SupportsIndex, /) -> str: ... # type: ignore[misc] - @staticmethod - @overload -@@ -624,39 +544,21 @@ class str(Sequence[str]): + + if sys.version_info >= (3, 15): +@@ -677,49 +576,25 @@ class str(Sequence[str]): @staticmethod @overload def maketrans(x: str, y: str, z: str, /) -> dict[int, int | None]: ... +- - @overload - def __add__(self: LiteralString, value: LiteralString, /) -> LiteralString: ... - @overload def __add__(self, value: str, /) -> str: ... # type: ignore[misc] + # Incompatible with Sequence.__contains__ def __contains__(self, key: str, /) -> bool: ... # type: ignore[override] def __eq__(self, value: object, /) -> bool: ... def __ge__(self, value: str, /) -> bool: ... +- - @overload - def __getitem__(self: LiteralString, key: SupportsIndex | slice[SupportsIndex | None], /) -> LiteralString: ... - @overload def __getitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> str: ... # type: ignore[misc] + def __gt__(self, value: str, /) -> bool: ... def __hash__(self) -> int: ... +- - @overload - def __iter__(self: LiteralString) -> Iterator[LiteralString]: ... - @overload def __iter__(self) -> Iterator[str]: ... # type: ignore[misc] + def __le__(self, value: str, /) -> bool: ... def __len__(self) -> int: ... def __lt__(self, value: str, /) -> bool: ... +- - @overload - def __mod__(self: LiteralString, value: LiteralString | tuple[LiteralString, ...], /) -> LiteralString: ... - @overload def __mod__(self, value: Any, /) -> str: ... +- - @overload - def __mul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... - @overload def __mul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] + def __ne__(self, value: object, /) -> bool: ... +- - @overload - def __rmul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... - @overload def __rmul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] + def __getnewargs__(self) -> tuple[str]: ... - def __format__(self, format_spec: str, /) -> str: ... -- -2.52.0 +2.54.0 diff --git a/misc/typeshed_patches/0001-Revert-Remove-redundant-inheritances-from-Iterator.patch b/misc/typeshed_patches/0001-Revert-Remove-redundant-inheritances-from-Iterator.patch index 6194dc62cd36e..96779922b52f6 100644 --- a/misc/typeshed_patches/0001-Revert-Remove-redundant-inheritances-from-Iterator.patch +++ b/misc/typeshed_patches/0001-Revert-Remove-redundant-inheritances-from-Iterator.patch @@ -1,4 +1,4 @@ -From 69791281c2c5e919cea9a77c4a771f79d9e70384 Mon Sep 17 00:00:00 2001 +From d3dabcf7b7aaf0997b59f0a28bb41d17b6098f2c Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Sat, 21 Dec 2024 22:36:38 +0100 Subject: [PATCH] Revert Remove redundant inheritances from Iterator in @@ -15,7 +15,7 @@ Subject: [PATCH] Revert Remove redundant inheritances from Iterator in 7 files changed, 34 insertions(+), 34 deletions(-) diff --git a/mypy/typeshed/stdlib/_asyncio.pyi b/mypy/typeshed/stdlib/_asyncio.pyi -index d663f5d93..f43178e4d 100644 +index 23b690a9c..0ce93a435 100644 --- a/mypy/typeshed/stdlib/_asyncio.pyi +++ b/mypy/typeshed/stdlib/_asyncio.pyi @@ -1,6 +1,6 @@ @@ -25,7 +25,7 @@ index d663f5d93..f43178e4d 100644 +from collections.abc import Awaitable, Callable, Coroutine, Generator, Iterable from contextvars import Context from types import FrameType, GenericAlias - from typing import Any, Literal, TextIO, TypeVar + from typing import Any, Literal, TextIO, TypeAlias, TypeVar @@ -11,7 +11,7 @@ _T_co = TypeVar("_T_co", covariant=True) _TaskYieldType: TypeAlias = Future[object] | None @@ -36,10 +36,10 @@ index d663f5d93..f43178e4d 100644 @property def _exception(self) -> BaseException | None: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi -index 8acdeadff..5a3bb5908 100644 +index 1808e28e2..9db6f4fc7 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi -@@ -1226,7 +1226,7 @@ class frozenset(AbstractSet[_T_co]): +@@ -1369,7 +1369,7 @@ class frozenset(AbstractSet[_T_co]): def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @disjoint_base @@ -48,7 +48,7 @@ index 8acdeadff..5a3bb5908 100644 def __new__(cls, iterable: Iterable[_T], start: int = 0) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> tuple[int, _T]: ... -@@ -1413,7 +1413,7 @@ else: +@@ -1635,7 +1635,7 @@ else: exit: _sitebuiltins.Quitter @disjoint_base @@ -57,16 +57,16 @@ index 8acdeadff..5a3bb5908 100644 @overload def __new__(cls, function: None, iterable: Iterable[_T | None], /) -> Self: ... @overload -@@ -1477,7 +1477,7 @@ license: _sitebuiltins._Printer - +@@ -1706,7 +1706,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 -@@ -1784,7 +1784,7 @@ def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex +@@ -2022,7 +2022,7 @@ def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex quit: _sitebuiltins.Quitter @disjoint_base @@ -75,29 +75,29 @@ index 8acdeadff..5a3bb5908 100644 @overload def __new__(cls, sequence: Reversible[_T], /) -> Iterator[_T]: ... # type: ignore[misc] @overload -@@ -1848,7 +1848,7 @@ def vars(object: type, /) -> types.MappingProxyType[str, Any]: ... - @overload +@@ -2100,7 +2100,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]): - if sys.version_info >= (3, 10): - @overload - def __new__(cls, *, strict: bool = False) -> zip[Any]: ... + @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 2c8e7109c..4ed0ab1d8 100644 +index f8ab5f000..f3b4286a6 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi -@@ -25,7 +25,7 @@ else: - from _csv import _reader as Reader, _writer as Writer - +@@ -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): ... +@@ -69,7 +69,7 @@ class excel(Dialect): ... class excel_tab(excel): ... class unix_dialect(Dialect): ... @@ -107,7 +107,7 @@ index 2c8e7109c..4ed0ab1d8 100644 restkey: _T | None restval: str | Any | None diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi -index 6778b7648..95164de2f 100644 +index 37783254c..db9c228f5 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -1,8 +1,8 @@ @@ -116,22 +116,22 @@ index 6778b7648..95164de2f 100644 -from collections.abc import Callable, Iterable +from collections.abc import Callable, Iterable, Iterator from types import GenericAlias, TracebackType --from typing import IO, Any, AnyStr, Generic, Literal, Protocol, overload, type_check_only -+from typing import IO, Any, AnyStr, Literal, Protocol, overload, type_check_only - from typing_extensions import Self, TypeAlias, deprecated +-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__ = [ -@@ -105,7 +105,7 @@ def fileno() -> int: ... +@@ -74,7 +74,7 @@ def fileno() -> int: ... def isfirstline() -> bool: ... def isstdin() -> bool: ... -class FileInput(Generic[AnyStr]): +class FileInput(Iterator[AnyStr]): - if sys.version_info >= (3, 10): - # encoding and errors are added - @overload + # encoding and errors are added + @overload + def __init__( diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi -index 8a924ad8b..5c2bf7f83 100644 +index d26a4e1da..9d1cd84da 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -28,7 +28,7 @@ _Predicate: TypeAlias = Callable[[_T], object] @@ -143,7 +143,7 @@ index 8a924ad8b..5c2bf7f83 100644 @overload def __new__(cls) -> count[int]: ... @overload -@@ -39,13 +39,13 @@ class count(Generic[_N]): +@@ -40,13 +40,13 @@ class count(Generic[_N]): def __iter__(self) -> Self: ... @disjoint_base @@ -159,7 +159,7 @@ index 8a924ad8b..5c2bf7f83 100644 @overload def __new__(cls, object: _T) -> Self: ... @overload -@@ -55,7 +55,7 @@ class repeat(Generic[_T]): +@@ -57,7 +57,7 @@ class repeat(Generic[_T]): def __length_hint__(self) -> int: ... @disjoint_base @@ -168,7 +168,7 @@ index 8a924ad8b..5c2bf7f83 100644 @overload def __new__(cls, iterable: Iterable[_T], func: None = None, *, initial: _T | None = None) -> Self: ... @overload -@@ -64,7 +64,7 @@ class accumulate(Generic[_T]): +@@ -67,7 +67,7 @@ class accumulate(Generic[_T]): def __next__(self) -> _T: ... @disjoint_base @@ -177,7 +177,7 @@ index 8a924ad8b..5c2bf7f83 100644 def __new__(cls, *iterables: Iterable[_T]) -> Self: ... def __next__(self) -> _T: ... def __iter__(self) -> Self: ... -@@ -74,25 +74,25 @@ class chain(Generic[_T]): +@@ -77,25 +77,25 @@ class chain(Generic[_T]): def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @disjoint_base @@ -207,7 +207,7 @@ index 8a924ad8b..5c2bf7f83 100644 @overload def __new__(cls, iterable: Iterable[_T1], key: None = None) -> groupby[_T1, _T1]: ... @overload -@@ -101,7 +101,7 @@ class groupby(Generic[_T_co, _S_co]): +@@ -105,7 +105,7 @@ class groupby(Generic[_T_co, _S_co]): def __next__(self) -> tuple[_T_co, Iterator[_S_co]]: ... @disjoint_base @@ -216,7 +216,7 @@ index 8a924ad8b..5c2bf7f83 100644 @overload def __new__(cls, iterable: Iterable[_T], stop: int | None, /) -> Self: ... @overload -@@ -110,20 +110,20 @@ class islice(Generic[_T]): +@@ -115,13 +115,13 @@ class islice(Generic[_T]): def __next__(self) -> _T: ... @disjoint_base @@ -232,15 +232,16 @@ index 8a924ad8b..5c2bf7f83 100644 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]]: ... -@@ -202,7 +202,7 @@ class zip_longest(Generic[_T_co]): +@@ -209,7 +209,7 @@ class zip_longest(Generic[_T_co]): def __next__(self) -> _T_co: ... @disjoint_base @@ -249,7 +250,7 @@ index 8a924ad8b..5c2bf7f83 100644 @overload def __new__(cls, iter1: Iterable[_T1], /) -> product[tuple[_T1]]: ... @overload -@@ -288,7 +288,7 @@ class product(Generic[_T_co]): +@@ -296,7 +296,7 @@ class product(Generic[_T_co]): def __next__(self) -> _T_co: ... @disjoint_base @@ -258,7 +259,7 @@ index 8a924ad8b..5c2bf7f83 100644 @overload def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> permutations[tuple[_T, _T]]: ... @overload -@@ -303,7 +303,7 @@ class permutations(Generic[_T_co]): +@@ -312,7 +312,7 @@ class permutations(Generic[_T_co]): def __next__(self) -> _T_co: ... @disjoint_base @@ -267,7 +268,7 @@ index 8a924ad8b..5c2bf7f83 100644 @overload def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations[tuple[_T, _T]]: ... @overload -@@ -318,7 +318,7 @@ class combinations(Generic[_T_co]): +@@ -328,7 +328,7 @@ class combinations(Generic[_T_co]): def __next__(self) -> _T_co: ... @disjoint_base @@ -276,15 +277,15 @@ index 8a924ad8b..5c2bf7f83 100644 @overload def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations_with_replacement[tuple[_T, _T]]: ... @overload -@@ -334,14 +334,14 @@ class combinations_with_replacement(Generic[_T_co]): +@@ -344,14 +344,14 @@ class combinations_with_replacement(Generic[_T_co]): + def __next__(self) -> _T_co: ... - if sys.version_info >= (3, 10): - @disjoint_base -- class pairwise(Generic[_T_co]): -+ class pairwise(Iterator[_T_co]): - def __new__(cls, iterable: Iterable[_T], /) -> pairwise[tuple[_T, _T]]: ... - def __iter__(self) -> Self: ... - def __next__(self) -> _T_co: ... + @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 @@ -313,10 +314,10 @@ index b79f9e773..f276372d0 100644 def __iter__(self) -> Self: ... def next(self, timeout: float | None = None) -> _T: ... diff --git a/mypy/typeshed/stdlib/sqlite3/__init__.pyi b/mypy/typeshed/stdlib/sqlite3/__init__.pyi -index 04b978b1b..e4604144f 100644 +index 7c033bdf4..7bf020558 100644 --- a/mypy/typeshed/stdlib/sqlite3/__init__.pyi +++ b/mypy/typeshed/stdlib/sqlite3/__init__.pyi -@@ -408,7 +408,7 @@ class Connection: +@@ -426,7 +426,7 @@ class Connection: ) -> Literal[False]: ... @disjoint_base @@ -326,5 +327,5 @@ index 04b978b1b..e4604144f 100644 @property def connection(self) -> Connection: ... -- -2.52.0 +2.54.0 diff --git a/misc/typeshed_patches/0001-Revert-dict.__or__-typeshed-change.patch b/misc/typeshed_patches/0001-Revert-dict.__or__-typeshed-change.patch index 890b2782abedd..f144e989fb683 100644 --- a/misc/typeshed_patches/0001-Revert-dict.__or__-typeshed-change.patch +++ b/misc/typeshed_patches/0001-Revert-dict.__or__-typeshed-change.patch @@ -1,30 +1,63 @@ -From d88a4b774fc59ecd0f2d0fdda8e0e61092adafd3 Mon Sep 17 00:00:00 2001 +From 92a0169fa37f3ff1c41beb98ae0f61e3b3ff19dc Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Wed, 8 Apr 2026 00:01:44 +0100 Subject: [PATCH] Revert dict.__or__ typeshed change --- - mypy/typeshed/stdlib/builtins.pyi | 6 ++++++ - 1 file changed, 6 insertions(+) + mypy/typeshed/stdlib/builtins.pyi | 20 ++++++++++++++++++++ + 1 file changed, 20 insertions(+) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi -index 674142d70..25b21ba97 100644 +index 9db6f4fc7..7ec0e2d7c 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi -@@ -1142,7 +1142,13 @@ class dict(MutableMapping[_KT, _VT]): - def __reversed__(self) -> Iterator[_KT]: ... +@@ -1228,14 +1228,27 @@ class dict(MutableMapping[_KT, _VT]): __hash__: ClassVar[None] # type: ignore[assignment] def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -+ @overload -+ def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... -+ @overload - def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... -+ @overload -+ def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... -+ @overload - def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + if sys.version_info >= (3, 15): ++ @overload ++ def __or__(self, value: dict[_KT, _VT] | frozendict[_KT, _VT], /) -> dict[_KT, _VT]: ... ++ @overload + def __or__(self, value: dict[_T1, _T2] | frozendict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + ++ @overload ++ def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + @overload ++ def __ror__(self, value: frozendict[_KT, _VT], /) -> frozendict[_KT, _VT]: ... ++ @overload + def __ror__(self, value: frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... + else: ++ @overload ++ def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... ++ @overload + def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... ++ @overload ++ def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... ++ @overload + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + # dict.__ior__ should be kept roughly in line with MutableMapping.update() - @overload # type: ignore[misc] +@@ -1290,11 +1303,18 @@ if sys.version_info >= (3, 15): + def __iter__(self) -> Iterator[_KT]: ... + def __hash__(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... ++ @overload ++ def __or__(self, value: dict[_KT, _VT] | frozendict[_KT, _VT], /) -> frozendict[_KT, _VT]: ... ++ @overload + def __or__(self, value: dict[_T1, _T2] | frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... + ++ @overload ++ def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + @overload ++ def __ror__(self, value: frozendict[_KT, _VT], /) -> frozendict[_KT, _VT]: ... ++ @overload + def __ror__(self, value: frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... + + @disjoint_base -- -2.25.1 +2.54.0 diff --git a/misc/typeshed_patches/0001-Revert-operator-changes.patch b/misc/typeshed_patches/0001-Revert-operator-changes.patch index 71b0ae9b47abd..77cdeebb619bf 100644 --- a/misc/typeshed_patches/0001-Revert-operator-changes.patch +++ b/misc/typeshed_patches/0001-Revert-operator-changes.patch @@ -1,14 +1,14 @@ -From 7f38b86464d59188a87ff8c9913c257e788a2f0b Mon Sep 17 00:00:00 2001 +From 5ab958030bd7d4ed9cb3e2afa656b68ea5a07901 Mon Sep 17 00:00:00 2001 From: hauntsaninja Date: Wed, 6 May 2026 19:49:41 -0700 Subject: [PATCH] Revert operator changes --- - mypy/typeshed/stdlib/_operator.pyi | 51 ++++++++---------------------- - 1 file changed, 14 insertions(+), 37 deletions(-) + mypy/typeshed/stdlib/_operator.pyi | 58 ++++++++---------------------- + 1 file changed, 14 insertions(+), 44 deletions(-) diff --git a/mypy/typeshed/stdlib/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi -index e7d85f811..8c705065b 100644 +index 04dae79dc..29a6d7057 100644 --- a/mypy/typeshed/stdlib/_operator.pyi +++ b/mypy/typeshed/stdlib/_operator.pyi @@ -1,15 +1,5 @@ @@ -27,8 +27,8 @@ index e7d85f811..8c705065b 100644 +from _typeshed import SupportsGetItem from collections.abc import Callable, Container, Iterable, MutableMapping, MutableSequence, Sequence from operator import attrgetter as attrgetter, itemgetter as itemgetter, methodcaller as methodcaller - from typing import Any, AnyStr, Protocol, SupportsAbs, SupportsIndex, TypeVar, overload, type_check_only -@@ -18,7 +8,6 @@ from typing_extensions import ParamSpec, TypeAlias, TypeIs + from typing import Any, AnyStr, ParamSpec, Protocol, SupportsAbs, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only +@@ -18,7 +8,6 @@ from typing_extensions import TypeIs _R = TypeVar("_R") _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) @@ -36,14 +36,16 @@ index e7d85f811..8c705065b 100644 _K = TypeVar("_K") _V = TypeVar("_V") _P = ParamSpec("_P") -@@ -69,36 +58,24 @@ def truth(a: object, /) -> bool: ... +@@ -69,43 +58,24 @@ def truth(a: object, /) -> bool: ... def is_(a: object, b: object, /) -> bool: ... def is_not(a: object, b: object, /) -> bool: ... def abs(a: SupportsAbs[_T], /) -> _T: ... +- -@overload -def add(a: SupportsAdd[_T_contra, _T_co], b: _T_contra, /) -> _T_co: ... -@overload -def add(a: _T_contra, b: SupportsRAdd[_T_contra, _T_co], /) -> _T_co: ... +- -def and_(a, b, /): ... -def floordiv(a, b, /): ... +def add(a: Any, b: Any, /) -> Any: ... @@ -53,14 +55,17 @@ index e7d85f811..8c705065b 100644 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: ... @@ -72,10 +77,12 @@ index e7d85f811..8c705065b 100644 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: ... @@ -87,5 +94,5 @@ index e7d85f811..8c705065b 100644 def contains(a: Container[object], b: object, /) -> bool: ... def countOf(a: Iterable[object], b: object, /) -> int: ... -- -2.53.0 +2.54.0 diff --git a/misc/typeshed_patches/0001-Revert-sum-literal-integer-change-13961.patch b/misc/typeshed_patches/0001-Revert-sum-literal-integer-change-13961.patch index d05f66ff26108..99e4cb0e8d187 100644 --- a/misc/typeshed_patches/0001-Revert-sum-literal-integer-change-13961.patch +++ b/misc/typeshed_patches/0001-Revert-sum-literal-integer-change-13961.patch @@ -1,4 +1,4 @@ -From 0e30b762e8335f02e19977c055ac7b98e707991c Mon Sep 17 00:00:00 2001 +From a97066922305395b64cbbc1a6f68f7cae60a3aa6 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] Revert sum literal integer change (#13961) @@ -19,10 +19,10 @@ within mypy, I might pursue upstreaming this in typeshed. 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi -index 5a3bb5908..0f2196070 100644 +index dc24bc540..6f21960cb 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi -@@ -1835,7 +1835,7 @@ _SupportsSumNoDefaultT = TypeVar("_SupportsSumNoDefaultT", bound=_SupportsSumWit +@@ -2099,7 +2099,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 @@ -32,5 +32,5 @@ index 5a3bb5908..0f2196070 100644 def sum(iterable: Iterable[_SupportsSumNoDefaultT], /) -> _SupportsSumNoDefaultT | Literal[0]: ... @overload -- -2.52.0 +2.54.0 diff --git a/misc/typeshed_patches/0001-Revert-typeshed-ctypes-change.patch b/misc/typeshed_patches/0001-Revert-typeshed-ctypes-change.patch index e795be53bce71..a19d87ba8c3f8 100644 --- a/misc/typeshed_patches/0001-Revert-typeshed-ctypes-change.patch +++ b/misc/typeshed_patches/0001-Revert-typeshed-ctypes-change.patch @@ -1,4 +1,4 @@ -From 80a710e0e2c09612c6fc30c644f2052450e69ccd Mon Sep 17 00:00:00 2001 +From 22a35cde63e8e89b91b4b62a20f4ef0fc3f5d3fe Mon Sep 17 00:00:00 2001 From: AlexWaygood Date: Mon, 1 May 2023 20:34:55 +0100 Subject: [PATCH] Revert typeshed ctypes change @@ -7,26 +7,27 @@ The plugin provides superior type checking: https://github.com/python/mypy/pull/13987#issuecomment-1310863427 A manual cherry-pick of e437cdf. --- - mypy/typeshed/stdlib/_ctypes.pyi | 6 +----- - 1 file changed, 1 insertion(+), 5 deletions(-) + 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 be7792818..b7a3fb104 100644 +index d800ac5c2..1efb11926 100644 --- a/mypy/typeshed/stdlib/_ctypes.pyi +++ b/mypy/typeshed/stdlib/_ctypes.pyi -@@ -320,11 +320,7 @@ class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): - def _type_(self) -> type[_CT]: ... +@@ -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 -- -2.52.0 +2.54.0 diff --git a/misc/typeshed_patches/0001-Temporarily-revert-contextlib-deprecation.patch b/misc/typeshed_patches/0001-Temporarily-revert-contextlib-deprecation.patch index 4540e891f9954..fab037c38045e 100644 --- a/misc/typeshed_patches/0001-Temporarily-revert-contextlib-deprecation.patch +++ b/misc/typeshed_patches/0001-Temporarily-revert-contextlib-deprecation.patch @@ -1,4 +1,4 @@ -From ae45edc46f2ca9c939e317648b44ed3372487798 Mon Sep 17 00:00:00 2001 +From 12fb8e77eb5efc5c025d961e04ba7ccef23333bf Mon Sep 17 00:00:00 2001 From: Shantanu Jain Date: Sun, 22 Feb 2026 20:37:48 -0800 Subject: [PATCH] Temporarily revert contextlib deprecation @@ -8,19 +8,19 @@ Subject: [PATCH] Temporarily revert contextlib deprecation 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi -index 8d5902c46..221102ee2 100644 +index b95c23502..73cdda3b8 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -5,7 +5,7 @@ from abc import ABC, abstractmethod from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Generator, Iterator from types import TracebackType - from typing import Any, Generic, Protocol, TypeVar, overload, runtime_checkable, type_check_only --from typing_extensions import ParamSpec, Self, TypeAlias, deprecated -+from typing_extensions import ParamSpec, Self, TypeAlias + 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__ = [ - "contextmanager", -@@ -86,12 +86,6 @@ class _GeneratorContextManager( + "aclosing", +@@ -84,12 +84,6 @@ class _GeneratorContextManager( self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> bool | None: ... @@ -32,10 +32,10 @@ index 8d5902c46..221102ee2 100644 -) def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ... - if sys.version_info >= (3, 10): -@@ -118,13 +112,6 @@ else: - self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None - ) -> bool | None: ... + _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]]: ... @@ -45,8 +45,8 @@ index 8d5902c46..221102ee2 100644 - "Use `-> AsyncGenerator[Foo]` instead." -) def asynccontextmanager(func: Callable[_P, AsyncIterator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ... + @type_check_only - class _SupportsClose(Protocol): -- -2.53.0 +2.54.0 diff --git a/mypy/test/teststubtest.py b/mypy/test/teststubtest.py index 71555c03b9ad4..858fd860fd01d 100644 --- a/mypy/test/teststubtest.py +++ b/mypy/test/teststubtest.py @@ -3135,7 +3135,6 @@ def test_get_typeshed_stdlib_modules(self) -> None: assert "os.path" in stdlib assert "asyncio" in stdlib assert "graphlib" not in stdlib - assert "formatter" in stdlib assert "contextvars" in stdlib # 3.7+ assert "importlib.metadata" not in stdlib diff --git a/mypy/typeshed/stdlib/VERSIONS b/mypy/typeshed/stdlib/VERSIONS index e26bb8da2574e..e9c8d91fdbd71 100644 --- a/mypy/typeshed/stdlib/VERSIONS +++ b/mypy/typeshed/stdlib/VERSIONS @@ -23,7 +23,6 @@ _ast: 3.0- _asyncio: 3.0- _bisect: 3.0- _blake2: 3.6- -_bootlocale: 3.4-3.9 _bz2: 3.3- _codecs: 3.0- _collections_abc: 3.3- @@ -61,6 +60,7 @@ _py_abc: 3.7- _pydecimal: 3.5- _queue: 3.7- _random: 3.0- +_remote_debugging: 3.15- _sitebuiltins: 3.4- _socket: 3.0- # present in 3.0 at runtime, but not in typeshed _sqlite3: 3.0- @@ -143,7 +143,6 @@ difflib: 3.0- dis: 3.0- distutils: 3.0-3.11 distutils.command.bdist_msi: 3.0-3.10 -distutils.command.bdist_wininst: 3.0-3.9 doctest: 3.0- email: 3.0- encodings: 3.0- @@ -160,7 +159,6 @@ fcntl: 3.0- filecmp: 3.0- fileinput: 3.0- fnmatch: 3.0- -formatter: 3.0-3.9 fractions: 3.0- ftplib: 3.0- functools: 3.0- @@ -211,6 +209,7 @@ mailbox: 3.0- mailcap: 3.0-3.12 marshal: 3.0- math: 3.0- +math.integer: 3.15- mimetypes: 3.0- mmap: 3.0- modulefinder: 3.0- @@ -231,7 +230,6 @@ operator: 3.0- optparse: 3.0- os: 3.0- ossaudiodev: 3.0-3.12 -parser: 3.0-3.9 pathlib: 3.4- pathlib.types: 3.14- pdb: 3.0- @@ -246,6 +244,9 @@ posix: 3.0- posixpath: 3.0- pprint: 3.0- profile: 3.0- +profiling: 3.15- +profiling.sampling: 3.15- +profiling.tracing: 3.15- pstats: 3.0- pty: 3.0- pwd: 3.0- @@ -280,9 +281,9 @@ socket: 3.0- socketserver: 3.0- spwd: 3.0-3.12 sqlite3: 3.0- -sre_compile: 3.0- -sre_constants: 3.0- -sre_parse: 3.0- +sre_compile: 3.0-3.14 +sre_constants: 3.0-3.14 +sre_parse: 3.0-3.14 ssl: 3.0- stat: 3.0- statistics: 3.4- @@ -292,9 +293,9 @@ stringprep: 3.0- struct: 3.0- subprocess: 3.0- sunau: 3.0-3.12 -symbol: 3.0-3.9 symtable: 3.0- sys: 3.0- +sys.__jit: 3.14- # Similar to sys._monitoring sys._monitoring: 3.12- # Doesn't actually exist. See comments in the stub. sysconfig: 3.0- syslog: 3.0- @@ -339,6 +340,7 @@ wsgiref: 3.0- wsgiref.types: 3.11- xdrlib: 3.0-3.12 xml: 3.0- +xml.utils: 3.15- xmlrpc: 3.0- xxlimited: 3.2- zipapp: 3.5- diff --git a/mypy/typeshed/stdlib/_ast.pyi b/mypy/typeshed/stdlib/_ast.pyi index d8d5a1829991e..fd89973aefe65 100644 --- a/mypy/typeshed/stdlib/_ast.pyi +++ b/mypy/typeshed/stdlib/_ast.pyi @@ -58,6 +58,15 @@ from ast import ( LShift as LShift, Lt as Lt, LtE as LtE, + Match as Match, + MatchAs as MatchAs, + MatchClass as MatchClass, + MatchMapping as MatchMapping, + MatchOr as MatchOr, + MatchSequence as MatchSequence, + MatchSingleton as MatchSingleton, + MatchStar as MatchStar, + MatchValue as MatchValue, MatMult as MatMult, Mod as Mod, Module as Module, @@ -101,8 +110,10 @@ from ast import ( expr as expr, expr_context as expr_context, keyword as keyword, + match_case as match_case, mod as mod, operator as operator, + pattern as pattern, stmt as stmt, type_ignore as type_ignore, unaryop as unaryop, @@ -122,21 +133,6 @@ if sys.version_info >= (3, 12): if sys.version_info >= (3, 11): from ast import TryStar as TryStar -if sys.version_info >= (3, 10): - from ast import ( - Match as Match, - MatchAs as MatchAs, - MatchClass as MatchClass, - MatchMapping as MatchMapping, - MatchOr as MatchOr, - MatchSequence as MatchSequence, - MatchSingleton as MatchSingleton, - MatchStar as MatchStar, - MatchValue as MatchValue, - match_case as match_case, - pattern as pattern, - ) - PyCF_ALLOW_TOP_LEVEL_AWAIT: Final = 8192 PyCF_ONLY_AST: Final = 1024 PyCF_TYPE_COMMENTS: Final = 4096 diff --git a/mypy/typeshed/stdlib/_asyncio.pyi b/mypy/typeshed/stdlib/_asyncio.pyi index f43178e4d7258..0ce93a4358d2a 100644 --- a/mypy/typeshed/stdlib/_asyncio.pyi +++ b/mypy/typeshed/stdlib/_asyncio.pyi @@ -3,8 +3,8 @@ from asyncio.events import AbstractEventLoop from collections.abc import Awaitable, Callable, Coroutine, Generator, Iterable from contextvars import Context from types import FrameType, GenericAlias -from typing import Any, Literal, TextIO, TypeVar -from typing_extensions import Self, TypeAlias, disjoint_base +from typing import Any, Literal, TextIO, TypeAlias, TypeVar +from typing_extensions import Self, disjoint_base _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) @@ -16,10 +16,12 @@ class Future(Awaitable[_T], Iterable[_T]): @property def _exception(self) -> BaseException | None: ... _blocking: bool + @property def _log_traceback(self) -> bool: ... @_log_traceback.setter def _log_traceback(self, val: Literal[False]) -> None: ... + _asyncio_future_blocking: bool # is a part of duck-typing contract for `Future` def __init__(self, *, loop: AbstractEventLoop | None = None) -> None: ... def __del__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/_bisect.pyi b/mypy/typeshed/stdlib/_bisect.pyi index 5ac43b3e06414..b87dd8f3fb871 100644 --- a/mypy/typeshed/stdlib/_bisect.pyi +++ b/mypy/typeshed/stdlib/_bisect.pyi @@ -1,140 +1,103 @@ -import sys from _typeshed import SupportsGetItem, SupportsLenAndGetItem, SupportsRichComparisonT from collections.abc import Callable, MutableSequence from typing import TypeVar, overload _T = TypeVar("_T") -if sys.version_info >= (3, 10): - @overload - def bisect_left( - a: SupportsLenAndGetItem[SupportsRichComparisonT], - x: SupportsRichComparisonT, - lo: int = 0, - hi: int | None = None, - *, - key: None = None, - ) -> int: ... - @overload - def bisect_left( - a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int, hi: int, *, key: None = None - ) -> int: ... - @overload - def bisect_left( - a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, *, hi: int, key: None = None - ) -> int: ... - @overload - def bisect_left( - a: SupportsLenAndGetItem[_T], - x: SupportsRichComparisonT, - lo: int = 0, - hi: int | None = None, - *, - key: Callable[[_T], SupportsRichComparisonT], - ) -> int: ... - @overload - def bisect_left( - a: SupportsGetItem[int, _T], x: SupportsRichComparisonT, lo: int, hi: int, *, key: Callable[[_T], SupportsRichComparisonT] - ) -> int: ... - @overload - def bisect_left( - a: SupportsGetItem[int, _T], - x: SupportsRichComparisonT, - lo: int = 0, - *, - hi: int, - key: Callable[[_T], SupportsRichComparisonT], - ) -> int: ... - @overload - def bisect_right( - a: SupportsLenAndGetItem[SupportsRichComparisonT], - x: SupportsRichComparisonT, - lo: int = 0, - hi: int | None = None, - *, - key: None = None, - ) -> int: ... - @overload - def bisect_right( - a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int, hi: int, *, key: None = None - ) -> int: ... - @overload - def bisect_right( - a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, *, hi: int, key: None = None - ) -> int: ... - @overload - def bisect_right( - a: SupportsLenAndGetItem[_T], - x: SupportsRichComparisonT, - lo: int = 0, - hi: int | None = None, - *, - key: Callable[[_T], SupportsRichComparisonT], - ) -> int: ... - @overload - def bisect_right( - a: SupportsGetItem[int, _T], x: SupportsRichComparisonT, lo: int, hi: int, *, key: Callable[[_T], SupportsRichComparisonT] - ) -> int: ... - @overload - def bisect_right( - a: SupportsGetItem[int, _T], - x: SupportsRichComparisonT, - lo: int = 0, - *, - hi: int, - key: Callable[[_T], SupportsRichComparisonT], - ) -> int: ... - @overload - def insort_left( - a: MutableSequence[SupportsRichComparisonT], - x: SupportsRichComparisonT, - lo: int = 0, - hi: int | None = None, - *, - key: None = None, - ) -> None: ... - @overload - def insort_left( - a: MutableSequence[_T], x: _T, lo: int = 0, hi: int | None = None, *, key: Callable[[_T], SupportsRichComparisonT] - ) -> None: ... - @overload - def insort_right( - a: MutableSequence[SupportsRichComparisonT], - x: SupportsRichComparisonT, - lo: int = 0, - hi: int | None = None, - *, - key: None = None, - ) -> None: ... - @overload - def insort_right( - a: MutableSequence[_T], x: _T, lo: int = 0, hi: int | None = None, *, key: Callable[[_T], SupportsRichComparisonT] - ) -> None: ... +@overload +def bisect_left( + a: SupportsLenAndGetItem[SupportsRichComparisonT], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: None = None, +) -> int: ... +@overload +def bisect_left( + a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int, hi: int, *, key: None = None +) -> int: ... +@overload +def bisect_left( + a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, *, hi: int, key: None = None +) -> int: ... +@overload +def bisect_left( + a: SupportsLenAndGetItem[_T], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: Callable[[_T], SupportsRichComparisonT], +) -> int: ... +@overload +def bisect_left( + a: SupportsGetItem[int, _T], x: SupportsRichComparisonT, lo: int, hi: int, *, key: Callable[[_T], SupportsRichComparisonT] +) -> int: ... +@overload +def bisect_left( + a: SupportsGetItem[int, _T], x: SupportsRichComparisonT, lo: int = 0, *, hi: int, key: Callable[[_T], SupportsRichComparisonT] +) -> int: ... -else: - @overload - def bisect_left( - a: SupportsLenAndGetItem[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None - ) -> int: ... - @overload - def bisect_left(a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int, hi: int) -> int: ... - @overload - def bisect_left( - a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, *, hi: int - ) -> int: ... - @overload - def bisect_right( - a: SupportsLenAndGetItem[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None - ) -> int: ... - @overload - def bisect_right(a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int, hi: int) -> int: ... - @overload - def bisect_right( - a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, *, hi: int - ) -> int: ... - def insort_left( - a: MutableSequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None - ) -> None: ... - def insort_right( - a: MutableSequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None - ) -> None: ... +@overload +def bisect_right( + a: SupportsLenAndGetItem[SupportsRichComparisonT], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: None = None, +) -> int: ... +@overload +def bisect_right( + a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int, hi: int, *, key: None = None +) -> int: ... +@overload +def bisect_right( + a: SupportsGetItem[int, SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, *, hi: int, key: None = None +) -> int: ... +@overload +def bisect_right( + a: SupportsLenAndGetItem[_T], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: Callable[[_T], SupportsRichComparisonT], +) -> int: ... +@overload +def bisect_right( + a: SupportsGetItem[int, _T], x: SupportsRichComparisonT, lo: int, hi: int, *, key: Callable[[_T], SupportsRichComparisonT] +) -> int: ... +@overload +def bisect_right( + a: SupportsGetItem[int, _T], x: SupportsRichComparisonT, lo: int = 0, *, hi: int, key: Callable[[_T], SupportsRichComparisonT] +) -> int: ... + +@overload +def insort_left( + a: MutableSequence[SupportsRichComparisonT], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: None = None, +) -> None: ... +@overload +def insort_left( + a: MutableSequence[_T], x: _T, lo: int = 0, hi: int | None = None, *, key: Callable[[_T], SupportsRichComparisonT] +) -> None: ... + +@overload +def insort_right( + a: MutableSequence[SupportsRichComparisonT], + x: SupportsRichComparisonT, + lo: int = 0, + hi: int | None = None, + *, + key: None = None, +) -> None: ... +@overload +def insort_right( + a: MutableSequence[_T], x: _T, lo: int = 0, hi: int | None = None, *, key: Callable[[_T], SupportsRichComparisonT] +) -> None: ... diff --git a/mypy/typeshed/stdlib/_bootlocale.pyi b/mypy/typeshed/stdlib/_bootlocale.pyi deleted file mode 100644 index 233d4934f3c6d..0000000000000 --- a/mypy/typeshed/stdlib/_bootlocale.pyi +++ /dev/null @@ -1 +0,0 @@ -def getpreferredencoding(do_setlocale: bool = True) -> str: ... diff --git a/mypy/typeshed/stdlib/_codecs.pyi b/mypy/typeshed/stdlib/_codecs.pyi index 89cb78c33571d..38cf857d05691 100644 --- a/mypy/typeshed/stdlib/_codecs.pyi +++ b/mypy/typeshed/stdlib/_codecs.pyi @@ -2,8 +2,7 @@ import codecs import sys from _typeshed import ReadableBuffer from collections.abc import Callable -from typing import Literal, final, overload, type_check_only -from typing_extensions import TypeAlias +from typing import Literal, TypeAlias, final, overload, type_check_only # This type is not exposed; it is defined in unicodeobject.c # At runtime it calls itself builtins.EncodingMap @@ -17,10 +16,7 @@ _Handler: TypeAlias = Callable[[UnicodeError], tuple[str | bytes, int]] _SearchFunction: TypeAlias = Callable[[str], codecs.CodecInfo | None] def register(search_function: _SearchFunction, /) -> None: ... - -if sys.version_info >= (3, 10): - def unregister(search_function: _SearchFunction, /) -> None: ... - +def unregister(search_function: _SearchFunction, /) -> None: ... def register_error(errors: str, handler: _Handler, /) -> None: ... def lookup_error(name: str, /) -> _Handler: ... @@ -53,6 +49,7 @@ def encode(obj: ReadableBuffer, encoding: _BytesToBytesEncoding, errors: str = " def encode(obj: str, encoding: _StrToStrEncoding, errors: str = "strict") -> str: ... # type: ignore[overload-overlap] @overload def encode(obj: str, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... + @overload def decode(obj: ReadableBuffer, encoding: _BytesToBytesEncoding, errors: str = "strict") -> bytes: ... # type: ignore[overload-overlap] @overload @@ -71,6 +68,7 @@ def decode( def decode(obj: str, encoding: Literal["hex", "hex_codec"], errors: str = "strict") -> bytes: ... @overload def decode(obj: ReadableBuffer, encoding: str = "utf-8", errors: str = "strict") -> str: ... + def lookup(encoding: str, /) -> codecs.CodecInfo: ... def charmap_build(map: str, /) -> _CharMap: ... def ascii_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... diff --git a/mypy/typeshed/stdlib/_collections_abc.pyi b/mypy/typeshed/stdlib/_collections_abc.pyi index 0fa81662dfbc1..6fc32078532e0 100644 --- a/mypy/typeshed/stdlib/_collections_abc.pyi +++ b/mypy/typeshed/stdlib/_collections_abc.pyi @@ -1,7 +1,7 @@ import sys from abc import abstractmethod from types import MappingProxyType -from typing import ( # noqa: Y022,Y038,UP035,Y057,RUF100 +from typing import ( # noqa: Y022,Y038,UP035,Y057 AbstractSet as Set, AsyncGenerator as AsyncGenerator, AsyncIterable as AsyncIterable, @@ -60,8 +60,9 @@ __all__ = [ "ValuesView", "Sequence", "MutableSequence", - "ByteString", ] +if sys.version_info < (3, 15): + __all__ += ["ByteString"] if sys.version_info >= (3, 12): __all__ += ["Buffer"] @@ -75,16 +76,15 @@ class dict_keys(KeysView[_KT_co], Generic[_KT_co, _VT_co]): # undocumented __hash__: ClassVar[None] # type: ignore[assignment] if sys.version_info >= (3, 13): def isdisjoint(self, other: Iterable[_KT_co], /) -> bool: ... - if sys.version_info >= (3, 10): - @property - def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... + + @property + def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... @final class dict_values(ValuesView[_VT_co], Generic[_KT_co, _VT_co]): # undocumented def __reversed__(self) -> Iterator[_VT_co]: ... - if sys.version_info >= (3, 10): - @property - def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... + @property + def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... @final class dict_items(ItemsView[_KT_co, _VT_co]): # undocumented @@ -93,9 +93,9 @@ class dict_items(ItemsView[_KT_co, _VT_co]): # undocumented __hash__: ClassVar[None] # type: ignore[assignment] if sys.version_info >= (3, 13): def isdisjoint(self, other: Iterable[tuple[_KT_co, _VT_co]], /) -> bool: ... - if sys.version_info >= (3, 10): - @property - def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... + + @property + def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ... if sys.version_info >= (3, 12): @runtime_checkable diff --git a/mypy/typeshed/stdlib/_contextvars.pyi b/mypy/typeshed/stdlib/_contextvars.pyi index 0ddeca7882cd1..56440884a1508 100644 --- a/mypy/typeshed/stdlib/_contextvars.pyi +++ b/mypy/typeshed/stdlib/_contextvars.pyi @@ -1,8 +1,8 @@ import sys from collections.abc import Callable, Iterator, Mapping from types import GenericAlias, TracebackType -from typing import Any, ClassVar, Generic, TypeVar, final, overload -from typing_extensions import ParamSpec, Self +from typing import Any, ClassVar, Generic, ParamSpec, TypeVar, final, overload +from typing_extensions import Self _T = TypeVar("_T") _D = TypeVar("_D") @@ -14,15 +14,18 @@ class ContextVar(Generic[_T]): def __new__(cls, name: str) -> Self: ... @overload def __new__(cls, name: str, *, default: _T) -> Self: ... + def __hash__(self) -> int: ... @property def name(self) -> str: ... + @overload def get(self) -> _T: ... @overload def get(self, default: _T, /) -> _T: ... @overload def get(self, default: _D, /) -> _D | _T: ... + def set(self, value: _T, /) -> Token[_T]: ... def reset(self, token: Token[_T], /) -> None: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @@ -49,12 +52,14 @@ def copy_context() -> Context: ... @final class Context(Mapping[ContextVar[Any], Any]): def __init__(self) -> None: ... + @overload def get(self, key: ContextVar[_T], default: None = None, /) -> _T | None: ... @overload def get(self, key: ContextVar[_T], default: _T, /) -> _T: ... @overload def get(self, key: ContextVar[_T], default: _D, /) -> _T | _D: ... + def run(self, callable: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> _T: ... def copy(self) -> Context: ... __hash__: ClassVar[None] # type: ignore[assignment] diff --git a/mypy/typeshed/stdlib/_csv.pyi b/mypy/typeshed/stdlib/_csv.pyi index ea90766afee66..d3702be78c3d5 100644 --- a/mypy/typeshed/stdlib/_csv.pyi +++ b/mypy/typeshed/stdlib/_csv.pyi @@ -2,8 +2,8 @@ import csv import sys from _typeshed import SupportsWrite from collections.abc import Iterable -from typing import Any, Final, Literal, type_check_only -from typing_extensions import Self, TypeAlias, disjoint_base +from typing import Any, Final, Literal, TypeAlias +from typing_extensions import Self, disjoint_base __version__: Final[str] @@ -47,47 +47,24 @@ class Dialect: strict: bool = False, ) -> Self: ... -if sys.version_info >= (3, 10): - # This class calls itself _csv.reader. - @disjoint_base - class Reader: - @property - def dialect(self) -> Dialect: ... - line_num: int - def __iter__(self) -> Self: ... - def __next__(self) -> list[str]: ... - - # This class calls itself _csv.writer. - @disjoint_base - class Writer: - @property - def dialect(self) -> Dialect: ... - if sys.version_info >= (3, 13): - def writerow(self, row: Iterable[Any], /) -> Any: ... - def writerows(self, rows: Iterable[Iterable[Any]], /) -> None: ... - else: - def writerow(self, row: Iterable[Any]) -> Any: ... - def writerows(self, rows: Iterable[Iterable[Any]]) -> None: ... - - # For the return types below. - # These aliases can be removed when typeshed drops support for 3.9. - _reader = Reader - _writer = Writer -else: - # This class is not exposed. It calls itself _csv.reader. - @type_check_only - class _reader: - @property - def dialect(self) -> Dialect: ... - line_num: int - def __iter__(self) -> Self: ... - def __next__(self) -> list[str]: ... +# This class calls itself _csv.reader. +@disjoint_base +class Reader: + @property + def dialect(self) -> Dialect: ... + line_num: int + def __iter__(self) -> Self: ... + def __next__(self) -> list[str]: ... - # This class is not exposed. It calls itself _csv.writer. - @type_check_only - class _writer: - @property - def dialect(self) -> Dialect: ... +# This class calls itself _csv.writer. +@disjoint_base +class Writer: + @property + def dialect(self) -> Dialect: ... + if sys.version_info >= (3, 13): + def writerow(self, row: Iterable[Any], /) -> Any: ... + def writerows(self, rows: Iterable[Iterable[Any]], /) -> None: ... + else: def writerow(self, row: Iterable[Any]) -> Any: ... def writerows(self, rows: Iterable[Iterable[Any]]) -> None: ... @@ -104,7 +81,7 @@ def writer( lineterminator: str = "\r\n", quoting: _QuotingType = 0, strict: bool = False, -) -> _writer: ... +) -> Writer: ... def reader( iterable: Iterable[str], /, @@ -118,7 +95,7 @@ def reader( lineterminator: str = "\r\n", quoting: _QuotingType = 0, strict: bool = False, -) -> _reader: ... +) -> Reader: ... def register_dialect( name: str, /, diff --git a/mypy/typeshed/stdlib/_ctypes.pyi b/mypy/typeshed/stdlib/_ctypes.pyi index 0e02092a361c9..1efb119263ef1 100644 --- a/mypy/typeshed/stdlib/_ctypes.pyi +++ b/mypy/typeshed/stdlib/_ctypes.pyi @@ -6,8 +6,8 @@ from abc import abstractmethod from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from ctypes import CDLL, ArgumentError as ArgumentError, c_void_p from types import GenericAlias -from typing import Any, ClassVar, Final, Generic, Literal, SupportsIndex, TypeVar, final, overload, type_check_only -from typing_extensions import Self, TypeAlias +from typing import Any, ClassVar, Final, Generic, Literal, SupportsIndex, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import Self _T = TypeVar("_T") _CT = TypeVar("_CT", bound=_CData) @@ -127,14 +127,17 @@ class _PyCPointerType(_CTypeBaseType): class _Pointer(_PointerLike, _CData, Generic[_CT], metaclass=_PyCPointerType): _type_: type[_CT] contents: _CT + @overload def __init__(self) -> None: ... @overload def __init__(self, arg: _CT) -> None: ... + @overload def __getitem__(self, key: int, /) -> Any: ... @overload def __getitem__(self, key: slice[SupportsIndex | None], /) -> list[Any]: ... + def __setitem__(self, key: int, value: Any, /) -> None: ... if sys.version_info < (3, 14): @@ -142,6 +145,7 @@ if sys.version_info < (3, 14): def POINTER(type: None, /) -> type[c_void_p]: ... @overload def POINTER(type: type[_CT], /) -> type[_Pointer[_CT]]: ... + def pointer(obj: _CT, /) -> _Pointer[_CT]: ... # This class is not exposed. It calls itself _ctypes.CArgObject. @@ -177,6 +181,7 @@ class CFuncPtr(_PointerLike, _CData, metaclass=_PyCFuncPtrType): errcheck: _ECT # Abstract attribute that must be defined on subclasses _flags_: ClassVar[int] + @overload def __new__(cls) -> Self: ... @overload @@ -209,10 +214,12 @@ if sys.version_info >= (3, 14): bit_offset: int bit_size: int is_anonymous: bool + @overload def __get__(self, instance: None, owner: builtins.type[Any] | None = None, /) -> Self: ... @overload def __get__(self, instance: Any, owner: builtins.type[Any] | None = None, /) -> _GetT: ... + def __set__(self, instance: Any, value: _SetT, /) -> None: ... _CField = CField @@ -223,16 +230,11 @@ else: class _CField(Generic[_CT, _GetT, _SetT]): offset: int size: int - if sys.version_info >= (3, 10): - @overload - def __get__(self, instance: None, owner: type[Any] | None = None, /) -> Self: ... - @overload - def __get__(self, instance: Any, owner: type[Any] | None = None, /) -> _GetT: ... - else: - @overload - def __get__(self, instance: None, owner: type[Any] | None, /) -> Self: ... - @overload - def __get__(self, instance: Any, owner: type[Any] | None, /) -> _GetT: ... + + @overload + def __get__(self, instance: None, owner: type[Any] | None = None, /) -> Self: ... + @overload + def __get__(self, instance: Any, owner: type[Any] | None = None, /) -> _GetT: ... def __set__(self, instance: Any, value: _SetT, /) -> None: ... @@ -315,11 +317,13 @@ class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): def _length_(self) -> int: ... @_length_.setter def _length_(self, value: int) -> None: ... + @property @abstractmethod def _type_(self) -> type[_CT]: ... @_type_.setter def _type_(self, value: type[_CT]) -> 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. @@ -335,14 +339,17 @@ class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): # This special behavior is not easy to model in a stub, so for now all places where # the array element type would belong are annotated with Any instead. def __init__(self, *args: Any) -> None: ... + @overload def __getitem__(self, key: int, /) -> Any: ... @overload def __getitem__(self, key: slice[SupportsIndex | None], /) -> list[Any]: ... + @overload def __setitem__(self, key: int, value: Any, /) -> None: ... @overload def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[Any], /) -> None: ... + def __iter__(self) -> Iterator[Any]: ... # Can't inherit from Sized because the metaclass conflict between # Sized and _CData prevents using _CDataMeta. diff --git a/mypy/typeshed/stdlib/_curses.pyi b/mypy/typeshed/stdlib/_curses.pyi index d4e4d48f4e20f..449cf75dad422 100644 --- a/mypy/typeshed/stdlib/_curses.pyi +++ b/mypy/typeshed/stdlib/_curses.pyi @@ -1,8 +1,7 @@ import sys from _typeshed import ReadOnlyBuffer, SupportsRead, SupportsWrite from curses import _ncurses_version -from typing import Any, Final, final, overload -from typing_extensions import TypeAlias +from typing import Any, Final, TypeAlias, final, overload # NOTE: This module is ordinarily only available on Unix, but the windows-curses # package makes it available on Windows as well with the same contents. @@ -96,13 +95,12 @@ BUTTON4_PRESSED: Final[int] BUTTON4_RELEASED: Final[int] BUTTON4_TRIPLE_CLICKED: Final[int] # Darwin ncurses doesn't provide BUTTON5_* constants prior to 3.12.10 and 3.13.3 -if sys.version_info >= (3, 10): - if sys.version_info >= (3, 12) or sys.platform != "darwin": - BUTTON5_PRESSED: Final[int] - BUTTON5_RELEASED: Final[int] - BUTTON5_CLICKED: Final[int] - BUTTON5_DOUBLE_CLICKED: Final[int] - BUTTON5_TRIPLE_CLICKED: Final[int] +if sys.version_info >= (3, 12) or sys.platform != "darwin": + BUTTON5_PRESSED: Final[int] + BUTTON5_RELEASED: Final[int] + BUTTON5_CLICKED: Final[int] + BUTTON5_DOUBLE_CLICKED: Final[int] + BUTTON5_TRIPLE_CLICKED: Final[int] BUTTON_ALT: Final[int] BUTTON_CTRL: Final[int] BUTTON_SHIFT: Final[int] @@ -300,9 +298,7 @@ def getsyx() -> tuple[int, int]: ... def getwin(file: SupportsRead[bytes], /) -> window: ... def halfdelay(tenths: int, /) -> None: ... def has_colors() -> bool: ... - -if sys.version_info >= (3, 10): - def has_extended_color_support() -> bool: ... +def has_extended_color_support() -> bool: ... if sys.version_info >= (3, 14): def assume_default_colors(fg: int, bg: int, /) -> None: ... @@ -379,18 +375,22 @@ class error(Exception): ... @final class window: # undocumented encoding: str + @overload def addch(self, ch: _ChType, attr: int = ...) -> None: ... @overload def addch(self, y: int, x: int, ch: _ChType, attr: int = ...) -> None: ... + @overload def addnstr(self, str: str, n: int, attr: int = ...) -> None: ... @overload def addnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... + @overload def addstr(self, str: str, attr: int = ...) -> None: ... @overload def addstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... + def attroff(self, attr: int, /) -> None: ... def attron(self, attr: int, /) -> None: ... def attrset(self, attr: int, /) -> None: ... @@ -407,10 +407,12 @@ class window: # undocumented bl: _ChType = ..., br: _ChType = ..., ) -> None: ... + @overload def box(self) -> None: ... @overload def box(self, vertch: _ChType = 0, horch: _ChType = 0) -> None: ... + @overload def chgat(self, attr: int) -> None: ... @overload @@ -419,39 +421,49 @@ class window: # undocumented def chgat(self, y: int, x: int, attr: int) -> None: ... @overload def chgat(self, y: int, x: int, num: int, attr: int) -> None: ... + def clear(self) -> None: ... def clearok(self, yes: int) -> None: ... def clrtobot(self) -> None: ... def clrtoeol(self) -> None: ... def cursyncup(self) -> None: ... + @overload def delch(self) -> None: ... @overload def delch(self, y: int, x: int) -> None: ... + def deleteln(self) -> None: ... + @overload def derwin(self, begin_y: int, begin_x: int) -> window: ... @overload def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ... + def echochar(self, ch: _ChType, attr: int = 0, /) -> None: ... def enclose(self, y: int, x: int, /) -> bool: ... def erase(self) -> None: ... def getbegyx(self) -> tuple[int, int]: ... def getbkgd(self) -> tuple[int, int]: ... + @overload def getch(self) -> int: ... @overload def getch(self, y: int, x: int) -> int: ... + @overload def get_wch(self) -> int | str: ... @overload def get_wch(self, y: int, x: int) -> int | str: ... + @overload def getkey(self) -> str: ... @overload def getkey(self, y: int, x: int) -> str: ... + def getmaxyx(self) -> tuple[int, int]: ... def getparyx(self) -> tuple[int, int]: ... + @overload def getstr(self) -> bytes: ... @overload @@ -460,36 +472,46 @@ class window: # undocumented def getstr(self, y: int, x: int) -> bytes: ... @overload def getstr(self, y: int, x: int, n: int) -> bytes: ... + def getyx(self) -> tuple[int, int]: ... + @overload def hline(self, ch: _ChType, n: int) -> None: ... @overload def hline(self, y: int, x: int, ch: _ChType, n: int) -> None: ... + def idcok(self, flag: bool) -> None: ... def idlok(self, yes: bool) -> None: ... def immedok(self, flag: bool) -> None: ... + @overload def inch(self) -> int: ... @overload def inch(self, y: int, x: int) -> int: ... + @overload def insch(self, ch: _ChType, attr: int = ...) -> None: ... @overload def insch(self, y: int, x: int, ch: _ChType, attr: int = ...) -> None: ... + def insdelln(self, nlines: int) -> None: ... def insertln(self) -> None: ... + @overload def insnstr(self, str: str, n: int, attr: int = ...) -> None: ... @overload def insnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... + @overload def insstr(self, str: str, attr: int = ...) -> None: ... @overload def insstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... + @overload def instr(self, n: int = 2047) -> bytes: ... @overload def instr(self, y: int, x: int, n: int = 2047) -> bytes: ... + def is_linetouched(self, line: int, /) -> bool: ... def is_wintouched(self) -> bool: ... def keypad(self, yes: bool, /) -> None: ... @@ -499,43 +521,52 @@ class window: # undocumented def mvwin(self, new_y: int, new_x: int) -> None: ... def nodelay(self, yes: bool) -> None: ... def notimeout(self, yes: bool) -> None: ... + @overload def noutrefresh(self) -> None: ... @overload def noutrefresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... + @overload def overlay(self, destwin: window) -> None: ... @overload def overlay( self, destwin: window, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int ) -> None: ... + @overload def overwrite(self, destwin: window) -> None: ... @overload def overwrite( self, destwin: window, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int ) -> None: ... + def putwin(self, file: SupportsWrite[bytes], /) -> None: ... def redrawln(self, beg: int, num: int, /) -> None: ... def redrawwin(self) -> None: ... + @overload def refresh(self) -> None: ... @overload def refresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... + def resize(self, nlines: int, ncols: int) -> None: ... def scroll(self, lines: int = 1) -> None: ... def scrollok(self, flag: bool) -> None: ... def setscrreg(self, top: int, bottom: int, /) -> None: ... def standend(self) -> None: ... def standout(self) -> None: ... + @overload def subpad(self, begin_y: int, begin_x: int) -> window: ... @overload def subpad(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ... + @overload def subwin(self, begin_y: int, begin_x: int) -> window: ... @overload def subwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ... + def syncdown(self) -> None: ... def syncok(self, flag: bool) -> None: ... def syncup(self) -> None: ... @@ -543,6 +574,7 @@ class window: # undocumented def touchline(self, start: int, count: int, changed: bool = True) -> None: ... def touchwin(self) -> None: ... def untouchwin(self) -> None: ... + @overload def vline(self, ch: _ChType, n: int) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/_dbm.pyi b/mypy/typeshed/stdlib/_dbm.pyi index 222c3ffcb246b..29d9b4c2fadca 100644 --- a/mypy/typeshed/stdlib/_dbm.pyi +++ b/mypy/typeshed/stdlib/_dbm.pyi @@ -1,8 +1,8 @@ import sys from _typeshed import ReadOnlyBuffer, StrOrBytesPath from types import TracebackType -from typing import Final, TypeVar, final, overload, type_check_only -from typing_extensions import Self, TypeAlias +from typing import Final, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import Self if sys.platform != "win32": _T = TypeVar("_T") @@ -28,10 +28,12 @@ if sys.platform != "win32": def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... + @overload def get(self, k: _KeyType, /) -> bytes | None: ... @overload def get(self, k: _KeyType, default: _T, /) -> bytes | _T: ... + def keys(self) -> list[bytes]: ... def setdefault(self, k: _KeyType, default: _ValueType = b"", /) -> bytes: ... # This isn't true, but the class can't be instantiated. See #13024 diff --git a/mypy/typeshed/stdlib/_decimal.pyi b/mypy/typeshed/stdlib/_decimal.pyi index 3cfe8944dfaf4..75d5be277f959 100644 --- a/mypy/typeshed/stdlib/_decimal.pyi +++ b/mypy/typeshed/stdlib/_decimal.pyi @@ -19,13 +19,14 @@ from decimal import ( Underflow as Underflow, _ContextManager, ) -from typing import Final -from typing_extensions import TypeAlias +from typing import Final, TypeAlias _TrapType: TypeAlias = type[DecimalException] __version__: Final[str] __libmpdec_version__: Final[str] +if sys.version_info >= (3, 15): + SPEC_VERSION: Final[str] ROUND_DOWN: Final = "ROUND_DOWN" ROUND_HALF_UP: Final = "ROUND_HALF_UP" diff --git a/mypy/typeshed/stdlib/_frozen_importlib.pyi b/mypy/typeshed/stdlib/_frozen_importlib.pyi index 58db64a016f34..172da4522d8ff 100644 --- a/mypy/typeshed/stdlib/_frozen_importlib.pyi +++ b/mypy/typeshed/stdlib/_frozen_importlib.pyi @@ -74,16 +74,11 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader) "The module spec is now used by the import machinery to generate a module repr." ) def module_repr(module: types.ModuleType) -> str: ... - if sys.version_info >= (3, 10): - @staticmethod - def create_module(spec: ModuleSpec) -> types.ModuleType | None: ... - @staticmethod - def exec_module(module: types.ModuleType) -> None: ... - else: - @classmethod - def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: ... - @classmethod - def exec_module(cls, module: types.ModuleType) -> None: ... + + @staticmethod + def create_module(spec: ModuleSpec) -> types.ModuleType | None: ... + @staticmethod + def exec_module(module: types.ModuleType) -> None: ... class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): # MetaPathFinder @@ -113,12 +108,8 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): "The module spec is now used by the import machinery to generate a module repr." ) def module_repr(m: types.ModuleType) -> str: ... - if sys.version_info >= (3, 10): - @staticmethod - def create_module(spec: ModuleSpec) -> types.ModuleType | None: ... - else: - @classmethod - def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: ... + @staticmethod + def create_module(spec: ModuleSpec) -> types.ModuleType | None: ... @staticmethod def exec_module(module: types.ModuleType) -> None: ... diff --git a/mypy/typeshed/stdlib/_frozen_importlib_external.pyi b/mypy/typeshed/stdlib/_frozen_importlib_external.pyi index 660cee6e84ec8..907e8def93806 100644 --- a/mypy/typeshed/stdlib/_frozen_importlib_external.pyi +++ b/mypy/typeshed/stdlib/_frozen_importlib_external.pyi @@ -1,19 +1,16 @@ import _ast -import _io import importlib.abc import importlib.machinery +import importlib.readers import sys import types from _typeshed import ReadableBuffer, StrOrBytesPath, StrPath from _typeshed.importlib import LoaderProtocol -from collections.abc import Callable, Iterable, Iterator, Mapping, MutableSequence, Sequence +from collections.abc import Callable, Iterable, Mapping, MutableSequence, Sequence from importlib.machinery import ModuleSpec from importlib.metadata import DistributionFinder, PathDistribution from typing import Any, Final, Literal, overload -from typing_extensions import Self, deprecated - -if sys.version_info >= (3, 10): - import importlib.readers +from typing_extensions import deprecated if sys.platform == "win32": path_separators: Literal["\\/"] @@ -33,6 +30,7 @@ MAGIC_NUMBER: Final[bytes] def cache_from_source(path: StrPath, debug_override: bool, *, optimization: None = None) -> str: ... @overload def cache_from_source(path: StrPath, debug_override: None = None, *, optimization: Any | None = None) -> str: ... + def source_from_cache(path: StrPath) -> str: ... def decode_source(source_bytes: ReadableBuffer) -> str: ... def spec_from_file_location( @@ -42,6 +40,7 @@ def spec_from_file_location( loader: LoaderProtocol | None = None, submodule_search_locations: list[str] | None = ..., ) -> importlib.machinery.ModuleSpec | None: ... + @deprecated( "Deprecated since Python 3.6. Use site configuration instead. " "Future versions of Python may not enable this finder by default." @@ -58,19 +57,10 @@ class WindowsRegistryFinder(importlib.abc.MetaPathFinder): ) -> ModuleSpec | None: ... class PathFinder(importlib.abc.MetaPathFinder): - if sys.version_info >= (3, 10): - @staticmethod - def invalidate_caches() -> None: ... - else: - @classmethod - def invalidate_caches(cls) -> None: ... - if sys.version_info >= (3, 10): - @staticmethod - def find_distributions(context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... - else: - @classmethod - def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... - + @staticmethod + def invalidate_caches() -> None: ... + @staticmethod + def find_distributions(context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... @classmethod def find_spec( cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None @@ -117,14 +107,7 @@ class FileLoader: def get_data(self, path: str) -> bytes: ... def get_filename(self, fullname: str | None = None) -> str: ... def load_module(self, fullname: str | None = None) -> types.ModuleType: ... - if sys.version_info >= (3, 10): - def get_resource_reader(self, name: str | None = None) -> importlib.readers.FileReader: ... - else: - def get_resource_reader(self, name: str | None = None) -> Self | None: ... - def open_resource(self, resource: str) -> _io.FileIO: ... - def resource_path(self, resource: str) -> str: ... - def is_resource(self, name: str) -> bool: ... - def contents(self) -> Iterator[str]: ... + def get_resource_reader(self, name: str | None = None) -> importlib.readers.FileReader: ... class SourceFileLoader(importlib.abc.FileLoader, FileLoader, importlib.abc.SourceLoader, SourceLoader): # type: ignore[misc] # incompatible method arguments in base classes def set_data(self, path: str, data: ReadableBuffer, *, _mode: int = 0o666) -> None: ... @@ -183,24 +166,15 @@ else: def get_code(self, fullname: str) -> types.CodeType: ... def create_module(self, spec: ModuleSpec) -> None: ... def exec_module(self, module: types.ModuleType) -> None: ... - if sys.version_info >= (3, 10): - @deprecated("Deprecated since Python 3.10; will be removed in Python 3.15. Use `exec_module()` instead.") - def load_module(self, fullname: str) -> types.ModuleType: ... - @staticmethod - @deprecated( - "Deprecated since Python 3.4; removed in Python 3.12. " - "The module spec is now used by the import machinery to generate a module repr." - ) - def module_repr(module: types.ModuleType) -> str: ... - def get_resource_reader(self, module: types.ModuleType) -> importlib.readers.NamespaceReader: ... - else: - def load_module(self, fullname: str) -> types.ModuleType: ... - @classmethod - @deprecated( - "Deprecated since Python 3.4; removed in Python 3.12. " - "The module spec is now used by the import machinery to generate a module repr." - ) - def module_repr(cls, module: types.ModuleType) -> str: ... + @deprecated("Deprecated since Python 3.10; will be removed in Python 3.15. Use `exec_module()` instead.") + def load_module(self, fullname: str) -> types.ModuleType: ... + @staticmethod + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "The module spec is now used by the import machinery to generate a module repr." + ) + def module_repr(module: types.ModuleType) -> str: ... + def get_resource_reader(self, module: types.ModuleType) -> importlib.readers.NamespaceReader: ... if sys.version_info >= (3, 13): class AppleFrameworkLoader(ExtensionFileLoader, importlib.abc.ExecutionLoader): ... diff --git a/mypy/typeshed/stdlib/_gdbm.pyi b/mypy/typeshed/stdlib/_gdbm.pyi index 2cb5fba29dfa1..b7a01a4531205 100644 --- a/mypy/typeshed/stdlib/_gdbm.pyi +++ b/mypy/typeshed/stdlib/_gdbm.pyi @@ -1,8 +1,8 @@ import sys from _typeshed import ReadOnlyBuffer, StrOrBytesPath from types import TracebackType -from typing import TypeVar, overload, type_check_only -from typing_extensions import Self, TypeAlias +from typing import TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self if sys.platform != "win32": _T = TypeVar("_T") @@ -32,10 +32,12 @@ if sys.platform != "win32": def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... + @overload def get(self, k: _KeyType) -> bytes | None: ... @overload def get(self, k: _KeyType, default: _T) -> bytes | _T: ... + def keys(self) -> list[bytes]: ... def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... # Don't exist at runtime diff --git a/mypy/typeshed/stdlib/_hashlib.pyi b/mypy/typeshed/stdlib/_hashlib.pyi index 03c1eef3be3ff..b98edc5757c39 100644 --- a/mypy/typeshed/stdlib/_hashlib.pyi +++ b/mypy/typeshed/stdlib/_hashlib.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import ReadableBuffer from collections.abc import Callable from types import ModuleType -from typing import AnyStr, Protocol, final, overload, type_check_only -from typing_extensions import Self, TypeAlias, disjoint_base +from typing import AnyStr, Protocol, TypeAlias, final, overload, type_check_only +from typing_extensions import Self, disjoint_base _DigestMod: TypeAlias = str | Callable[[], _HashObject] | ModuleType | None @@ -35,8 +35,7 @@ class HASH: def hexdigest(self) -> str: ... def update(self, obj: ReadableBuffer, /) -> None: ... -if sys.version_info >= (3, 10): - class UnsupportedDigestmodError(ValueError): ... +class UnsupportedDigestmodError(ValueError): ... class HASHXOF(HASH): def digest(self, length: int) -> bytes: ... # type: ignore[override] @@ -59,8 +58,9 @@ class HMAC: def compare_digest(a: ReadableBuffer, b: ReadableBuffer, /) -> bool: ... @overload def compare_digest(a: AnyStr, b: AnyStr, /) -> bool: ... + def get_fips_mode() -> int: ... -def hmac_new(key: bytes | bytearray, msg: ReadableBuffer = b"", digestmod: _DigestMod = None) -> HMAC: ... +def hmac_new(key: ReadableBuffer, msg: ReadableBuffer = b"", digestmod: _DigestMod = None) -> HMAC: ... if sys.version_info >= (3, 13): def new( @@ -118,7 +118,7 @@ else: def openssl_shake_128(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASHXOF: ... def openssl_shake_256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASHXOF: ... -def hmac_digest(key: bytes | bytearray, msg: ReadableBuffer, digest: str) -> bytes: ... +def hmac_digest(key: ReadableBuffer, msg: ReadableBuffer, digest: str) -> bytes: ... def pbkdf2_hmac( hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: int | None = None ) -> bytes: ... diff --git a/mypy/typeshed/stdlib/_interpqueues.pyi b/mypy/typeshed/stdlib/_interpqueues.pyi index c9323b106f3dc..94605e4c0dda5 100644 --- a/mypy/typeshed/stdlib/_interpqueues.pyi +++ b/mypy/typeshed/stdlib/_interpqueues.pyi @@ -1,5 +1,5 @@ -from typing import Any, Literal, SupportsIndex -from typing_extensions import TypeAlias +import sys +from typing import Any, Literal, SupportsIndex, TypeAlias _UnboundOp: TypeAlias = Literal[1, 2, 3] @@ -7,7 +7,13 @@ class QueueError(RuntimeError): ... class QueueNotFoundError(QueueError): ... def bind(qid: SupportsIndex) -> None: ... -def create(maxsize: SupportsIndex, fmt: SupportsIndex, unboundop: _UnboundOp) -> int: ... + +if sys.version_info >= (3, 15): + def create(maxsize: SupportsIndex, unboundop: SupportsIndex = -1, fallback: SupportsIndex = -1) -> int: ... + +else: + def create(maxsize: SupportsIndex, fmt: SupportsIndex, unboundop: _UnboundOp) -> int: ... + def destroy(qid: SupportsIndex) -> None: ... def get(qid: SupportsIndex) -> tuple[Any, int, _UnboundOp | None]: ... def get_count(qid: SupportsIndex) -> int: ... @@ -15,5 +21,11 @@ def get_maxsize(qid: SupportsIndex) -> int: ... def get_queue_defaults(qid: SupportsIndex) -> tuple[int, _UnboundOp]: ... def is_full(qid: SupportsIndex) -> bool: ... def list_all() -> list[tuple[int, int, _UnboundOp]]: ... -def put(qid: SupportsIndex, obj: Any, fmt: SupportsIndex, unboundop: _UnboundOp) -> None: ... + +if sys.version_info >= (3, 15): + def put(qid: SupportsIndex, obj: Any, unboundop: SupportsIndex = -1, fallback: SupportsIndex = -1) -> None: ... + +else: + def put(qid: SupportsIndex, obj: Any, fmt: SupportsIndex, unboundop: _UnboundOp) -> None: ... + def release(qid: SupportsIndex) -> None: ... diff --git a/mypy/typeshed/stdlib/_interpreters.pyi b/mypy/typeshed/stdlib/_interpreters.pyi index 8e097efad618a..3885669278f51 100644 --- a/mypy/typeshed/stdlib/_interpreters.pyi +++ b/mypy/typeshed/stdlib/_interpreters.pyi @@ -1,7 +1,7 @@ import types from collections.abc import Callable -from typing import Any, Final, Literal, SupportsIndex, TypeVar, overload -from typing_extensions import TypeAlias, disjoint_base +from typing import Any, Final, Literal, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import disjoint_base _R = TypeVar("_R") @@ -47,6 +47,7 @@ def set___main___attrs(id: SupportsIndex, updates: _SharedDict, *, restrict: boo def incref(id: SupportsIndex, *, implieslink: bool = False, restrict: bool = False) -> None: ... def decref(id: SupportsIndex, *, restrict: bool = False) -> None: ... def is_shareable(obj: object) -> bool: ... + @overload def capture_exception(exc: BaseException) -> types.SimpleNamespace: ... @overload diff --git a/mypy/typeshed/stdlib/_io.pyi b/mypy/typeshed/stdlib/_io.pyi index ed8eff2759a98..5e216123be984 100644 --- a/mypy/typeshed/stdlib/_io.pyi +++ b/mypy/typeshed/stdlib/_io.pyi @@ -163,13 +163,39 @@ class BufferedReader(BufferedIOBase, _BufferedIOBase, BinaryIO, Generic[_Buffere def seek(self, target: int, whence: int = 0, /) -> int: ... def truncate(self, pos: int | None = None, /) -> int: ... +@type_check_only +class _BufferedWriterStream(Protocol): + def write(self, b: WriteableBuffer, /) -> int | None: ... + def seek(self, pos: int, whence: int, /) -> int: ... + def tell(self) -> int: ... + def truncate(self, size: int, /) -> int: ... + def flush(self) -> object: ... + def close(self) -> object: ... + @property + def closed(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + + # The following methods just pass through to the underlying stream. Since + # not all streams support them, they are marked as optional here, and will + # raise an AttributeError if called on a stream that does not support them. + + # @property + # def name(self) -> Any: ... # Type is inconsistent between the various I/O types. + # @property + # def mode(self) -> str: ... + # def fileno(self) -> int: ... + # def isatty(self) -> bool: ... + +_BufferedWriterStreamT = TypeVar("_BufferedWriterStreamT", bound=_BufferedWriterStream, default=_BufferedWriterStream) + @disjoint_base -class BufferedWriter(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes - raw: RawIOBase +class BufferedWriter(BufferedIOBase, _BufferedIOBase, BinaryIO, Generic[_BufferedWriterStreamT]): # type: ignore[misc] # incompatible definitions of writelines in the base classes + raw: _BufferedWriterStreamT if sys.version_info >= (3, 14): - def __init__(self, raw: RawIOBase, buffer_size: int = 131072) -> None: ... + def __init__(self, raw: _BufferedWriterStreamT, buffer_size: int = 131072) -> None: ... else: - def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ... + def __init__(self, raw: _BufferedWriterStreamT, buffer_size: int = 8192) -> None: ... def write(self, buffer: ReadableBuffer, /) -> int: ... def seek(self, target: int, whence: int = 0, /) -> int: ... @@ -190,11 +216,15 @@ class BufferedRandom(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore def truncate(self, pos: int | None = None, /) -> int: ... @disjoint_base -class BufferedRWPair(BufferedIOBase, _BufferedIOBase, Generic[_BufferedReaderStreamT]): +class BufferedRWPair(BufferedIOBase, _BufferedIOBase, Generic[_BufferedReaderStreamT, _BufferedWriterStreamT]): if sys.version_info >= (3, 14): - def __init__(self, reader: _BufferedReaderStreamT, writer: RawIOBase, buffer_size: int = 131072, /) -> None: ... + def __init__( + self, reader: _BufferedReaderStreamT, writer: _BufferedWriterStreamT, buffer_size: int = 131072, / + ) -> None: ... else: - def __init__(self, reader: _BufferedReaderStreamT, writer: RawIOBase, buffer_size: int = 8192, /) -> None: ... + def __init__( + self, reader: _BufferedReaderStreamT, writer: _BufferedWriterStreamT, buffer_size: int = 8192, / + ) -> None: ... def peek(self, size: int = 0, /) -> bytes: ... @@ -294,8 +324,7 @@ class IncrementalNewlineDecoder: def reset(self) -> None: ... def setstate(self, state: tuple[bytes, int], /) -> None: ... -if sys.version_info >= (3, 10): - @overload - def text_encoding(encoding: None, stacklevel: int = 2, /) -> Literal["locale", "utf-8"]: ... - @overload - def text_encoding(encoding: _S, stacklevel: int = 2, /) -> _S: ... +@overload +def text_encoding(encoding: None, stacklevel: int = 2, /) -> Literal["locale", "utf-8"]: ... +@overload +def text_encoding(encoding: _S, stacklevel: int = 2, /) -> _S: ... diff --git a/mypy/typeshed/stdlib/_json.pyi b/mypy/typeshed/stdlib/_json.pyi index 4a77e5be594ab..c6c2c97e83aa9 100644 --- a/mypy/typeshed/stdlib/_json.pyi +++ b/mypy/typeshed/stdlib/_json.pyi @@ -1,3 +1,4 @@ +import sys from collections.abc import Callable from typing import Any, final from typing_extensions import Self @@ -36,6 +37,8 @@ class make_encoder: @final class make_scanner: + if sys.version_info >= (3, 15): + array_hook: Any object_hook: Any object_pairs_hook: Any parse_int: Any @@ -48,4 +51,9 @@ class make_scanner: def encode_basestring(s: str, /) -> str: ... def encode_basestring_ascii(s: str, /) -> str: ... -def scanstring(string: str, end: int, strict: bool = True) -> tuple[str, int]: ... + +if sys.version_info >= (3, 15): + def scanstring(pystr: str, end: int, strict: bool = True, /) -> tuple[str, int]: ... + +else: + def scanstring(string: str, end: int, strict: bool = True) -> tuple[str, int]: ... diff --git a/mypy/typeshed/stdlib/_lsprof.pyi b/mypy/typeshed/stdlib/_lsprof.pyi index 4f6d98b8ffb61..d04c2a74ee07b 100644 --- a/mypy/typeshed/stdlib/_lsprof.pyi +++ b/mypy/typeshed/stdlib/_lsprof.pyi @@ -1,4 +1,3 @@ -import sys from _typeshed import structseq from collections.abc import Callable from types import CodeType @@ -17,8 +16,7 @@ class Profiler: @final class profiler_entry(structseq[Any], tuple[CodeType | str, int, int, float, float, list[profiler_subentry]]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime", "calls") + __match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime", "calls") code: CodeType | str callcount: int reccallcount: int @@ -28,8 +26,7 @@ class profiler_entry(structseq[Any], tuple[CodeType | str, int, int, float, floa @final class profiler_subentry(structseq[Any], tuple[CodeType | str, int, int, float, float]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime") + __match_args__: Final = ("code", "callcount", "reccallcount", "totaltime", "inlinetime") code: CodeType | str callcount: int reccallcount: int diff --git a/mypy/typeshed/stdlib/_lzma.pyi b/mypy/typeshed/stdlib/_lzma.pyi index b38dce9fadedf..83cd8fd756b9a 100644 --- a/mypy/typeshed/stdlib/_lzma.pyi +++ b/mypy/typeshed/stdlib/_lzma.pyi @@ -1,8 +1,8 @@ import sys from _typeshed import ReadableBuffer from collections.abc import Mapping, Sequence -from typing import Any, Final, final -from typing_extensions import Self, TypeAlias +from typing import Any, Final, TypeAlias, final +from typing_extensions import Self _FilterChain: TypeAlias = Sequence[Mapping[str, Any]] diff --git a/mypy/typeshed/stdlib/_markupbase.pyi b/mypy/typeshed/stdlib/_markupbase.pyi index 597bd09b700b0..acc3ccac7188c 100644 --- a/mypy/typeshed/stdlib/_markupbase.pyi +++ b/mypy/typeshed/stdlib/_markupbase.pyi @@ -1,6 +1,3 @@ -import sys -from typing import Any - class ParserBase: def reset(self) -> None: ... def getpos(self) -> tuple[int, int]: ... @@ -9,8 +6,5 @@ class ParserBase: def parse_declaration(self, i: int) -> int: ... # undocumented def parse_marked_section(self, i: int, report: bool = True) -> int: ... # undocumented def updatepos(self, i: int, j: int) -> int: ... # undocumented - if sys.version_info < (3, 10): - # Removed from ParserBase: https://bugs.python.org/issue31844 - def error(self, message: str) -> Any: ... # undocumented lineno: int # undocumented offset: int # undocumented diff --git a/mypy/typeshed/stdlib/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi index 8c705065bde7d..29a6d70572028 100644 --- a/mypy/typeshed/stdlib/_operator.pyi +++ b/mypy/typeshed/stdlib/_operator.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import SupportsGetItem from collections.abc import Callable, Container, Iterable, MutableMapping, MutableSequence, Sequence from operator import attrgetter as attrgetter, itemgetter as itemgetter, methodcaller as methodcaller -from typing import Any, AnyStr, Protocol, SupportsAbs, SupportsIndex, TypeVar, overload, type_check_only -from typing_extensions import ParamSpec, TypeAlias, TypeIs +from typing import Any, AnyStr, ParamSpec, Protocol, SupportsAbs, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import TypeIs _R = TypeVar("_R") _T = TypeVar("_T") @@ -79,23 +79,28 @@ 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: ... + @overload def delitem(a: MutableSequence[Any], b: int, /) -> None: ... @overload def delitem(a: MutableSequence[Any], b: slice[int | None], /) -> None: ... @overload def delitem(a: MutableMapping[_K, Any], b: _K, /) -> None: ... + @overload def getitem(a: Sequence[_T], b: slice[int | None], /) -> Sequence[_T]: ... @overload def getitem(a: SupportsGetItem[_K, _V], b: _K, /) -> _V: ... + def indexOf(a: Iterable[_T], b: _T, /) -> int: ... + @overload def setitem(a: MutableSequence[_T], b: int, c: _T, /) -> None: ... @overload def setitem(a: MutableSequence[_T], b: slice[int | None], c: Sequence[_T], /) -> None: ... @overload def setitem(a: MutableMapping[_K, _V], b: _K, c: _V, /) -> None: ... + def length_hint(obj: object, default: int = 0, /) -> int: ... def iadd(a, b, /): ... def iand(a, b, /): ... diff --git a/mypy/typeshed/stdlib/_pickle.pyi b/mypy/typeshed/stdlib/_pickle.pyi index 4294de4c2c7fe..f8411c6abc4b8 100644 --- a/mypy/typeshed/stdlib/_pickle.pyi +++ b/mypy/typeshed/stdlib/_pickle.pyi @@ -1,8 +1,8 @@ from _typeshed import ReadableBuffer, SupportsWrite from collections.abc import Callable, Iterable, Iterator, Mapping from pickle import PickleBuffer as PickleBuffer -from typing import Any, Protocol, type_check_only -from typing_extensions import TypeAlias, disjoint_base +from typing import Any, Protocol, TypeAlias, type_check_only +from typing_extensions import disjoint_base @type_check_only class _ReadableFileobj(Protocol): @@ -69,10 +69,12 @@ class Pickler: fix_imports: bool = True, buffer_callback: _BufferCallback = None, ) -> None: ... + @property def memo(self) -> PicklerMemoProxy: ... @memo.setter def memo(self, value: PicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ... + def dump(self, obj: Any, /) -> None: ... def clear_memo(self) -> None: ... @@ -99,10 +101,12 @@ class Unpickler: errors: str = "strict", buffers: Iterable[Any] | None = (), ) -> None: ... + @property def memo(self) -> UnpicklerMemoProxy: ... @memo.setter def memo(self, value: UnpicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ... + def load(self) -> Any: ... def find_class(self, module_name: str, global_name: str, /) -> Any: ... diff --git a/mypy/typeshed/stdlib/_pydecimal.pyi b/mypy/typeshed/stdlib/_pydecimal.pyi index a6723f749da6d..9fabcc6400969 100644 --- a/mypy/typeshed/stdlib/_pydecimal.pyi +++ b/mypy/typeshed/stdlib/_pydecimal.pyi @@ -45,3 +45,6 @@ __all__ = [ if sys.version_info >= (3, 14): __all__ += ["IEEEContext", "IEEE_CONTEXT_MAX_BITS"] + +if sys.version_info >= (3, 15): + __all__ += ["SPEC_VERSION"] diff --git a/mypy/typeshed/stdlib/_random.pyi b/mypy/typeshed/stdlib/_random.pyi index ac00fdfb7272b..e333b00d1084e 100644 --- a/mypy/typeshed/stdlib/_random.pyi +++ b/mypy/typeshed/stdlib/_random.pyi @@ -1,16 +1,12 @@ -import sys -from typing_extensions import Self, TypeAlias, disjoint_base +from typing import TypeAlias +from typing_extensions import disjoint_base # Actually Tuple[(int,) * 625] _State: TypeAlias = tuple[int, ...] @disjoint_base class Random: - if sys.version_info >= (3, 10): - def __init__(self, seed: object = ..., /) -> None: ... - else: - def __new__(self, seed: object = ..., /) -> Self: ... - + def __init__(self, seed: object = ..., /) -> None: ... def seed(self, n: object = None, /) -> None: ... def getstate(self) -> _State: ... def setstate(self, state: _State, /) -> None: ... diff --git a/mypy/typeshed/stdlib/_remote_debugging.pyi b/mypy/typeshed/stdlib/_remote_debugging.pyi new file mode 100644 index 0000000000000..b001962aad7bf --- /dev/null +++ b/mypy/typeshed/stdlib/_remote_debugging.pyi @@ -0,0 +1,183 @@ +from _typeshed import StrOrBytesPath, structseq +from collections.abc import Callable +from typing import Final, TypeAlias, final +from typing_extensions import Self + +_Location: TypeAlias = tuple[int, int, int, int] | LocationInfo | None +_Frame: TypeAlias = tuple[str, _Location, str, int | None] | FrameInfo +_Stats: TypeAlias = dict[str, int | float] + +PROCESS_VM_READV_SUPPORTED: Final[int] +THREAD_STATUS_GIL_REQUESTED: Final[int] +THREAD_STATUS_HAS_EXCEPTION: Final[int] +THREAD_STATUS_HAS_GIL: Final[int] +THREAD_STATUS_MAIN_THREAD: Final[int] +THREAD_STATUS_ON_CPU: Final[int] +THREAD_STATUS_UNKNOWN: Final[int] + +@final +class LocationInfo(structseq[int], tuple[int, int, int, int]): + __match_args__: Final = ("lineno", "end_lineno", "col_offset", "end_col_offset") + @property + def lineno(self) -> int: ... + @property + def end_lineno(self) -> int: ... + @property + def col_offset(self) -> int: ... + @property + def end_col_offset(self) -> int: ... + +@final +class FrameInfo(structseq[object], tuple[str, _Location, str, int | None]): + __match_args__: Final = ("filename", "location", "funcname", "opcode") + @property + def filename(self) -> str: ... + @property + def location(self) -> _Location: ... + @property + def funcname(self) -> str: ... + @property + def opcode(self) -> int | None: ... + +@final +class CoroInfo(structseq[object], tuple[list[_Frame], int | str]): + __match_args__: Final = ("call_stack", "task_name") + @property + def call_stack(self) -> list[_Frame]: ... + @property + def task_name(self) -> int | str: ... + +@final +class TaskInfo(structseq[object], tuple[int, str, list[CoroInfo], list[CoroInfo]]): + __match_args__: Final = ("task_id", "task_name", "coroutine_stack", "awaited_by") + @property + def task_id(self) -> int: ... + @property + def task_name(self) -> str: ... + @property + def coroutine_stack(self) -> list[CoroInfo]: ... + @property + def awaited_by(self) -> list[CoroInfo]: ... + +@final +class ThreadInfo(structseq[object], tuple[int, int, list[_Frame]]): + __match_args__: Final = ("thread_id", "status", "frame_info") + @property + def thread_id(self) -> int: ... + @property + def status(self) -> int: ... + @property + def frame_info(self) -> list[_Frame]: ... + +@final +class InterpreterInfo(structseq[object], tuple[int, list[ThreadInfo]]): + __match_args__: Final = ("interpreter_id", "threads") + @property + def interpreter_id(self) -> int: ... + @property + def threads(self) -> list[ThreadInfo]: ... + +@final +class AwaitedInfo(structseq[object], tuple[int, list[TaskInfo]]): + __match_args__: Final = ("thread_id", "awaited_by") + @property + def thread_id(self) -> int: ... + @property + def awaited_by(self) -> list[TaskInfo]: ... + +@final +class GCStatsInfo(structseq[object], tuple[int, int, int, int, int, int, int, int, int, float]): + __match_args__: Final = ( + "gen", + "iid", + "ts_start", + "ts_stop", + "collections", + "collected", + "uncollectable", + "candidates", + "heap_size", + "duration", + ) + @property + def gen(self) -> int: ... + @property + def iid(self) -> int: ... + @property + def ts_start(self) -> int: ... + @property + def ts_stop(self) -> int: ... + @property + def collections(self) -> int: ... + @property + def collected(self) -> int: ... + @property + def uncollectable(self) -> int: ... + @property + def candidates(self) -> int: ... + @property + def heap_size(self) -> int: ... + @property + def duration(self) -> float: ... + +@final +class RemoteUnwinder: + def __init__( + self, + pid: int, + *, + all_threads: bool = False, + only_active_thread: bool = False, + mode: int = 0, + debug: bool = False, + skip_non_matching_threads: bool = True, + native: bool = False, + gc: bool = False, + opcodes: bool = False, + cache_frames: bool = False, + stats: bool = False, + ) -> None: ... + def get_stack_trace(self) -> list[InterpreterInfo]: ... + def get_all_awaited_by(self) -> list[AwaitedInfo]: ... + def get_async_stack_trace(self) -> list[AwaitedInfo]: ... + def get_stats(self) -> _Stats: ... + def pause_threads(self) -> bool: ... + def resume_threads(self) -> bool: ... + +@final +class GCMonitor: + def __init__(self, pid: int, *, debug: bool = False) -> None: ... + def get_gc_stats(self, all_interpreters: bool = False) -> list[GCStatsInfo]: ... + +@final +class BinaryWriter: + def __init__( + self, filename: StrOrBytesPath, sample_interval_us: int, start_time_us: int, *, compression: int = 0 + ) -> None: ... + @property + def total_samples(self) -> int: ... + def write_sample(self, stack_frames: list[InterpreterInfo], timestamp_us: int) -> None: ... + def finalize(self) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object = None, exc_val: object = None, exc_tb: object = None) -> bool: ... + def get_stats(self) -> _Stats: ... + +@final +class BinaryReader: + def __init__(self, filename: StrOrBytesPath) -> None: ... + @property + def sample_count(self) -> int: ... + @property + def sample_interval_us(self) -> int: ... + def replay(self, collector: object, progress_callback: Callable[[int, int], object] | None = None) -> int: ... + def get_info(self) -> dict[str, object]: ... + def get_stats(self) -> _Stats: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, exc_type: object = None, exc_val: object = None, exc_tb: object = None) -> bool: ... + +def zstd_available() -> bool: ... +def get_child_pids(pid: int, *, recursive: bool = True) -> list[int]: ... +def is_python_process(pid: int) -> bool: ... +def get_gc_stats(pid: int, *, all_interpreters: bool = False) -> list[GCStatsInfo]: ... diff --git a/mypy/typeshed/stdlib/_socket.pyi b/mypy/typeshed/stdlib/_socket.pyi index 918bffc7f9085..bb9b08e2f79ad 100644 --- a/mypy/typeshed/stdlib/_socket.pyi +++ b/mypy/typeshed/stdlib/_socket.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import ReadableBuffer, WriteableBuffer from collections.abc import Iterable from socket import error as error, gaierror as gaierror, herror as herror, timeout as timeout -from typing import Any, Final, SupportsIndex, overload -from typing_extensions import CapsuleType, TypeAlias, disjoint_base +from typing import Any, Final, SupportsIndex, TypeAlias, overload +from typing_extensions import CapsuleType, disjoint_base _CMSG: TypeAlias = tuple[int, int, bytes] _CMSGArg: TypeAlias = tuple[int, int, ReadableBuffer] @@ -195,7 +195,7 @@ if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "lin if sys.platform == "linux": # Availability: Linux >= 2.6.20, FreeBSD >= 10.1 IPPROTO_UDPLITE: Final[int] -if sys.version_info >= (3, 10) and sys.platform == "linux": +if sys.platform == "linux": IPPROTO_MPTCP: Final[int] IPPORT_RESERVED: Final[int] @@ -218,8 +218,7 @@ IP_MULTICAST_TTL: Final[int] IP_OPTIONS: Final[int] if sys.platform != "linux": IP_RECVDSTADDR: Final[int] -if sys.version_info >= (3, 10): - IP_RECVTOS: Final[int] +IP_RECVTOS: Final[int] IP_TOS: Final[int] IP_TTL: Final[int] if sys.platform != "win32": @@ -231,6 +230,9 @@ if sys.platform != "win32": IP_RETOPTS: Final[int] if sys.version_info >= (3, 13) and sys.platform == "linux": CAN_RAW_ERR_FILTER: Final[int] +if sys.version_info >= (3, 15): + if sys.platform == "win32" or sys.platform == "linux": + IPV6_HDRINCL: Final[int] if sys.version_info >= (3, 14): IP_RECVTTL: Final[int] @@ -343,7 +345,7 @@ if sys.platform != "win32": TCP_NOTSENT_LOWAT: Final[int] if sys.platform != "darwin": TCP_KEEPIDLE: Final[int] -if sys.version_info >= (3, 10) and sys.platform == "darwin": +if sys.platform == "darwin": TCP_KEEPALIVE: Final[int] if sys.version_info >= (3, 11) and sys.platform == "darwin": TCP_CONNECTION_INFO: Final[int] @@ -438,6 +440,35 @@ if sys.platform == "linux": CAN_RAW_JOIN_FILTERS: Final[int] # Availability: Linux >= 2.6.25 CAN_ISOTP: Final[int] + if sys.version_info >= (3, 15): + CAN_ISOTP_CHK_PAD_DATA: Final[int] + CAN_ISOTP_CHK_PAD_LEN: Final[int] + CAN_ISOTP_DEFAULT_EXT_ADDRESS: Final[int] + CAN_ISOTP_DEFAULT_FLAGS: Final[int] + CAN_ISOTP_DEFAULT_FRAME_TXTIME: Final[int] + CAN_ISOTP_DEFAULT_LL_MTU: Final[int] + CAN_ISOTP_DEFAULT_LL_TX_DL: Final[int] + CAN_ISOTP_DEFAULT_LL_TX_FLAGS: Final[int] + CAN_ISOTP_DEFAULT_PAD_CONTENT: Final[int] + CAN_ISOTP_DEFAULT_RECV_BS: Final[int] + CAN_ISOTP_DEFAULT_RECV_STMIN: Final[int] + CAN_ISOTP_DEFAULT_RECV_WFTMAX: Final[int] + CAN_ISOTP_EXTEND_ADDR: Final[int] + CAN_ISOTP_FORCE_RXSTMIN: Final[int] + CAN_ISOTP_FORCE_TXSTMIN: Final[int] + CAN_ISOTP_HALF_DUPLEX: Final[int] + CAN_ISOTP_LL_OPTS: Final[int] + CAN_ISOTP_LISTEN_MODE: Final[int] + CAN_ISOTP_OPTS: Final[int] + CAN_ISOTP_RECV_FC: Final[int] + CAN_ISOTP_RX_EXT_ADDR: Final[int] + CAN_ISOTP_RX_PADDING: Final[int] + CAN_ISOTP_RX_STMIN: Final[int] + CAN_ISOTP_SF_BROADCAST: Final[int] + CAN_ISOTP_TX_PADDING: Final[int] + CAN_ISOTP_TX_STMIN: Final[int] + CAN_ISOTP_WAIT_TX_DONE: Final[int] + SOL_CAN_ISOTP: Final[int] # Availability: Linux >= 5.4 CAN_J1939: Final[int] @@ -757,10 +788,12 @@ class socket: def fileno(self) -> int: ... def getpeername(self) -> _RetAddress: ... def getsockname(self) -> _RetAddress: ... + @overload def getsockopt(self, level: int, optname: int, /) -> int: ... @overload def getsockopt(self, level: int, optname: int, buflen: int, /) -> bytes: ... + def getblocking(self) -> bool: ... def gettimeout(self) -> float | None: ... if sys.platform == "win32": @@ -779,10 +812,12 @@ class socket: def recv_into(self, buffer: WriteableBuffer, nbytes: int = 0, flags: int = 0) -> int: ... def send(self, data: ReadableBuffer, flags: int = 0, /) -> int: ... def sendall(self, data: ReadableBuffer, flags: int = 0, /) -> None: ... + @overload def sendto(self, data: ReadableBuffer, address: _Address, /) -> int: ... @overload def sendto(self, data: ReadableBuffer, flags: int, address: _Address, /) -> int: ... + if sys.platform != "win32": def sendmsg( self, @@ -799,10 +834,12 @@ class socket: def setblocking(self, flag: bool, /) -> None: ... def settimeout(self, value: float | None, /) -> None: ... + @overload def setsockopt(self, level: int, optname: int, value: int | ReadableBuffer, /) -> None: ... @overload def setsockopt(self, level: int, optname: int, value: None, optlen: int, /) -> None: ... + if sys.platform == "win32": def share(self, process_id: int, /) -> bytes: ... diff --git a/mypy/typeshed/stdlib/_sqlite3.pyi b/mypy/typeshed/stdlib/_sqlite3.pyi index 5361584d6b184..b6d96121afa98 100644 --- a/mypy/typeshed/stdlib/_sqlite3.pyi +++ b/mypy/typeshed/stdlib/_sqlite3.pyi @@ -18,8 +18,8 @@ from sqlite3 import ( Warning as Warning, _IsolationLevel, ) -from typing import Any, Final, Literal, TypeVar, overload -from typing_extensions import TypeAlias, deprecated +from typing import Any, Final, Literal, TypeAlias, TypeVar, overload +from typing_extensions import deprecated if sys.version_info >= (3, 11): from sqlite3 import Blob as Blob @@ -69,6 +69,8 @@ SQLITE_SAVEPOINT: Final = 32 SQLITE_SELECT: Final = 21 SQLITE_TRANSACTION: Final = 22 SQLITE_UPDATE: Final = 23 +if sys.version_info >= (3, 15): + SQLITE_KEYWORDS: tuple[str, ...] adapters: dict[tuple[type[Any], type[Any]], _Adapter[Any]] converters: dict[str, _Converter] sqlite_version: str @@ -218,6 +220,7 @@ if sys.version_info >= (3, 11): def adapt(obj: Any, proto: Any, /) -> Any: ... @overload def adapt(obj: Any, proto: Any, alt: _T, /) -> Any | _T: ... + def complete_statement(statement: str) -> bool: ... if sys.version_info >= (3, 12): @@ -259,7 +262,6 @@ if sys.version_info >= (3, 12): uri: bool = False, autocommit: bool = ..., ) -> _ConnectionT: ... - else: @overload def connect( @@ -305,13 +307,5 @@ if sys.version_info < (3, 12): ) def enable_shared_cache(do_enable: int) -> None: ... # undocumented -if sys.version_info >= (3, 10): - def register_adapter(type: type[_T], adapter: _Adapter[_T], /) -> None: ... - def register_converter(typename: str, converter: _Converter, /) -> None: ... - -else: - def register_adapter(type: type[_T], caster: _Adapter[_T], /) -> None: ... - def register_converter(name: str, converter: _Converter, /) -> None: ... - -if sys.version_info < (3, 10): - OptimizedUnicode = str # undocumented +def register_adapter(type: type[_T], adapter: _Adapter[_T], /) -> None: ... +def register_converter(typename: str, converter: _Converter, /) -> None: ... diff --git a/mypy/typeshed/stdlib/_ssl.pyi b/mypy/typeshed/stdlib/_ssl.pyi index e84b24e8f4db7..87023d90e13bb 100644 --- a/mypy/typeshed/stdlib/_ssl.pyi +++ b/mypy/typeshed/stdlib/_ssl.pyi @@ -12,8 +12,8 @@ from ssl import ( SSLWantWriteError as SSLWantWriteError, SSLZeroReturnError as SSLZeroReturnError, ) -from typing import Any, ClassVar, Final, Literal, TypedDict, final, overload, type_check_only -from typing_extensions import NotRequired, Self, TypeAlias, deprecated, disjoint_base +from typing import Any, ClassVar, Final, Literal, TypeAlias, TypedDict, final, overload, type_check_only +from typing_extensions import NotRequired, Self, deprecated, disjoint_base _PasswordType: TypeAlias = Callable[[], str | bytes | bytearray] | str | bytes | bytearray _PCTRTT: TypeAlias = tuple[tuple[str, str], ...] @@ -54,13 +54,12 @@ if sys.version_info < (3, 12): @deprecated("Deprecated since Python 3.6; removed in Python 3.12. Use `ssl.RAND_bytes()` instead.") def RAND_pseudo_bytes(n: int, /) -> tuple[bytes, bool]: ... -if sys.version_info < (3, 10): - @deprecated("Unsupported by OpenSSL since 1.1.1; removed in Python 3.10.") - def RAND_egd(path: str) -> None: ... - def RAND_status() -> bool: ... def get_default_verify_paths() -> tuple[str, str, str, str]: ... +if sys.version_info >= (3, 15): + def get_sigalgs() -> list[str]: ... + if sys.platform == "win32": _EnumRetType: TypeAlias = list[tuple[bytes, str, set[str] | bool]] def enum_certificates(store_name: str) -> _EnumRetType: ... @@ -68,6 +67,7 @@ if sys.platform == "win32": def txt2obj(txt: str, name: bool = False) -> tuple[int, str, str, str]: ... def nid2obj(nid: int, /) -> tuple[int, str, str, str]: ... + @disjoint_base class _SSLContext: check_hostname: bool @@ -78,19 +78,20 @@ class _SSLContext: options: int post_handshake_auth: bool protocol: int - if sys.version_info >= (3, 10): - security_level: int + security_level: int sni_callback: Callable[[SSLObject, str, SSLContext], None | int] | None verify_flags: int verify_mode: int def __new__(cls, protocol: int, /) -> Self: ... def cert_store_stats(self) -> dict[str, int]: ... + @overload def get_ca_certs(self, binary_form: Literal[False] = False) -> list[_PeerCertRetDictType]: ... @overload def get_ca_certs(self, binary_form: Literal[True]) -> list[bytes]: ... @overload def get_ca_certs(self, binary_form: bool = False) -> Any: ... + def get_ciphers(self) -> list[_Cipher]: ... def load_cert_chain( self, certfile: StrOrBytesPath, keyfile: StrOrBytesPath | None = None, password: _PasswordType | None = None @@ -106,6 +107,12 @@ class _SSLContext: def set_ciphers(self, cipherlist: str, /) -> None: ... def set_default_verify_paths(self) -> None: ... def set_ecdh_curve(self, name: str, /) -> None: ... + if sys.version_info >= (3, 15): + def get_groups(self, *, include_aliases: bool = False) -> list[str]: ... + def set_ciphersuites(self, ciphersuites: str, /) -> None: ... + def set_client_sigalgs(self, sigalgslist: str, /) -> None: ... + def set_groups(self, grouplist: str, /) -> None: ... + def set_server_sigalgs(self, sigalgslist: str, /) -> None: ... if sys.version_info >= (3, 13): def set_psk_client_callback(self, callback: Callable[[str | None], tuple[str | None, bytes]] | None) -> None: ... def set_psk_server_callback( @@ -145,18 +152,18 @@ class SSLSession: # # You can find a _ssl._SSLSocket object as the _sslobj attribute of a ssl.SSLSocket object -if sys.version_info >= (3, 10): - @final - class Certificate: - def get_info(self) -> _CertInfo: ... - @overload - def public_bytes(self) -> str: ... - @overload - def public_bytes(self, format: Literal[1] = 1, /) -> str: ... # ENCODING_PEM - @overload - def public_bytes(self, format: Literal[2], /) -> bytes: ... # ENCODING_DER - @overload - def public_bytes(self, format: int, /) -> str | bytes: ... +@final +class Certificate: + def get_info(self) -> _CertInfo: ... + + @overload + def public_bytes(self) -> str: ... + @overload + def public_bytes(self, format: Literal[1] = 1, /) -> str: ... # ENCODING_PEM + @overload + def public_bytes(self, format: Literal[2], /) -> bytes: ... # ENCODING_DER + @overload + def public_bytes(self, format: int, /) -> str | bytes: ... if sys.version_info < (3, 12): err_codes_to_names: dict[tuple[int, int], str] @@ -187,9 +194,8 @@ VERIFY_CRL_CHECK_LEAF: Final = 0x04 VERIFY_CRL_CHECK_CHAIN: Final = 0x0C VERIFY_X509_STRICT: Final = 0x20 VERIFY_X509_TRUSTED_FIRST: Final = 0x8000 -if sys.version_info >= (3, 10): - VERIFY_ALLOW_PROXY_CERTS: Final = 0x40 - VERIFY_X509_PARTIAL_CHAIN: Final = 0x80000 +VERIFY_ALLOW_PROXY_CERTS: Final = 0x40 +VERIFY_X509_PARTIAL_CHAIN: Final = 0x80000 # alert descriptions ALERT_DESCRIPTION_CLOSE_NOTIFY: Final = 0 @@ -258,10 +264,9 @@ HOSTFLAG_NO_PARTIAL_WILDCARDS: Final = 0x4 HOSTFLAG_MULTI_LABEL_WILDCARDS: Final = 0x8 HOSTFLAG_SINGLE_LABEL_SUBDOMAINS: Final = 0x10 -if sys.version_info >= (3, 10): - # certificate file types - ENCODING_PEM: Final = 1 - ENCODING_DER: Final = 2 +# certificate file types +ENCODING_PEM: Final = 1 +ENCODING_DER: Final = 2 # protocol versions PROTO_MINIMUM_SUPPORTED: Final = -2 @@ -279,6 +284,8 @@ HAS_ECDH: Final[bool] HAS_NPN: Final[bool] if sys.version_info >= (3, 13): HAS_PSK: Final[bool] +if sys.version_info >= (3, 15): + HAS_PSK_TLS13: Final[bool] HAS_ALPN: Final[bool] HAS_SSLv2: Final[bool] HAS_SSLv3: Final[bool] diff --git a/mypy/typeshed/stdlib/_struct.pyi b/mypy/typeshed/stdlib/_struct.pyi index a8fac2aea1b00..c13e440e10aa9 100644 --- a/mypy/typeshed/stdlib/_struct.pyi +++ b/mypy/typeshed/stdlib/_struct.pyi @@ -9,6 +9,7 @@ def unpack(format: str | bytes, buffer: ReadableBuffer, /) -> tuple[Any, ...]: . def unpack_from(format: str | bytes, /, buffer: ReadableBuffer, offset: int = 0) -> tuple[Any, ...]: ... def iter_unpack(format: str | bytes, buffer: ReadableBuffer, /) -> Iterator[tuple[Any, ...]]: ... def calcsize(format: str | bytes, /) -> int: ... + @disjoint_base class Struct: @property diff --git a/mypy/typeshed/stdlib/_thread.pyi b/mypy/typeshed/stdlib/_thread.pyi index 1323a55e9aad8..e2d257c9ec0ba 100644 --- a/mypy/typeshed/stdlib/_thread.pyi +++ b/mypy/typeshed/stdlib/_thread.pyi @@ -12,6 +12,7 @@ _Ts = TypeVarTuple("_Ts") error = RuntimeError def _count() -> int: ... + @final class RLock: def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ... @@ -33,6 +34,7 @@ if sys.version_info >= (3, 13): def start_joinable_thread( function: Callable[[], object], handle: _ThreadHandle | None = None, daemon: bool = True ) -> _ThreadHandle: ... + @final class lock: def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ... @@ -71,6 +73,7 @@ else: def start_new_thread(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]], /) -> int: ... @overload def start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ... + @overload @deprecated("Obsolete synonym. Use `start_new_thread()` instead.") def start_new(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]], /) -> int: ... # undocumented @@ -78,12 +81,7 @@ def start_new(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts] @deprecated("Obsolete synonym. Use `start_new_thread()` instead.") def start_new(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ... # undocumented -if sys.version_info >= (3, 10): - def interrupt_main(signum: signal.Signals = signal.SIGINT, /) -> None: ... - -else: - def interrupt_main() -> None: ... - +def interrupt_main(signum: signal.Signals = signal.SIGINT, /) -> None: ... def exit() -> NoReturn: ... @deprecated("Obsolete synonym. Use `exit()` instead.") def exit_thread() -> NoReturn: ... # undocumented @@ -96,10 +94,10 @@ def stack_size(size: int = 0, /) -> int: ... TIMEOUT_MAX: Final[float] def get_native_id() -> int: ... # only available on some platforms + @final class _ExceptHookArgs(structseq[Any], tuple[type[BaseException], BaseException | None, TracebackType | None, Thread | None]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("exc_type", "exc_value", "exc_traceback", "thread") + __match_args__: Final = ("exc_type", "exc_value", "exc_traceback", "thread") @property def exc_type(self) -> type[BaseException]: ... diff --git a/mypy/typeshed/stdlib/_threading_local.pyi b/mypy/typeshed/stdlib/_threading_local.pyi index 5f6acaf840aa1..7d4e61c6f2ec8 100644 --- a/mypy/typeshed/stdlib/_threading_local.pyi +++ b/mypy/typeshed/stdlib/_threading_local.pyi @@ -1,6 +1,6 @@ from threading import RLock -from typing import Any -from typing_extensions import Self, TypeAlias +from typing import Any, TypeAlias +from typing_extensions import Self from weakref import ReferenceType __all__ = ["local"] diff --git a/mypy/typeshed/stdlib/_tkinter.pyi b/mypy/typeshed/stdlib/_tkinter.pyi index 5e46668e08b1c..500345f91e063 100644 --- a/mypy/typeshed/stdlib/_tkinter.pyi +++ b/mypy/typeshed/stdlib/_tkinter.pyi @@ -1,8 +1,8 @@ import sys from _typeshed import FileDescriptorLike, Incomplete from collections.abc import Callable -from typing import Any, ClassVar, Final, Literal, final, overload -from typing_extensions import TypeAlias, deprecated +from typing import Any, ClassVar, Final, Literal, TypeAlias, final, overload +from typing_extensions import deprecated # _tkinter is meant to be only used internally by tkinter, but some tkinter # functions e.g. return _tkinter.Tcl_Obj objects. Tcl_Obj represents a Tcl @@ -91,6 +91,7 @@ class TkappType: def splitlist(self, arg, /) -> tuple[Incomplete, ...]: ... def unsetvar(self, *args, **kwargs): ... + if sys.version_info >= (3, 14): @overload def wantobjects(self) -> Literal[0, 1]: ... @@ -100,6 +101,7 @@ class TkappType: @overload def wantobjects(self, wantobjects: Literal[0, 1] | bool, /) -> None: ... + def willdispatch(self) -> None: ... if sys.version_info >= (3, 12): def gettrace(self, /) -> _TkinterTraceFunc | None: ... diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index c006322b81451..e74ddc687e8c8 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -6,7 +6,7 @@ import sys from collections.abc import Awaitable, Callable, Iterable, Iterator, Sequence, Set as AbstractSet, Sized from dataclasses import Field from os import PathLike -from types import FrameType, TracebackType +from types import FrameType, NoneType as NoneType, TracebackType from typing import ( Any, AnyStr, @@ -18,11 +18,11 @@ from typing import ( SupportsFloat, SupportsIndex, SupportsInt, + TypeAlias, TypeVar, - final, overload, ) -from typing_extensions import Buffer, LiteralString, Self as _Self, TypeAlias +from typing_extensions import Buffer, LiteralString, Self as _Self _KT = TypeVar("_KT") _KT_co = TypeVar("_KT_co", covariant=True) @@ -313,6 +313,7 @@ class IndexableBuffer(Buffer, Protocol): class SupportsGetItemBuffer(SliceableBuffer, IndexableBuffer, Protocol): def __contains__(self, x: Any, /) -> bool: ... + @overload def __getitem__(self, slice: slice[SupportsIndex | None], /) -> Sequence[int]: ... @overload @@ -323,15 +324,6 @@ class SizedBuffer(Sized, Buffer, Protocol): ... ExcInfo: TypeAlias = tuple[type[BaseException], BaseException, TracebackType] OptExcInfo: TypeAlias = ExcInfo | tuple[None, None, None] -# stable -if sys.version_info >= (3, 10): - from types import NoneType as NoneType -else: - # Used by type checkers for checks involving None (does not exist at runtime) - @final - class NoneType: - def __bool__(self) -> Literal[False]: ... - # This is an internal CPython type that is like, but subtly different from, a NamedTuple # Subclasses of this type are found in multiple modules. # In typeshed, `structseq` is only ever used as a mixin in combination with a fixed-length `Tuple` diff --git a/mypy/typeshed/stdlib/_typeshed/_type_checker_internals.pyi b/mypy/typeshed/stdlib/_typeshed/_type_checker_internals.pyi index feb22aae00732..375e997e2c932 100644 --- a/mypy/typeshed/stdlib/_typeshed/_type_checker_internals.pyi +++ b/mypy/typeshed/stdlib/_typeshed/_type_checker_internals.pyi @@ -40,14 +40,17 @@ class TypedDictFallback(Mapping[str, object], metaclass=ABCMeta): def items(self) -> dict_items[str, object]: ... def keys(self) -> dict_keys[str, object]: ... def values(self) -> dict_values[str, object]: ... + @overload def __or__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... @overload def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... + @overload def __ror__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... @overload def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... + # supposedly incompatible definitions of __or__ and __ior__ def __ior__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... # type: ignore[misc] @@ -67,6 +70,7 @@ class NamedTupleFallback(tuple[Any, ...]): "Creating a typing.NamedTuple using keyword arguments is deprecated and support will be removed in Python 3.15" ) def __init__(self, typename: str, fields: None = None, /, **kwargs: Any) -> None: ... + @classmethod def _make(cls, iterable: Iterable[Any]) -> typing_extensions.Self: ... def _asdict(self) -> dict[str, Any]: ... diff --git a/mypy/typeshed/stdlib/_typeshed/dbapi.pyi b/mypy/typeshed/stdlib/_typeshed/dbapi.pyi index d54fbee57042a..e08a84553dfc0 100644 --- a/mypy/typeshed/stdlib/_typeshed/dbapi.pyi +++ b/mypy/typeshed/stdlib/_typeshed/dbapi.pyi @@ -2,8 +2,7 @@ # https://www.python.org/dev/peps/pep-0249/ from collections.abc import Mapping, Sequence -from typing import Any, Protocol -from typing_extensions import TypeAlias +from typing import Any, Protocol, TypeAlias DBAPITypeCode: TypeAlias = Any | None # Strictly speaking, this should be a Sequence, but the type system does diff --git a/mypy/typeshed/stdlib/_typeshed/wsgi.pyi b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi index 63f204eb889b6..980a24122252e 100644 --- a/mypy/typeshed/stdlib/_typeshed/wsgi.pyi +++ b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi @@ -7,8 +7,7 @@ import sys from _typeshed import OptExcInfo from collections.abc import Callable, Iterable, Iterator -from typing import Any, Protocol -from typing_extensions import TypeAlias +from typing import Any, Protocol, TypeAlias class _Readable(Protocol): def read(self, size: int = ..., /) -> bytes: ... diff --git a/mypy/typeshed/stdlib/_warnings.pyi b/mypy/typeshed/stdlib/_warnings.pyi index 2dbc7b8552813..5f4648259025d 100644 --- a/mypy/typeshed/stdlib/_warnings.pyi +++ b/mypy/typeshed/stdlib/_warnings.pyi @@ -24,7 +24,6 @@ if sys.version_info >= (3, 12): *, skip_file_prefixes: tuple[str, ...] = (), ) -> None: ... - else: @overload def warn(message: str, category: type[Warning] | None = None, stacklevel: int = 1, source: Any | None = None) -> None: ... diff --git a/mypy/typeshed/stdlib/_weakrefset.pyi b/mypy/typeshed/stdlib/_weakrefset.pyi index dad1ed7a4fb5c..82ffa4463f488 100644 --- a/mypy/typeshed/stdlib/_weakrefset.pyi +++ b/mypy/typeshed/stdlib/_weakrefset.pyi @@ -13,6 +13,7 @@ class WeakSet(MutableSet[_T]): def __init__(self, data: None = None) -> None: ... @overload def __init__(self, data: Iterable[_T]) -> None: ... + def add(self, item: _T) -> None: ... def discard(self, item: _T) -> None: ... def copy(self) -> Self: ... diff --git a/mypy/typeshed/stdlib/_winapi.pyi b/mypy/typeshed/stdlib/_winapi.pyi index 42efce9bed705..7fd918d9b1e99 100644 --- a/mypy/typeshed/stdlib/_winapi.pyi +++ b/mypy/typeshed/stdlib/_winapi.pyi @@ -29,6 +29,14 @@ if sys.platform == "win32": ERROR_PIPE_CONNECTED: Final = 535 ERROR_SEM_TIMEOUT: Final = 121 + if sys.version_info >= (3, 15): + EVENTLOG_AUDIT_FAILURE: Final = 16 + EVENTLOG_AUDIT_SUCCESS: Final = 8 + EVENTLOG_ERROR_TYPE: Final = 1 + EVENTLOG_INFORMATION_TYPE: Final = 4 + EVENTLOG_SUCCESS: Final = 0 + EVENTLOG_WARNING_TYPE: Final = 2 + FILE_FLAG_FIRST_PIPE_INSTANCE: Final = 0x80000 FILE_FLAG_OVERLAPPED: Final = 0x40000000 @@ -127,22 +135,21 @@ if sys.platform == "win32": WAIT_OBJECT_0: Final = 0 WAIT_TIMEOUT: Final = 258 - if sys.version_info >= (3, 10): - LOCALE_NAME_INVARIANT: Final[str] - LOCALE_NAME_MAX_LENGTH: Final[int] - LOCALE_NAME_SYSTEM_DEFAULT: Final[str] - LOCALE_NAME_USER_DEFAULT: Final[str | None] - - LCMAP_FULLWIDTH: Final[int] - LCMAP_HALFWIDTH: Final[int] - LCMAP_HIRAGANA: Final[int] - LCMAP_KATAKANA: Final[int] - LCMAP_LINGUISTIC_CASING: Final[int] - LCMAP_LOWERCASE: Final[int] - LCMAP_SIMPLIFIED_CHINESE: Final[int] - LCMAP_TITLECASE: Final[int] - LCMAP_TRADITIONAL_CHINESE: Final[int] - LCMAP_UPPERCASE: Final[int] + LOCALE_NAME_INVARIANT: Final[str] + LOCALE_NAME_MAX_LENGTH: Final[int] + LOCALE_NAME_SYSTEM_DEFAULT: Final[str] + LOCALE_NAME_USER_DEFAULT: Final[str | None] + + LCMAP_FULLWIDTH: Final[int] + LCMAP_HALFWIDTH: Final[int] + LCMAP_HIRAGANA: Final[int] + LCMAP_KATAKANA: Final[int] + LCMAP_LINGUISTIC_CASING: Final[int] + LCMAP_LOWERCASE: Final[int] + LCMAP_SIMPLIFIED_CHINESE: Final[int] + LCMAP_TITLECASE: Final[int] + LCMAP_TRADITIONAL_CHINESE: Final[int] + LCMAP_UPPERCASE: Final[int] if sys.version_info >= (3, 12): COPYFILE2_CALLBACK_CHUNK_STARTED: Final = 1 @@ -176,12 +183,14 @@ if sys.platform == "win32": COPY_FILE_DIRECTORY: Final = 0x00000080 def CloseHandle(handle: int, /) -> None: ... + @overload def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ... @overload def ConnectNamedPipe(handle: int, overlapped: Literal[False] = False) -> None: ... @overload def ConnectNamedPipe(handle: int, overlapped: bool) -> Overlapped | None: ... + def CreateFile( file_name: str, desired_access: int, @@ -231,6 +240,10 @@ if sys.platform == "win32": ) -> int: ... def ExitProcess(ExitCode: int, /) -> NoReturn: ... def GetACP() -> int: ... + if sys.version_info >= (3, 15): + def DeregisterEventSource(handle: int, /) -> None: ... + def GetOEMCP() -> int: ... + def GetFileType(handle: int) -> int: ... def GetCurrentProcess() -> int: ... def GetExitCodeProcess(process: int, /) -> int: ... @@ -243,9 +256,12 @@ if sys.platform == "win32": ) -> int: ... def OpenProcess(desired_access: int, inherit_handle: bool, process_id: int, /) -> int: ... def PeekNamedPipe(handle: int, size: int = 0, /) -> tuple[int, int] | tuple[bytes, int, int]: ... - if sys.version_info >= (3, 10): - def LCMapStringEx(locale: str, flags: int, src: str) -> str: ... - def UnmapViewOfFile(address: int, /) -> None: ... + def LCMapStringEx(locale: str, flags: int, src: str) -> str: ... + if sys.version_info >= (3, 15): + def RegisterEventSource(unc_server_name: str | None, source_name: str, /) -> int: ... + def ReportEvent(handle: int, type: int, category: int, event_id: int, string: str, /) -> None: ... + + def UnmapViewOfFile(address: int, /) -> None: ... @overload def ReadFile(handle: int, size: int, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... @@ -253,6 +269,7 @@ if sys.platform == "win32": def ReadFile(handle: int, size: int, overlapped: Literal[False] = False) -> tuple[bytes, int]: ... @overload def ReadFile(handle: int, size: int, overlapped: int | bool) -> tuple[Any, int]: ... + def SetNamedPipeHandleState( named_pipe: int, mode: int | None, max_collection_count: int | None, collect_data_timeout: int | None, / ) -> None: ... @@ -261,12 +278,14 @@ if sys.platform == "win32": def WaitForMultipleObjects(handle_seq: Sequence[int], wait_flag: bool, milliseconds: int = 0xFFFFFFFF, /) -> int: ... def WaitForSingleObject(handle: int, milliseconds: int, /) -> int: ... def WaitNamedPipe(name: str, timeout: int, /) -> None: ... + @overload def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... @overload def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: Literal[False] = False) -> tuple[int, int]: ... @overload def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: int | bool) -> tuple[Any, int]: ... + @final class Overlapped: event: int diff --git a/mypy/typeshed/stdlib/_zstd.pyi b/mypy/typeshed/stdlib/_zstd.pyi index e40c7d12b6e77..34b619f9b0b62 100644 --- a/mypy/typeshed/stdlib/_zstd.pyi +++ b/mypy/typeshed/stdlib/_zstd.pyi @@ -1,8 +1,8 @@ from _typeshed import ReadableBuffer from collections.abc import Mapping from compression.zstd import CompressionParameter, DecompressionParameter -from typing import Final, Literal, final -from typing_extensions import Self, TypeAlias +from typing import Final, Literal, TypeAlias, final +from typing_extensions import Self ZSTD_CLEVEL_DEFAULT: Final = 3 ZSTD_DStreamOutSize: Final = 131072 @@ -74,7 +74,7 @@ class ZstdDecompressor: @final class ZstdDict: - def __new__(cls, dict_content: bytes, /, *, is_raw: bool = False) -> Self: ... + def __new__(cls, dict_content: ReadableBuffer, /, *, is_raw: bool = False) -> Self: ... def __len__(self, /) -> int: ... @property def as_digested_dict(self) -> tuple[Self, int]: ... diff --git a/mypy/typeshed/stdlib/abc.pyi b/mypy/typeshed/stdlib/abc.pyi index 7e76abace214e..a43a641489a43 100644 --- a/mypy/typeshed/stdlib/abc.pyi +++ b/mypy/typeshed/stdlib/abc.pyi @@ -2,8 +2,8 @@ import _typeshed import sys from _typeshed import SupportsWrite from collections.abc import Callable -from typing import Any, Literal, TypeVar -from typing_extensions import Concatenate, ParamSpec, deprecated +from typing import Any, Concatenate, Literal, ParamSpec, TypeVar +from typing_extensions import deprecated _T = TypeVar("_T") _R_co = TypeVar("_R_co", covariant=True) @@ -28,6 +28,7 @@ class ABCMeta(type): def register(cls: ABCMeta, subclass: type[_T]) -> type[_T]: ... def abstractmethod(funcobj: _FuncT) -> _FuncT: ... + @deprecated("Deprecated since Python 3.3. Use `@classmethod` stacked on top of `@abstractmethod` instead.") class abstractclassmethod(classmethod[_T, _P, _R_co]): __isabstractmethod__: Literal[True] @@ -46,6 +47,4 @@ class ABC(metaclass=ABCMeta): __slots__ = () def get_cache_token() -> object: ... - -if sys.version_info >= (3, 10): - def update_abstractmethods(cls: type[_T]) -> type[_T]: ... +def update_abstractmethods(cls: type[_T]) -> type[_T]: ... diff --git a/mypy/typeshed/stdlib/aifc.pyi b/mypy/typeshed/stdlib/aifc.pyi index bfe12c6af2b0b..afb9029f710ea 100644 --- a/mypy/typeshed/stdlib/aifc.pyi +++ b/mypy/typeshed/stdlib/aifc.pyi @@ -1,6 +1,6 @@ from types import TracebackType -from typing import IO, Any, Literal, NamedTuple, overload -from typing_extensions import Self, TypeAlias +from typing import IO, Any, Literal, NamedTuple, TypeAlias, overload +from typing_extensions import Self __all__ = ["Error", "open"] diff --git a/mypy/typeshed/stdlib/annotationlib.pyi b/mypy/typeshed/stdlib/annotationlib.pyi index 3679dc29daaa0..c3e843d95d9a8 100644 --- a/mypy/typeshed/stdlib/annotationlib.pyi +++ b/mypy/typeshed/stdlib/annotationlib.pyi @@ -41,13 +41,16 @@ if sys.version_info >= (3, 14): "__cell__", "__owner__", "__stringifier_dict__", + "__resolved_str_cache__", ) __forward_is_argument__: bool __forward_is_class__: bool __forward_module__: str | None + __resolved_str_cache__: str | None def __init__( self, arg: str, *, module: str | None = None, owner: object = None, is_argument: bool = True, is_class: bool = False ) -> None: ... + @overload def evaluate( self, @@ -78,6 +81,7 @@ if sys.version_info >= (3, 14): owner: object = None, format: Format = Format.VALUE, # noqa: Y011 ) -> AnnotationForm: ... + @deprecated("Use `ForwardRef.evaluate()` or `typing.evaluate_forward_ref()` instead.") def _evaluate( self, @@ -91,6 +95,8 @@ if sys.version_info >= (3, 14): def __forward_arg__(self) -> str: ... @property def __forward_code__(self) -> types.CodeType: ... + @property + def __resolved_str__(self) -> str: ... def __eq__(self, other: object) -> bool: ... def __hash__(self) -> int: ... def __or__(self, other: Any) -> types.UnionType: ... @@ -104,6 +110,7 @@ if sys.version_info >= (3, 14): ) -> AnnotationForm | ForwardRef: ... @overload def call_evaluate_function(evaluate: EvaluateFunc, format: Format, *, owner: object = None) -> AnnotationForm: ... + @overload def call_annotate_function( annotate: AnnotateFunc, format: Literal[Format.STRING], *, owner: object = None @@ -114,7 +121,9 @@ if sys.version_info >= (3, 14): ) -> dict[str, AnnotationForm | ForwardRef]: ... @overload def call_annotate_function(annotate: AnnotateFunc, format: Format, *, owner: object = None) -> dict[str, AnnotationForm]: ... + def get_annotate_from_class_namespace(obj: Mapping[str, object]) -> AnnotateFunc | None: ... + @overload def get_annotations( obj: Any, # any object with __annotations__ or __annotate__ @@ -142,5 +151,6 @@ if sys.version_info >= (3, 14): eval_str: bool = False, format: Format = Format.VALUE, # noqa: Y011 ) -> dict[str, AnnotationForm]: ... + def type_repr(value: object) -> str: ... def annotations_to_string(annotations: SupportsItems[str, object]) -> dict[str, str]: ... diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index 7d4bd1a3a8418..fa22f842de028 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import SupportsWrite, sentinel from collections.abc import Callable, Generator, Iterable, Sequence from re import Pattern -from typing import IO, Any, ClassVar, Final, Generic, NewType, NoReturn, Protocol, TypeVar, overload, type_check_only -from typing_extensions import Self, TypeAlias, deprecated +from typing import IO, Any, ClassVar, Final, Generic, NewType, NoReturn, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, deprecated __all__ = [ "ArgumentParser", @@ -93,39 +93,28 @@ class _ActionsContainer: version: str = ..., **kwargs: Any, ) -> Action: ... - if sys.version_info >= (3, 14): - @overload - def add_argument_group( - self, - title: str | None = None, - description: str | None = None, - *, - # argument_default's type must be valid for the arguments in the group - argument_default: Any = ..., - conflict_handler: str = ..., - ) -> _ArgumentGroup: ... - @overload - @deprecated("The `prefix_chars` parameter deprecated since Python 3.14.") - def add_argument_group( - self, - title: str | None = None, - description: str | None = None, - *, - prefix_chars: str, - argument_default: Any = ..., - conflict_handler: str = ..., - ) -> _ArgumentGroup: ... - else: - def add_argument_group( - self, - title: str | None = None, - description: str | None = None, - *, - prefix_chars: str = ..., - # argument_default's type must be valid for the arguments in the group - argument_default: Any = ..., - conflict_handler: str = ..., - ) -> _ArgumentGroup: ... + + @overload + def add_argument_group( + self, + title: str | None = None, + description: str | None = None, + *, + # argument_default's type must be valid for the arguments in the group + argument_default: Any = ..., + conflict_handler: str = ..., + ) -> _ArgumentGroup: ... + @overload + @deprecated("The `prefix_chars` parameter deprecated since Python 3.14.") + def add_argument_group( + self, + title: str | None = None, + description: str | None = None, + *, + prefix_chars: str, + argument_default: Any = ..., + conflict_handler: str = ..., + ) -> _ArgumentGroup: ... def add_mutually_exclusive_group(self, *, required: bool = False) -> _MutuallyExclusiveGroup: ... def _add_action(self, action: _ActionT) -> _ActionT: ... @@ -163,7 +152,28 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): _subparsers: _ArgumentGroup | None # Note: the constructor arguments are also used in _SubParsersAction.add_parser. - if sys.version_info >= (3, 14): + if sys.version_info >= (3, 15): + def __init__( + self, + prog: str | None = None, + usage: str | None = None, + description: str | None = None, + epilog: str | None = None, + parents: Iterable[ArgumentParser] = [], + formatter_class: _FormatterClass = ..., + prefix_chars: str = "-", + fromfile_prefix_chars: str | None = None, + argument_default: Any = None, + conflict_handler: str = "error", + add_help: bool = True, + allow_abbrev: bool = True, + exit_on_error: bool = True, + *, + suggest_on_error: bool = True, + color: bool = True, + ) -> None: ... + + elif sys.version_info >= (3, 14): def __init__( self, prog: str | None = None, @@ -207,6 +217,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): def parse_args(self, args: Iterable[str] | None, namespace: _N) -> _N: ... @overload def parse_args(self, *, namespace: _N) -> _N: ... + @overload def add_subparsers( self: _ArgumentParserT, @@ -236,25 +247,35 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): help: str | None = None, metavar: str | None = None, ) -> _SubParsersAction[_ArgumentParserT]: ... + def print_usage(self, file: SupportsWrite[str] | None = None) -> None: ... def print_help(self, file: SupportsWrite[str] | None = None) -> None: ... - def format_usage(self) -> str: ... - def format_help(self) -> str: ... + if sys.version_info >= (3, 15): + def format_usage(self, formatter: HelpFormatter | None = None) -> str: ... + def format_help(self, formatter: HelpFormatter | None = None) -> str: ... + + else: + def format_usage(self) -> str: ... + def format_help(self) -> str: ... + @overload def parse_known_args(self, args: Iterable[str] | None = None, namespace: None = None) -> tuple[Namespace, list[str]]: ... @overload def parse_known_args(self, args: Iterable[str] | None, namespace: _N) -> tuple[_N, list[str]]: ... @overload def parse_known_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ... + def convert_arg_line_to_args(self, arg_line: str) -> list[str]: ... def exit(self, status: int = 0, message: str | None = None) -> NoReturn: ... def error(self, message: str) -> NoReturn: ... + @overload def parse_intermixed_args(self, args: Iterable[str] | None = None, namespace: None = None) -> Namespace: ... @overload def parse_intermixed_args(self, args: Iterable[str] | None, namespace: _N) -> _N: ... @overload def parse_intermixed_args(self, *, namespace: _N) -> _N: ... + @overload def parse_known_intermixed_args( self, args: Iterable[str] | None = None, namespace: None = None @@ -263,6 +284,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): def parse_known_intermixed_args(self, args: Iterable[str] | None, namespace: _N) -> tuple[_N, list[str]]: ... @overload def parse_known_intermixed_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ... + # undocumented def _get_optional_actions(self) -> list[Action]: ... def _get_positional_actions(self) -> list[Action]: ... @@ -286,7 +308,11 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): def _get_values(self, action: Action, arg_strings: list[str]) -> Any: ... def _get_value(self, action: Action, arg_string: str) -> Any: ... def _check_value(self, action: Action, value: Any) -> None: ... - def _get_formatter(self) -> HelpFormatter: ... + if sys.version_info >= (3, 15): + def _get_formatter(self, file: SupportsWrite[str] | None = None) -> HelpFormatter: ... + else: + def _get_formatter(self) -> HelpFormatter: ... + def _print_message(self, message: str, file: SupportsWrite[str] | None = None) -> None: ... class HelpFormatter: @@ -311,7 +337,12 @@ class HelpFormatter: def __init__(self, formatter: HelpFormatter, parent: Self | None, heading: str | None = None) -> None: ... def format_help(self) -> str: ... - if sys.version_info >= (3, 14): + if sys.version_info >= (3, 15): + def __init__( + self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None + ) -> None: ... + + elif sys.version_info >= (3, 14): def __init__( self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None, color: bool = True ) -> None: ... @@ -501,69 +532,43 @@ class Namespace(_AttributeHolder): def __eq__(self, other: object) -> bool: ... __hash__: ClassVar[None] # type: ignore[assignment] -if sys.version_info >= (3, 14): - @deprecated("Deprecated since Python 3.14. Open files after parsing arguments instead.") - class FileType: - # undocumented - _mode: str - _bufsize: int - _encoding: str | None - _errors: str | None - def __init__( - self, mode: str = "r", bufsize: int = -1, encoding: str | None = None, errors: str | None = None - ) -> None: ... - def __call__(self, string: str) -> IO[Any]: ... - -else: - class FileType: - # undocumented - _mode: str - _bufsize: int - _encoding: str | None - _errors: str | None - def __init__( - self, mode: str = "r", bufsize: int = -1, encoding: str | None = None, errors: str | None = None - ) -> None: ... - def __call__(self, string: str) -> IO[Any]: ... +@deprecated("Deprecated since Python 3.14. Open files after parsing arguments instead.") +class FileType: + # undocumented + _mode: str + _bufsize: int + _encoding: str | None + _errors: str | None + def __init__(self, mode: str = "r", bufsize: int = -1, encoding: str | None = None, errors: str | None = None) -> None: ... + def __call__(self, string: str) -> IO[Any]: ... # undocumented class _ArgumentGroup(_ActionsContainer): title: str | None _group_actions: list[Action] - if sys.version_info >= (3, 14): - @overload - def __init__( - self, - container: _ActionsContainer, - title: str | None = None, - description: str | None = None, - *, - argument_default: Any = ..., - conflict_handler: str = ..., - ) -> None: ... - @overload - @deprecated("Undocumented `prefix_chars` parameter is deprecated since Python 3.14.") - def __init__( - self, - container: _ActionsContainer, - title: str | None = None, - description: str | None = None, - *, - prefix_chars: str, - argument_default: Any = ..., - conflict_handler: str = ..., - ) -> None: ... - else: - def __init__( - self, - container: _ActionsContainer, - title: str | None = None, - description: str | None = None, - *, - prefix_chars: str = ..., - argument_default: Any = ..., - conflict_handler: str = ..., - ) -> None: ... + + @overload + def __init__( + self, + container: _ActionsContainer, + title: str | None = None, + description: str | None = None, + *, + argument_default: Any = ..., + conflict_handler: str = ..., + ) -> None: ... + @overload + @deprecated("Undocumented `prefix_chars` parameter is deprecated since Python 3.14.") + def __init__( + self, + container: _ActionsContainer, + title: str | None = None, + description: str | None = None, + *, + prefix_chars: str, + argument_default: Any = ..., + conflict_handler: str = ..., + ) -> None: ... # undocumented class _MutuallyExclusiveGroup(_ArgumentGroup): diff --git a/mypy/typeshed/stdlib/array.pyi b/mypy/typeshed/stdlib/array.pyi index eb679dd50f722..2c83146edbf00 100644 --- a/mypy/typeshed/stdlib/array.pyi +++ b/mypy/typeshed/stdlib/array.pyi @@ -2,11 +2,14 @@ import sys from _typeshed import ReadableBuffer, SupportsRead, SupportsWrite from collections.abc import Iterable, MutableSequence from types import GenericAlias -from typing import Any, ClassVar, Literal, SupportsIndex, TypeVar, overload -from typing_extensions import Self, TypeAlias, deprecated, disjoint_base +from typing import Any, ClassVar, Literal, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import Self, deprecated, disjoint_base _IntTypeCode: TypeAlias = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] -_FloatTypeCode: TypeAlias = Literal["f", "d"] +if sys.version_info >= (3, 15): + _FloatTypeCode: TypeAlias = Literal["f", "d", "e", "Zf", "Zd"] +else: + _FloatTypeCode: TypeAlias = Literal["f", "d"] if sys.version_info >= (3, 13): _UnicodeTypeCode: TypeAlias = Literal["u", "w"] else: @@ -15,7 +18,10 @@ _TypeCode: TypeAlias = _IntTypeCode | _FloatTypeCode | _UnicodeTypeCode _T = TypeVar("_T", int, float, str) -typecodes: str +if sys.version_info >= (3, 15): + typecodes: tuple[str, ...] +else: + typecodes: str @disjoint_base class array(MutableSequence[_T]): @@ -23,6 +29,7 @@ class array(MutableSequence[_T]): def typecode(self) -> _TypeCode: ... @property def itemsize(self) -> int: ... + @overload def __new__( cls: type[array[int]], typecode: _IntTypeCode, initializer: bytes | bytearray | Iterable[int] = ..., / @@ -52,6 +59,7 @@ class array(MutableSequence[_T]): def __new__(cls, typecode: str, initializer: Iterable[_T], /) -> Self: ... @overload def __new__(cls, typecode: str, initializer: bytes | bytearray = ..., /) -> Self: ... + def append(self, v: _T, /) -> None: ... def buffer_info(self) -> tuple[int, int]: ... def byteswap(self) -> None: ... @@ -61,11 +69,7 @@ class array(MutableSequence[_T]): def fromfile(self, f: SupportsRead[bytes], n: int, /) -> None: ... def fromlist(self, list: list[_T], /) -> None: ... def fromunicode(self, ustr: str, /) -> None: ... - if sys.version_info >= (3, 10): - def index(self, v: _T, start: int = 0, stop: int = sys.maxsize, /) -> int: ... - else: - def index(self, v: _T, /) -> int: ... # type: ignore[override] - + def index(self, v: _T, start: int = 0, stop: int = sys.maxsize, /) -> int: ... def insert(self, i: int, v: _T, /) -> None: ... def pop(self, i: int = -1, /) -> _T: ... def remove(self, v: _T, /) -> None: ... @@ -77,14 +81,17 @@ class array(MutableSequence[_T]): __hash__: ClassVar[None] # type: ignore[assignment] def __contains__(self, value: object, /) -> bool: ... def __len__(self) -> int: ... + @overload def __getitem__(self, key: SupportsIndex, /) -> _T: ... @overload def __getitem__(self, key: slice[SupportsIndex | None], /) -> array[_T]: ... + @overload # type: ignore[override] def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ... @overload def __setitem__(self, key: slice[SupportsIndex | None], value: array[_T], /) -> None: ... + def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> None: ... def __add__(self, value: array[_T], /) -> array[_T]: ... def __eq__(self, value: object, /) -> bool: ... diff --git a/mypy/typeshed/stdlib/ast.pyi b/mypy/typeshed/stdlib/ast.pyi index e66e609ee6645..14a98b9a5fcaf 100644 --- a/mypy/typeshed/stdlib/ast.pyi +++ b/mypy/typeshed/stdlib/ast.pyi @@ -10,6 +10,7 @@ from _ast import ( ) from _typeshed import ReadableBuffer, Unused from collections.abc import Iterable, Iterator, Sequence +from types import EllipsisType from typing import Any, ClassVar, Generic, Literal, TypedDict, TypeVar as _TypeVar, overload, type_check_only from typing_extensions import Self, Unpack, deprecated, disjoint_base @@ -44,16 +45,14 @@ if sys.version_info >= (3, 12): else: class AST: - if sys.version_info >= (3, 10): - __match_args__ = () + __match_args__ = () _attributes: ClassVar[tuple[str, ...]] _fields: ClassVar[tuple[str, ...]] class mod(AST): ... class Module(mod): - if sys.version_info >= (3, 10): - __match_args__ = ("body", "type_ignores") + __match_args__ = ("body", "type_ignores") body: list[stmt] type_ignores: list[TypeIgnore] if sys.version_info >= (3, 13): @@ -65,8 +64,7 @@ class Module(mod): def __replace__(self, *, body: list[stmt] = ..., type_ignores: list[TypeIgnore] = ...) -> Self: ... class Interactive(mod): - if sys.version_info >= (3, 10): - __match_args__ = ("body",) + __match_args__ = ("body",) body: list[stmt] if sys.version_info >= (3, 13): def __init__(self, body: list[stmt] = ...) -> None: ... @@ -77,8 +75,7 @@ class Interactive(mod): def __replace__(self, *, body: list[stmt] = ...) -> Self: ... class Expression(mod): - if sys.version_info >= (3, 10): - __match_args__ = ("body",) + __match_args__ = ("body",) body: expr def __init__(self, body: expr) -> None: ... @@ -86,8 +83,7 @@ class Expression(mod): def __replace__(self, *, body: expr = ...) -> Self: ... class FunctionType(mod): - if sys.version_info >= (3, 10): - __match_args__ = ("argtypes", "returns") + __match_args__ = ("argtypes", "returns") argtypes: list[expr] returns: expr if sys.version_info >= (3, 13): @@ -114,7 +110,7 @@ class stmt(AST): class FunctionDef(stmt): if sys.version_info >= (3, 12): __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment", "type_params") - elif sys.version_info >= (3, 10): + else: __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment") name: str args: arguments @@ -191,7 +187,7 @@ class FunctionDef(stmt): class AsyncFunctionDef(stmt): if sys.version_info >= (3, 12): __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment", "type_params") - elif sys.version_info >= (3, 10): + else: __match_args__ = ("name", "args", "body", "decorator_list", "returns", "type_comment") name: str args: arguments @@ -268,7 +264,7 @@ class AsyncFunctionDef(stmt): class ClassDef(stmt): if sys.version_info >= (3, 12): __match_args__ = ("name", "bases", "keywords", "body", "decorator_list", "type_params") - elif sys.version_info >= (3, 10): + else: __match_args__ = ("name", "bases", "keywords", "body", "decorator_list") name: str bases: list[expr] @@ -324,8 +320,7 @@ class ClassDef(stmt): ) -> Self: ... class Return(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("value",) + __match_args__ = ("value",) value: expr | None def __init__(self, value: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ... @@ -333,8 +328,7 @@ class Return(stmt): def __replace__(self, *, value: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class Delete(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("targets",) + __match_args__ = ("targets",) targets: list[expr] if sys.version_info >= (3, 13): def __init__(self, targets: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... @@ -345,8 +339,7 @@ class Delete(stmt): def __replace__(self, *, targets: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class Assign(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("targets", "value", "type_comment") + __match_args__ = ("targets", "value", "type_comment") targets: list[expr] value: expr type_comment: str | None @@ -400,8 +393,7 @@ if sys.version_info >= (3, 12): ) -> Self: ... class AugAssign(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("target", "op", "value") + __match_args__ = ("target", "op", "value") target: Name | Attribute | Subscript op: operator value: expr @@ -420,12 +412,12 @@ class AugAssign(stmt): ) -> Self: ... class AnnAssign(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("target", "annotation", "value", "simple") + __match_args__ = ("target", "annotation", "value", "simple") target: Name | Attribute | Subscript annotation: expr value: expr | None simple: int + @overload def __init__( self, @@ -458,8 +450,7 @@ class AnnAssign(stmt): ) -> Self: ... class For(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("target", "iter", "body", "orelse", "type_comment") + __match_args__ = ("target", "iter", "body", "orelse", "type_comment") target: expr iter: expr body: list[stmt] @@ -499,8 +490,7 @@ class For(stmt): ) -> Self: ... class AsyncFor(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("target", "iter", "body", "orelse", "type_comment") + __match_args__ = ("target", "iter", "body", "orelse", "type_comment") target: expr iter: expr body: list[stmt] @@ -540,8 +530,7 @@ class AsyncFor(stmt): ) -> Self: ... class While(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("test", "body", "orelse") + __match_args__ = ("test", "body", "orelse") test: expr body: list[stmt] orelse: list[stmt] @@ -558,8 +547,7 @@ class While(stmt): ) -> Self: ... class If(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("test", "body", "orelse") + __match_args__ = ("test", "body", "orelse") test: expr body: list[stmt] orelse: list[stmt] @@ -576,8 +564,7 @@ class If(stmt): ) -> Self: ... class With(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("items", "body", "type_comment") + __match_args__ = ("items", "body", "type_comment") items: list[withitem] body: list[stmt] type_comment: str | None @@ -605,8 +592,7 @@ class With(stmt): ) -> Self: ... class AsyncWith(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("items", "body", "type_comment") + __match_args__ = ("items", "body", "type_comment") items: list[withitem] body: list[stmt] type_comment: str | None @@ -634,8 +620,7 @@ class AsyncWith(stmt): ) -> Self: ... class Raise(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("exc", "cause") + __match_args__ = ("exc", "cause") exc: expr | None cause: expr | None def __init__(self, exc: expr | None = None, cause: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ... @@ -644,8 +629,7 @@ class Raise(stmt): def __replace__(self, *, exc: expr | None = ..., cause: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class Try(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("body", "handlers", "orelse", "finalbody") + __match_args__ = ("body", "handlers", "orelse", "finalbody") body: list[stmt] handlers: list[ExceptHandler] orelse: list[stmt] @@ -718,8 +702,7 @@ if sys.version_info >= (3, 11): ) -> Self: ... class Assert(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("test", "msg") + __match_args__ = ("test", "msg") test: expr msg: expr | None def __init__(self, test: expr, msg: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ... @@ -728,24 +711,53 @@ class Assert(stmt): def __replace__(self, *, test: expr = ..., msg: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class Import(stmt): - if sys.version_info >= (3, 10): + if sys.version_info >= (3, 15): + __match_args__ = ("names", "is_lazy") + else: __match_args__ = ("names",) names: list[alias] - if sys.version_info >= (3, 13): + if sys.version_info >= (3, 15): + is_lazy: bool | None + if sys.version_info >= (3, 15): + def __init__(self, names: list[alias] = ..., is_lazy: bool | None = None, **kwargs: Unpack[_Attributes]) -> None: ... + + elif sys.version_info >= (3, 13): def __init__(self, names: list[alias] = ..., **kwargs: Unpack[_Attributes]) -> None: ... else: def __init__(self, names: list[alias], **kwargs: Unpack[_Attributes]) -> None: ... - if sys.version_info >= (3, 14): + if sys.version_info >= (3, 15): + def __replace__(self, *, names: list[alias] = ..., is_lazy: bool | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... + + elif sys.version_info >= (3, 14): def __replace__(self, *, names: list[alias] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class ImportFrom(stmt): - if sys.version_info >= (3, 10): + if sys.version_info >= (3, 15): + __match_args__ = ("module", "names", "level", "is_lazy") + else: __match_args__ = ("module", "names", "level") module: str | None names: list[alias] level: int - if sys.version_info >= (3, 13): + if sys.version_info >= (3, 15): + is_lazy: bool | None + if sys.version_info >= (3, 15): + @overload + def __init__( + self, module: str | None, names: list[alias], level: int, is_lazy: bool | None = None, **kwargs: Unpack[_Attributes] + ) -> None: ... + @overload + def __init__( + self, + module: str | None = None, + names: list[alias] = ..., + *, + level: int, + is_lazy: bool | None = None, + **kwargs: Unpack[_Attributes], + ) -> None: ... + elif sys.version_info >= (3, 13): @overload def __init__(self, module: str | None, names: list[alias], level: int, **kwargs: Unpack[_Attributes]) -> None: ... @overload @@ -760,14 +772,24 @@ class ImportFrom(stmt): self, module: str | None = None, *, names: list[alias], level: int, **kwargs: Unpack[_Attributes] ) -> None: ... - if sys.version_info >= (3, 14): + if sys.version_info >= (3, 15): + def __replace__( + self, + *, + module: str | None = ..., + names: list[alias] = ..., + level: int = ..., + is_lazy: bool | None = ..., + **kwargs: Unpack[_Attributes], + ) -> Self: ... + + elif sys.version_info >= (3, 14): def __replace__( self, *, module: str | None = ..., names: list[alias] = ..., level: int = ..., **kwargs: Unpack[_Attributes] ) -> Self: ... class Global(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("names",) + __match_args__ = ("names",) names: list[str] if sys.version_info >= (3, 13): def __init__(self, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> None: ... @@ -778,8 +800,7 @@ class Global(stmt): def __replace__(self, *, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class Nonlocal(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("names",) + __match_args__ = ("names",) names: list[str] if sys.version_info >= (3, 13): def __init__(self, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> None: ... @@ -790,8 +811,7 @@ class Nonlocal(stmt): def __replace__(self, *, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class Expr(stmt): - if sys.version_info >= (3, 10): - __match_args__ = ("value",) + __match_args__ = ("value",) value: expr def __init__(self, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... @@ -813,8 +833,7 @@ class expr(AST): def __replace__(self, **kwargs: Unpack[_Attributes]) -> Self: ... class BoolOp(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("op", "values") + __match_args__ = ("op", "values") op: boolop values: list[expr] if sys.version_info >= (3, 13): @@ -826,8 +845,7 @@ class BoolOp(expr): def __replace__(self, *, op: boolop = ..., values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class NamedExpr(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("target", "value") + __match_args__ = ("target", "value") target: Name value: expr def __init__(self, target: Name, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... @@ -836,8 +854,7 @@ class NamedExpr(expr): def __replace__(self, *, target: Name = ..., value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class BinOp(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("left", "op", "right") + __match_args__ = ("left", "op", "right") left: expr op: operator right: expr @@ -849,8 +866,7 @@ class BinOp(expr): ) -> Self: ... class UnaryOp(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("op", "operand") + __match_args__ = ("op", "operand") op: unaryop operand: expr def __init__(self, op: unaryop, operand: expr, **kwargs: Unpack[_Attributes]) -> None: ... @@ -859,8 +875,7 @@ class UnaryOp(expr): def __replace__(self, *, op: unaryop = ..., operand: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class Lambda(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("args", "body") + __match_args__ = ("args", "body") args: arguments body: expr def __init__(self, args: arguments, body: expr, **kwargs: Unpack[_Attributes]) -> None: ... @@ -869,8 +884,7 @@ class Lambda(expr): def __replace__(self, *, args: arguments = ..., body: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class IfExp(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("test", "body", "orelse") + __match_args__ = ("test", "body", "orelse") test: expr body: expr orelse: expr @@ -882,8 +896,7 @@ class IfExp(expr): ) -> Self: ... class Dict(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("keys", "values") + __match_args__ = ("keys", "values") keys: list[expr | None] values: list[expr] if sys.version_info >= (3, 13): @@ -897,8 +910,7 @@ class Dict(expr): ) -> Self: ... class Set(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("elts",) + __match_args__ = ("elts",) elts: list[expr] if sys.version_info >= (3, 13): def __init__(self, elts: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... @@ -909,8 +921,7 @@ class Set(expr): def __replace__(self, *, elts: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class ListComp(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("elt", "generators") + __match_args__ = ("elt", "generators") elt: expr generators: list[comprehension] if sys.version_info >= (3, 13): @@ -924,8 +935,7 @@ class ListComp(expr): ) -> Self: ... class SetComp(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("elt", "generators") + __match_args__ = ("elt", "generators") elt: expr generators: list[comprehension] if sys.version_info >= (3, 13): @@ -939,10 +949,12 @@ class SetComp(expr): ) -> Self: ... class DictComp(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("key", "value", "generators") + __match_args__ = ("key", "value", "generators") key: expr - value: expr + if sys.version_info >= (3, 15): + value: expr | None + else: + value: expr generators: list[comprehension] if sys.version_info >= (3, 13): def __init__( @@ -957,8 +969,7 @@ class DictComp(expr): ) -> Self: ... class GeneratorExp(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("elt", "generators") + __match_args__ = ("elt", "generators") elt: expr generators: list[comprehension] if sys.version_info >= (3, 13): @@ -972,8 +983,7 @@ class GeneratorExp(expr): ) -> Self: ... class Await(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("value",) + __match_args__ = ("value",) value: expr def __init__(self, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... @@ -981,8 +991,7 @@ class Await(expr): def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class Yield(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("value",) + __match_args__ = ("value",) value: expr | None def __init__(self, value: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ... @@ -990,8 +999,7 @@ class Yield(expr): def __replace__(self, *, value: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class YieldFrom(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("value",) + __match_args__ = ("value",) value: expr def __init__(self, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... @@ -999,8 +1007,7 @@ class YieldFrom(expr): def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class Compare(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("left", "ops", "comparators") + __match_args__ = ("left", "ops", "comparators") left: expr ops: list[cmpop] comparators: list[expr] @@ -1017,8 +1024,7 @@ class Compare(expr): ) -> Self: ... class Call(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("func", "args", "keywords") + __match_args__ = ("func", "args", "keywords") func: expr args: list[expr] keywords: list[keyword] @@ -1035,8 +1041,7 @@ class Call(expr): ) -> Self: ... class FormattedValue(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("value", "conversion", "format_spec") + __match_args__ = ("value", "conversion", "format_spec") value: expr conversion: int format_spec: expr | None @@ -1048,8 +1053,7 @@ class FormattedValue(expr): ) -> Self: ... class JoinedStr(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("values",) + __match_args__ = ("values",) values: list[expr] if sys.version_info >= (3, 13): def __init__(self, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ... @@ -1090,17 +1094,10 @@ if sys.version_info >= (3, 14): **kwargs: Unpack[_Attributes], ) -> Self: ... -if sys.version_info >= (3, 10): - from types import EllipsisType - - _ConstantValue: typing_extensions.TypeAlias = str | bytes | bool | int | float | complex | None | EllipsisType -else: - # Rely on builtins.ellipsis - _ConstantValue: typing_extensions.TypeAlias = str | bytes | bool | int | float | complex | None | ellipsis # noqa: F821 +_ConstantValue: typing_extensions.TypeAlias = str | bytes | bool | int | float | complex | None | EllipsisType class Constant(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("value", "kind") + __match_args__ = ("value", "kind") value: _ConstantValue kind: str | None if sys.version_info < (3, 14): @@ -1111,6 +1108,7 @@ class Constant(expr): @n.setter @deprecated("Removed in Python 3.14. Use `value` instead.") def n(self, value: _ConstantValue) -> None: ... + @property @deprecated("Removed in Python 3.14. Use `value` instead.") def s(self) -> _ConstantValue: ... @@ -1124,8 +1122,7 @@ class Constant(expr): def __replace__(self, *, value: _ConstantValue = ..., kind: str | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class Attribute(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("value", "attr", "ctx") + __match_args__ = ("value", "attr", "ctx") value: expr attr: str ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` @@ -1137,8 +1134,7 @@ class Attribute(expr): ) -> Self: ... class Subscript(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("value", "slice", "ctx") + __match_args__ = ("value", "slice", "ctx") value: expr slice: expr ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` @@ -1150,8 +1146,7 @@ class Subscript(expr): ) -> Self: ... class Starred(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("value", "ctx") + __match_args__ = ("value", "ctx") value: expr ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` def __init__(self, value: expr, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... @@ -1160,8 +1155,7 @@ class Starred(expr): def __replace__(self, *, value: expr = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class Name(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("id", "ctx") + __match_args__ = ("id", "ctx") id: str ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` def __init__(self, id: str, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... @@ -1170,8 +1164,7 @@ class Name(expr): def __replace__(self, *, id: str = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class List(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("elts", "ctx") + __match_args__ = ("elts", "ctx") elts: list[expr] ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` if sys.version_info >= (3, 13): @@ -1183,8 +1176,7 @@ class List(expr): def __replace__(self, *, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class Tuple(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("elts", "ctx") + __match_args__ = ("elts", "ctx") elts: list[expr] ctx: expr_context # Not present in Python < 3.13 if not passed to `__init__` dims: list[expr] @@ -1200,8 +1192,7 @@ class Tuple(expr): class slice(AST): ... class Slice(expr): - if sys.version_info >= (3, 10): - __match_args__ = ("lower", "upper", "step") + __match_args__ = ("lower", "upper", "step") lower: expr | None upper: expr | None step: expr | None @@ -1274,8 +1265,7 @@ class In(cmpop): ... class NotIn(cmpop): ... class comprehension(AST): - if sys.version_info >= (3, 10): - __match_args__ = ("target", "iter", "ifs", "is_async") + __match_args__ = ("target", "iter", "ifs", "is_async") target: expr iter: expr ifs: list[expr] @@ -1304,8 +1294,7 @@ class excepthandler(AST): ) -> Self: ... class ExceptHandler(excepthandler): - if sys.version_info >= (3, 10): - __match_args__ = ("type", "name", "body") + __match_args__ = ("type", "name", "body") type: expr | None name: str | None body: list[stmt] @@ -1327,8 +1316,7 @@ class ExceptHandler(excepthandler): ) -> Self: ... class arguments(AST): - if sys.version_info >= (3, 10): - __match_args__ = ("posonlyargs", "args", "vararg", "kwonlyargs", "kw_defaults", "kwarg", "defaults") + __match_args__ = ("posonlyargs", "args", "vararg", "kwonlyargs", "kw_defaults", "kwarg", "defaults") posonlyargs: list[arg] args: list[arg] vararg: arg | None @@ -1398,12 +1386,11 @@ class arguments(AST): ) -> Self: ... class arg(AST): + __match_args__ = ("arg", "annotation", "type_comment") lineno: int col_offset: int end_lineno: int | None end_col_offset: int | None - if sys.version_info >= (3, 10): - __match_args__ = ("arg", "annotation", "type_comment") arg: str annotation: expr | None type_comment: str | None @@ -1417,14 +1404,14 @@ class arg(AST): ) -> Self: ... class keyword(AST): + __match_args__ = ("arg", "value") lineno: int col_offset: int end_lineno: int | None end_col_offset: int | None - if sys.version_info >= (3, 10): - __match_args__ = ("arg", "value") arg: str | None value: expr + @overload def __init__(self, arg: str | None, value: expr, **kwargs: Unpack[_Attributes]) -> None: ... @overload @@ -1434,26 +1421,20 @@ class keyword(AST): def __replace__(self, *, arg: str | None = ..., value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class alias(AST): + __match_args__ = ("name", "asname") name: str asname: str | None - if sys.version_info >= (3, 10): - lineno: int - col_offset: int - end_lineno: int | None - end_col_offset: int | None - if sys.version_info >= (3, 10): - __match_args__ = ("name", "asname") - if sys.version_info >= (3, 10): - def __init__(self, name: str, asname: str | None = None, **kwargs: Unpack[_Attributes]) -> None: ... - else: - def __init__(self, name: str, asname: str | None = None) -> None: ... + lineno: int + col_offset: int + end_lineno: int | None + end_col_offset: int | None + def __init__(self, name: str, asname: str | None = None, **kwargs: Unpack[_Attributes]) -> None: ... if sys.version_info >= (3, 14): def __replace__(self, *, name: str = ..., asname: str | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ... class withitem(AST): - if sys.version_info >= (3, 10): - __match_args__ = ("context_expr", "optional_vars") + __match_args__ = ("context_expr", "optional_vars") context_expr: expr optional_vars: expr | None def __init__(self, context_expr: expr, optional_vars: expr | None = None) -> None: ... @@ -1461,177 +1442,173 @@ class withitem(AST): if sys.version_info >= (3, 14): def __replace__(self, *, context_expr: expr = ..., optional_vars: expr | None = ...) -> Self: ... -if sys.version_info >= (3, 10): - class pattern(AST): - lineno: int - col_offset: int - end_lineno: int - end_col_offset: int - def __init__(self, **kwargs: Unpack[_Attributes[int]]) -> None: ... +class pattern(AST): + lineno: int + col_offset: int + end_lineno: int + end_col_offset: int + def __init__(self, **kwargs: Unpack[_Attributes[int]]) -> None: ... - if sys.version_info >= (3, 14): - def __replace__( - self, *, lineno: int = ..., col_offset: int = ..., end_lineno: int = ..., end_col_offset: int = ... - ) -> Self: ... + if sys.version_info >= (3, 14): + def __replace__( + self, *, lineno: int = ..., col_offset: int = ..., end_lineno: int = ..., end_col_offset: int = ... + ) -> Self: ... - class match_case(AST): - __match_args__ = ("pattern", "guard", "body") - pattern: ast.pattern - guard: expr | None - body: list[stmt] - if sys.version_info >= (3, 13): - def __init__(self, pattern: ast.pattern, guard: expr | None = None, body: list[stmt] = ...) -> None: ... - elif sys.version_info >= (3, 10): - @overload - def __init__(self, pattern: ast.pattern, guard: expr | None, body: list[stmt]) -> None: ... - @overload - def __init__(self, pattern: ast.pattern, guard: expr | None = None, *, body: list[stmt]) -> None: ... +class match_case(AST): + __match_args__ = ("pattern", "guard", "body") + pattern: ast.pattern + guard: expr | None + body: list[stmt] + if sys.version_info >= (3, 13): + def __init__(self, pattern: ast.pattern, guard: expr | None = None, body: list[stmt] = ...) -> None: ... + else: + @overload + def __init__(self, pattern: ast.pattern, guard: expr | None, body: list[stmt]) -> None: ... + @overload + def __init__(self, pattern: ast.pattern, guard: expr | None = None, *, body: list[stmt]) -> None: ... - if sys.version_info >= (3, 14): - def __replace__(self, *, pattern: ast.pattern = ..., guard: expr | None = ..., body: list[stmt] = ...) -> Self: ... + if sys.version_info >= (3, 14): + def __replace__(self, *, pattern: ast.pattern = ..., guard: expr | None = ..., body: list[stmt] = ...) -> Self: ... - class Match(stmt): - __match_args__ = ("subject", "cases") - subject: expr - cases: list[match_case] - if sys.version_info >= (3, 13): - def __init__(self, subject: expr, cases: list[match_case] = ..., **kwargs: Unpack[_Attributes]) -> None: ... - else: - def __init__(self, subject: expr, cases: list[match_case], **kwargs: Unpack[_Attributes]) -> None: ... +class Match(stmt): + __match_args__ = ("subject", "cases") + subject: expr + cases: list[match_case] + if sys.version_info >= (3, 13): + def __init__(self, subject: expr, cases: list[match_case] = ..., **kwargs: Unpack[_Attributes]) -> None: ... + else: + def __init__(self, subject: expr, cases: list[match_case], **kwargs: Unpack[_Attributes]) -> None: ... - if sys.version_info >= (3, 14): - def __replace__( - self, *, subject: expr = ..., cases: list[match_case] = ..., **kwargs: Unpack[_Attributes] - ) -> Self: ... + if sys.version_info >= (3, 14): + def __replace__(self, *, subject: expr = ..., cases: list[match_case] = ..., **kwargs: Unpack[_Attributes]) -> Self: ... - class MatchValue(pattern): - __match_args__ = ("value",) - value: expr - def __init__(self, value: expr, **kwargs: Unpack[_Attributes[int]]) -> None: ... +class MatchValue(pattern): + __match_args__ = ("value",) + value: expr + def __init__(self, value: expr, **kwargs: Unpack[_Attributes[int]]) -> None: ... - if sys.version_info >= (3, 14): - def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + if sys.version_info >= (3, 14): + def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... - class MatchSingleton(pattern): - __match_args__ = ("value",) - value: bool | None - def __init__(self, value: bool | None, **kwargs: Unpack[_Attributes[int]]) -> None: ... +class MatchSingleton(pattern): + __match_args__ = ("value",) + value: bool | None + def __init__(self, value: bool | None, **kwargs: Unpack[_Attributes[int]]) -> None: ... - if sys.version_info >= (3, 14): - def __replace__(self, *, value: bool | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + if sys.version_info >= (3, 14): + def __replace__(self, *, value: bool | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... - class MatchSequence(pattern): - __match_args__ = ("patterns",) - patterns: list[pattern] - if sys.version_info >= (3, 13): - def __init__(self, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> None: ... - else: - def __init__(self, patterns: list[pattern], **kwargs: Unpack[_Attributes[int]]) -> None: ... +class MatchSequence(pattern): + __match_args__ = ("patterns",) + patterns: list[pattern] + if sys.version_info >= (3, 13): + def __init__(self, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> None: ... + else: + def __init__(self, patterns: list[pattern], **kwargs: Unpack[_Attributes[int]]) -> None: ... - if sys.version_info >= (3, 14): - def __replace__(self, *, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + if sys.version_info >= (3, 14): + def __replace__(self, *, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... - class MatchMapping(pattern): - __match_args__ = ("keys", "patterns", "rest") - keys: list[expr] - patterns: list[pattern] - rest: str | None - if sys.version_info >= (3, 13): - def __init__( - self, - keys: list[expr] = ..., - patterns: list[pattern] = ..., - rest: str | None = None, - **kwargs: Unpack[_Attributes[int]], - ) -> None: ... - else: - def __init__( - self, keys: list[expr], patterns: list[pattern], rest: str | None = None, **kwargs: Unpack[_Attributes[int]] - ) -> None: ... +class MatchMapping(pattern): + __match_args__ = ("keys", "patterns", "rest") + keys: list[expr] + patterns: list[pattern] + rest: str | None + if sys.version_info >= (3, 13): + def __init__( + self, + keys: list[expr] = ..., + patterns: list[pattern] = ..., + rest: str | None = None, + **kwargs: Unpack[_Attributes[int]], + ) -> None: ... + else: + def __init__( + self, keys: list[expr], patterns: list[pattern], rest: str | None = None, **kwargs: Unpack[_Attributes[int]] + ) -> None: ... - if sys.version_info >= (3, 14): - def __replace__( - self, - *, - keys: list[expr] = ..., - patterns: list[pattern] = ..., - rest: str | None = ..., - **kwargs: Unpack[_Attributes[int]], - ) -> Self: ... + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + keys: list[expr] = ..., + patterns: list[pattern] = ..., + rest: str | None = ..., + **kwargs: Unpack[_Attributes[int]], + ) -> Self: ... - class MatchClass(pattern): - __match_args__ = ("cls", "patterns", "kwd_attrs", "kwd_patterns") - cls: expr - patterns: list[pattern] - kwd_attrs: list[str] - kwd_patterns: list[pattern] - if sys.version_info >= (3, 13): - def __init__( - self, - cls: expr, - patterns: list[pattern] = ..., - kwd_attrs: list[str] = ..., - kwd_patterns: list[pattern] = ..., - **kwargs: Unpack[_Attributes[int]], - ) -> None: ... - else: - def __init__( - self, - cls: expr, - patterns: list[pattern], - kwd_attrs: list[str], - kwd_patterns: list[pattern], - **kwargs: Unpack[_Attributes[int]], - ) -> None: ... +class MatchClass(pattern): + __match_args__ = ("cls", "patterns", "kwd_attrs", "kwd_patterns") + cls: expr + patterns: list[pattern] + kwd_attrs: list[str] + kwd_patterns: list[pattern] + if sys.version_info >= (3, 13): + def __init__( + self, + cls: expr, + patterns: list[pattern] = ..., + kwd_attrs: list[str] = ..., + kwd_patterns: list[pattern] = ..., + **kwargs: Unpack[_Attributes[int]], + ) -> None: ... + else: + def __init__( + self, + cls: expr, + patterns: list[pattern], + kwd_attrs: list[str], + kwd_patterns: list[pattern], + **kwargs: Unpack[_Attributes[int]], + ) -> None: ... - if sys.version_info >= (3, 14): - def __replace__( - self, - *, - cls: expr = ..., - patterns: list[pattern] = ..., - kwd_attrs: list[str] = ..., - kwd_patterns: list[pattern] = ..., - **kwargs: Unpack[_Attributes[int]], - ) -> Self: ... + if sys.version_info >= (3, 14): + def __replace__( + self, + *, + cls: expr = ..., + patterns: list[pattern] = ..., + kwd_attrs: list[str] = ..., + kwd_patterns: list[pattern] = ..., + **kwargs: Unpack[_Attributes[int]], + ) -> Self: ... - class MatchStar(pattern): - __match_args__ = ("name",) - name: str | None - def __init__(self, name: str | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ... +class MatchStar(pattern): + __match_args__ = ("name",) + name: str | None + def __init__(self, name: str | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ... - if sys.version_info >= (3, 14): - def __replace__(self, *, name: str | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + if sys.version_info >= (3, 14): + def __replace__(self, *, name: str | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... - class MatchAs(pattern): - __match_args__ = ("pattern", "name") - pattern: ast.pattern | None - name: str | None - def __init__( - self, pattern: ast.pattern | None = None, name: str | None = None, **kwargs: Unpack[_Attributes[int]] - ) -> None: ... +class MatchAs(pattern): + __match_args__ = ("pattern", "name") + pattern: ast.pattern | None + name: str | None + def __init__( + self, pattern: ast.pattern | None = None, name: str | None = None, **kwargs: Unpack[_Attributes[int]] + ) -> None: ... - if sys.version_info >= (3, 14): - def __replace__( - self, *, pattern: ast.pattern | None = ..., name: str | None = ..., **kwargs: Unpack[_Attributes[int]] - ) -> Self: ... + if sys.version_info >= (3, 14): + def __replace__( + self, *, pattern: ast.pattern | None = ..., name: str | None = ..., **kwargs: Unpack[_Attributes[int]] + ) -> Self: ... - class MatchOr(pattern): - __match_args__ = ("patterns",) - patterns: list[pattern] - if sys.version_info >= (3, 13): - def __init__(self, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> None: ... - else: - def __init__(self, patterns: list[pattern], **kwargs: Unpack[_Attributes[int]]) -> None: ... +class MatchOr(pattern): + __match_args__ = ("patterns",) + patterns: list[pattern] + if sys.version_info >= (3, 13): + def __init__(self, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> None: ... + else: + def __init__(self, patterns: list[pattern], **kwargs: Unpack[_Attributes[int]]) -> None: ... - if sys.version_info >= (3, 14): - def __replace__(self, *, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... + if sys.version_info >= (3, 14): + def __replace__(self, *, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ... class type_ignore(AST): ... class TypeIgnore(type_ignore): - if sys.version_info >= (3, 10): - __match_args__ = ("lineno", "tag") + __match_args__ = ("lineno", "tag") lineno: int tag: str def __init__(self, lineno: int, tag: str) -> None: ... @@ -1743,7 +1720,104 @@ if sys.version_info < (3, 14): _T = _TypeVar("_T", bound=AST) -if sys.version_info >= (3, 13): +if sys.version_info >= (3, 15): + @overload + def parse( + source: _T, + filename: str | bytes | os.PathLike[Any] = "", + mode: Literal["exec", "eval", "func_type", "single"] = "exec", + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> _T: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any] = "", + mode: Literal["exec"] = "exec", + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Module: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["eval"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Expression: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["func_type"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> FunctionType: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any], + mode: Literal["single"], + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Interactive: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["eval"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Expression: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["func_type"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> FunctionType: ... + @overload + def parse( + source: str | ReadableBuffer, + *, + mode: Literal["single"], + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> Interactive: ... + @overload + def parse( + source: str | ReadableBuffer, + filename: str | bytes | os.PathLike[Any] = "", + mode: str = "exec", + *, + type_comments: bool = False, + feature_version: None | int | tuple[int, int] = None, + optimize: Literal[-1, 0, 1, 2] = -1, + module: str | None = None, + ) -> mod: ... +elif sys.version_info >= (3, 13): @overload def parse( source: _T, @@ -1831,7 +1905,6 @@ if sys.version_info >= (3, 13): feature_version: None | int | tuple[int, int] = None, optimize: Literal[-1, 0, 1, 2] = -1, ) -> mod: ... - else: @overload def parse( @@ -1914,7 +1987,18 @@ else: def literal_eval(node_or_string: str | AST) -> Any: ... -if sys.version_info >= (3, 13): +if sys.version_info >= (3, 15): + def dump( + node: AST, + annotate_fields: bool = True, + include_attributes: bool = False, + *, + indent: int | str | None = None, + show_empty: bool = False, + color: bool = False, + ) -> str: ... + +elif sys.version_info >= (3, 13): def dump( node: AST, annotate_fields: bool = True, @@ -2043,17 +2127,16 @@ class NodeVisitor: def visit_keyword(self, node: keyword) -> Any: ... def visit_alias(self, node: alias) -> Any: ... def visit_withitem(self, node: withitem) -> Any: ... - if sys.version_info >= (3, 10): - def visit_Match(self, node: Match) -> Any: ... - def visit_match_case(self, node: match_case) -> Any: ... - def visit_MatchValue(self, node: MatchValue) -> Any: ... - def visit_MatchSequence(self, node: MatchSequence) -> Any: ... - def visit_MatchSingleton(self, node: MatchSingleton) -> Any: ... - def visit_MatchStar(self, node: MatchStar) -> Any: ... - def visit_MatchMapping(self, node: MatchMapping) -> Any: ... - def visit_MatchClass(self, node: MatchClass) -> Any: ... - def visit_MatchAs(self, node: MatchAs) -> Any: ... - def visit_MatchOr(self, node: MatchOr) -> Any: ... + def visit_Match(self, node: Match) -> Any: ... + def visit_match_case(self, node: match_case) -> Any: ... + def visit_MatchValue(self, node: MatchValue) -> Any: ... + def visit_MatchSequence(self, node: MatchSequence) -> Any: ... + def visit_MatchSingleton(self, node: MatchSingleton) -> Any: ... + def visit_MatchStar(self, node: MatchStar) -> Any: ... + def visit_MatchMapping(self, node: MatchMapping) -> Any: ... + def visit_MatchClass(self, node: MatchClass) -> Any: ... + def visit_MatchAs(self, node: MatchAs) -> Any: ... + def visit_MatchOr(self, node: MatchOr) -> Any: ... if sys.version_info >= (3, 11): def visit_TryStar(self, node: TryStar) -> Any: ... diff --git a/mypy/typeshed/stdlib/asyncio/__init__.pyi b/mypy/typeshed/stdlib/asyncio/__init__.pyi index 23cf57aaac335..5748c85af4c6c 100644 --- a/mypy/typeshed/stdlib/asyncio/__init__.pyi +++ b/mypy/typeshed/stdlib/asyncio/__init__.pyi @@ -2,8 +2,7 @@ # Can't NOQA on a specific line: https://github.com/plinss/flake8-noqa/issues/22 import sys from collections.abc import Awaitable, Coroutine, Generator -from typing import Any, TypeVar -from typing_extensions import TypeAlias +from typing import Any, TypeAlias, TypeVar # As at runtime, this depends on all submodules defining __all__ accurately. from .base_events import * @@ -33,6 +32,24 @@ if sys.platform == "win32": else: from .unix_events import * +if sys.version_info >= (3, 14): + from .events import _AbstractEventLoopPolicy + + AbstractEventLoopPolicy = _AbstractEventLoopPolicy + +if sys.platform == "win32": + if sys.version_info >= (3, 14): + from .windows_events import _DefaultEventLoopPolicy, _WindowsProactorEventLoopPolicy, _WindowsSelectorEventLoopPolicy + + DefaultEventLoopPolicy = _DefaultEventLoopPolicy + WindowsProactorEventLoopPolicy = _WindowsProactorEventLoopPolicy + WindowsSelectorEventLoopPolicy = _WindowsSelectorEventLoopPolicy +else: + if sys.version_info >= (3, 14): + from .unix_events import _DefaultEventLoopPolicy + + DefaultEventLoopPolicy = _DefaultEventLoopPolicy + if sys.platform == "win32": if sys.version_info >= (3, 14): diff --git a/mypy/typeshed/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi index 0d8ac2d474914..1fae6d6595058 100644 --- a/mypy/typeshed/stdlib/asyncio/base_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_events.pyi @@ -11,8 +11,8 @@ from collections.abc import Callable, Iterable, Sequence from concurrent.futures import Executor, ThreadPoolExecutor from contextvars import Context from socket import AddressFamily, AddressInfo, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Literal, TypeVar, overload -from typing_extensions import TypeAlias, TypeVarTuple, Unpack +from typing import IO, Any, Literal, TypeAlias, TypeVar, overload +from typing_extensions import TypeVarTuple, Unpack # Keep asyncio.__all__ updated with any changes to __all__ here __all__ = ("BaseEventLoop", "Server") @@ -117,6 +117,7 @@ class BaseEventLoop(AbstractEventLoop): flags: int = 0, ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ... async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = 0) -> tuple[str, str]: ... + if sys.version_info >= (3, 12): @overload async def create_connection( diff --git a/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi index a5fe24e8768b7..36f0f6099cbc6 100644 --- a/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi @@ -1,8 +1,7 @@ import subprocess from collections import deque from collections.abc import Callable, Sequence -from typing import IO, Any -from typing_extensions import TypeAlias +from typing import IO, Any, TypeAlias from . import events, futures, protocols, transports diff --git a/mypy/typeshed/stdlib/asyncio/coroutines.pyi b/mypy/typeshed/stdlib/asyncio/coroutines.pyi index 777961d804412..7599c692949bd 100644 --- a/mypy/typeshed/stdlib/asyncio/coroutines.pyi +++ b/mypy/typeshed/stdlib/asyncio/coroutines.pyi @@ -1,7 +1,7 @@ import sys from collections.abc import Awaitable, Callable, Coroutine -from typing import Any, TypeVar, overload -from typing_extensions import ParamSpec, TypeGuard, TypeIs, deprecated +from typing import Any, ParamSpec, TypeGuard, TypeVar, overload +from typing_extensions import TypeIs, deprecated # Keep asyncio.__all__ updated with any changes to __all__ here if sys.version_info >= (3, 11): @@ -32,11 +32,9 @@ if sys.version_info >= (3, 11): @overload @deprecated("Deprecated since Python 3.14. Use `inspect.iscoroutinefunction()` instead.") def iscoroutinefunction(func: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ... - else: # Sometimes needed in Python < 3.11 due to the fact that it supports @coroutine # which was removed in 3.11 which the inspect version doesn't support. - @overload def iscoroutinefunction(func: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ... @overload diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index 4f2f45355f5ba..d4be117b14177 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -12,8 +12,8 @@ from collections.abc import Callable, Sequence from concurrent.futures import Executor from contextvars import Context from socket import AddressFamily, AddressInfo, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Literal, Protocol, TypeVar, overload, type_check_only -from typing_extensions import Self, TypeAlias, TypeVarTuple, Unpack, deprecated +from typing import IO, Any, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, TypeVarTuple, Unpack, deprecated from . import _AwaitableLike, _CoroutineLike from .base_events import Server @@ -208,6 +208,7 @@ class AbstractEventLoop: ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ... @abstractmethod async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = 0) -> tuple[str, str]: ... + if sys.version_info >= (3, 11): @overload @abstractmethod @@ -467,7 +468,7 @@ class AbstractEventLoop: ssl_handshake_timeout: float | None = None, ssl_shutdown_timeout: float | None = None, ) -> tuple[Transport, _ProtocolT]: ... - elif sys.version_info >= (3, 10): + else: async def connect_accepted_socket( self, protocol_factory: Callable[[], _ProtocolT], @@ -631,18 +632,12 @@ else: @abstractmethod def new_event_loop(self) -> AbstractEventLoop: ... # Child processes handling (Unix only). - if sys.version_info >= (3, 12): - @abstractmethod - @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") - def get_child_watcher(self) -> AbstractChildWatcher: ... - @abstractmethod - @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") - def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... - else: - @abstractmethod - def get_child_watcher(self) -> AbstractChildWatcher: ... - @abstractmethod - def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... + @abstractmethod + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + def get_child_watcher(self) -> AbstractChildWatcher: ... + @abstractmethod + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... AbstractEventLoopPolicy = _AbstractEventLoopPolicy @@ -661,25 +656,16 @@ else: if sys.version_info >= (3, 14): def _get_event_loop_policy() -> _AbstractEventLoopPolicy: ... def _set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ... - @deprecated("Deprecated since Python 3.14; will be removed in Python 3.16.") - def get_event_loop_policy() -> _AbstractEventLoopPolicy: ... - @deprecated("Deprecated since Python 3.14; will be removed in Python 3.16.") - def set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ... - -else: - def get_event_loop_policy() -> _AbstractEventLoopPolicy: ... - def set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ... +@deprecated("Deprecated since Python 3.14; will be removed in Python 3.16.") +def get_event_loop_policy() -> _AbstractEventLoopPolicy: ... +@deprecated("Deprecated since Python 3.14; will be removed in Python 3.16.") +def set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ... def set_event_loop(loop: AbstractEventLoop | None) -> None: ... def new_event_loop() -> AbstractEventLoop: ... if sys.version_info < (3, 14): - if sys.version_info >= (3, 12): - @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") - def get_child_watcher() -> AbstractChildWatcher: ... - @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") - def set_child_watcher(watcher: AbstractChildWatcher) -> None: ... - - else: - def get_child_watcher() -> AbstractChildWatcher: ... - def set_child_watcher(watcher: AbstractChildWatcher) -> None: ... + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + def get_child_watcher() -> AbstractChildWatcher: ... + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + def set_child_watcher(watcher: AbstractChildWatcher) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/format_helpers.pyi b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi index 597eb9e56e1a1..ff830a3b73d45 100644 --- a/mypy/typeshed/stdlib/asyncio/format_helpers.pyi +++ b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi @@ -3,8 +3,7 @@ import sys import traceback from collections.abc import Iterable from types import FrameType, FunctionType -from typing import Any, overload, type_check_only -from typing_extensions import TypeAlias +from typing import Any, TypeAlias, overload, type_check_only @type_check_only class _HasWrapper: diff --git a/mypy/typeshed/stdlib/asyncio/graph.pyi b/mypy/typeshed/stdlib/asyncio/graph.pyi index 18a8a6457d757..2f89de71b16b6 100644 --- a/mypy/typeshed/stdlib/asyncio/graph.pyi +++ b/mypy/typeshed/stdlib/asyncio/graph.pyi @@ -22,6 +22,7 @@ if sys.version_info >= (3, 14): def capture_call_graph(future: None = None, /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: ... @overload def capture_call_graph(future: Future[Any], /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: ... + def format_call_graph(future: Future[Any] | None = None, /, *, depth: int = 1, limit: int | None = None) -> str: ... def print_call_graph( future: Future[Any] | None = None, /, *, file: SupportsWrite[str] | None = None, depth: int = 1, limit: int | None = None diff --git a/mypy/typeshed/stdlib/asyncio/locks.pyi b/mypy/typeshed/stdlib/asyncio/locks.pyi index 17390b0c5a0ee..4420d02fcd269 100644 --- a/mypy/typeshed/stdlib/asyncio/locks.pyi +++ b/mypy/typeshed/stdlib/asyncio/locks.pyi @@ -7,13 +7,8 @@ from types import TracebackType from typing import Any, Literal, TypeVar from typing_extensions import Self -from .events import AbstractEventLoop from .futures import Future - -if sys.version_info >= (3, 10): - from .mixins import _LoopBoundMixin -else: - _LoopBoundMixin = object +from .mixins import _LoopBoundMixin # Keep asyncio.__all__ updated with any changes to __all__ here if sys.version_info >= (3, 11): @@ -31,22 +26,14 @@ class _ContextManagerMixin: class Lock(_ContextManagerMixin, _LoopBoundMixin): _waiters: deque[Future[Any]] | None - if sys.version_info >= (3, 10): - def __init__(self) -> None: ... - else: - def __init__(self, *, loop: AbstractEventLoop | None = None) -> None: ... - + def __init__(self) -> None: ... def locked(self) -> bool: ... async def acquire(self) -> Literal[True]: ... def release(self) -> None: ... class Event(_LoopBoundMixin): _waiters: deque[Future[Any]] - if sys.version_info >= (3, 10): - def __init__(self) -> None: ... - else: - def __init__(self, *, loop: AbstractEventLoop | None = None) -> None: ... - + def __init__(self) -> None: ... def is_set(self) -> bool: ... def set(self) -> None: ... def clear(self) -> None: ... @@ -54,11 +41,7 @@ class Event(_LoopBoundMixin): class Condition(_ContextManagerMixin, _LoopBoundMixin): _waiters: deque[Future[Any]] - if sys.version_info >= (3, 10): - def __init__(self, lock: Lock | None = None) -> None: ... - else: - def __init__(self, lock: Lock | None = None, *, loop: AbstractEventLoop | None = None) -> None: ... - + def __init__(self, lock: Lock | None = None) -> None: ... def locked(self) -> bool: ... async def acquire(self) -> Literal[True]: ... def release(self) -> None: ... @@ -70,11 +53,7 @@ class Condition(_ContextManagerMixin, _LoopBoundMixin): class Semaphore(_ContextManagerMixin, _LoopBoundMixin): _value: int _waiters: deque[Future[Any]] | None - if sys.version_info >= (3, 10): - def __init__(self, value: int = 1) -> None: ... - else: - def __init__(self, value: int = 1, *, loop: AbstractEventLoop | None = None) -> None: ... - + def __init__(self, value: int = 1) -> None: ... def locked(self) -> bool: ... async def acquire(self) -> Literal[True]: ... def release(self) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi index 909d671df289d..09c096d40f04b 100644 --- a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi @@ -1,4 +1,3 @@ -import sys from collections.abc import Mapping from socket import socket from typing import Any, ClassVar, Literal @@ -20,27 +19,16 @@ class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTr def __del__(self) -> None: ... class _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTransport): - if sys.version_info >= (3, 10): - def __init__( - self, - loop: events.AbstractEventLoop, - sock: socket, - protocol: streams.StreamReaderProtocol, - waiter: futures.Future[Any] | None = None, - extra: Mapping[Any, Any] | None = None, - server: events.AbstractServer | None = None, - buffer_size: int = 65536, - ) -> None: ... - else: - def __init__( - self, - loop: events.AbstractEventLoop, - sock: socket, - protocol: streams.StreamReaderProtocol, - waiter: futures.Future[Any] | None = None, - extra: Mapping[Any, Any] | None = None, - server: events.AbstractServer | None = None, - ) -> None: ... + def __init__( + self, + loop: events.AbstractEventLoop, + sock: socket, + protocol: streams.StreamReaderProtocol, + waiter: futures.Future[Any] | None = None, + extra: Mapping[Any, Any] | None = None, + server: events.AbstractServer | None = None, + buffer_size: int = 65536, + ) -> None: ... class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport, transports.WriteTransport): ... class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport): ... diff --git a/mypy/typeshed/stdlib/asyncio/queues.pyi b/mypy/typeshed/stdlib/asyncio/queues.pyi index 2fa2226d0e6ae..de7c4879d348e 100644 --- a/mypy/typeshed/stdlib/asyncio/queues.pyi +++ b/mypy/typeshed/stdlib/asyncio/queues.pyi @@ -1,13 +1,9 @@ import sys from _typeshed import SupportsRichComparisonT -from asyncio.events import AbstractEventLoop from types import GenericAlias from typing import Any, Generic, TypeVar -if sys.version_info >= (3, 10): - from .mixins import _LoopBoundMixin -else: - _LoopBoundMixin = object +from .mixins import _LoopBoundMixin class QueueEmpty(Exception): ... class QueueFull(Exception): ... @@ -24,14 +20,8 @@ _T = TypeVar("_T") if sys.version_info >= (3, 13): class QueueShutDown(Exception): ... -# If Generic[_T] is last and _LoopBoundMixin is object, pyright is unhappy. -# We can remove the noqa pragma when dropping 3.9 support. -class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059 - if sys.version_info >= (3, 10): - def __init__(self, maxsize: int = 0) -> None: ... - else: - def __init__(self, maxsize: int = 0, *, loop: AbstractEventLoop | None = None) -> None: ... - +class Queue(_LoopBoundMixin, Generic[_T]): + def __init__(self, maxsize: int = 0) -> None: ... def _init(self, maxsize: int) -> None: ... def _get(self) -> _T: ... def _put(self, item: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/sslproto.pyi b/mypy/typeshed/stdlib/asyncio/sslproto.pyi index ab102f124c2e8..72b4ea449e867 100644 --- a/mypy/typeshed/stdlib/asyncio/sslproto.pyi +++ b/mypy/typeshed/stdlib/asyncio/sslproto.pyi @@ -3,8 +3,7 @@ import sys from collections import deque from collections.abc import Callable from enum import Enum -from typing import Any, ClassVar, Final, Literal -from typing_extensions import TypeAlias +from typing import Any, ClassVar, Final, Literal, TypeAlias from . import constants, events, futures, protocols, transports diff --git a/mypy/typeshed/stdlib/asyncio/streams.pyi b/mypy/typeshed/stdlib/asyncio/streams.pyi index 33cffb11ed780..9e76c69d8732e 100644 --- a/mypy/typeshed/stdlib/asyncio/streams.pyi +++ b/mypy/typeshed/stdlib/asyncio/streams.pyi @@ -3,8 +3,8 @@ import sys from _typeshed import ReadableBuffer, StrPath from collections.abc import Awaitable, Callable, Iterable, Sequence, Sized from types import ModuleType -from typing import Any, Protocol, SupportsIndex, type_check_only -from typing_extensions import Self, TypeAlias +from typing import Any, Protocol, SupportsIndex, TypeAlias, type_check_only +from typing_extensions import Self from . import events, protocols, transports from .base_events import Server @@ -28,67 +28,32 @@ _ClientConnectedCallback: TypeAlias = Callable[[StreamReader, StreamWriter], Awa @type_check_only class _ReaduntilBuffer(ReadableBuffer, Sized, Protocol): ... -if sys.version_info >= (3, 10): - async def open_connection( - host: str | None = None, - port: int | str | None = None, - *, - limit: int = 65536, - ssl_handshake_timeout: float | None = None, - **kwds: Any, - ) -> tuple[StreamReader, StreamWriter]: ... - async def start_server( - client_connected_cb: _ClientConnectedCallback, - host: str | Sequence[str] | None = None, - port: int | str | None = None, - *, - limit: int = 65536, - ssl_handshake_timeout: float | None = None, - **kwds: Any, - ) -> Server: ... +async def open_connection( + host: str | None = None, + port: int | str | None = None, + *, + limit: int = 65536, + ssl_handshake_timeout: float | None = None, + **kwds: Any, +) -> tuple[StreamReader, StreamWriter]: ... +async def start_server( + client_connected_cb: _ClientConnectedCallback, + host: str | Sequence[str] | None = None, + port: int | str | None = None, + *, + limit: int = 65536, + ssl_handshake_timeout: float | None = None, + **kwds: Any, +) -> Server: ... -else: - async def open_connection( - host: str | None = None, - port: int | str | None = None, - *, - loop: events.AbstractEventLoop | None = None, - limit: int = 65536, - ssl_handshake_timeout: float | None = None, - **kwds: Any, +if sys.platform != "win32": + async def open_unix_connection( + path: StrPath | None = None, *, limit: int = 65536, **kwds: Any ) -> tuple[StreamReader, StreamWriter]: ... - async def start_server( - client_connected_cb: _ClientConnectedCallback, - host: str | None = None, - port: int | str | None = None, - *, - loop: events.AbstractEventLoop | None = None, - limit: int = 65536, - ssl_handshake_timeout: float | None = None, - **kwds: Any, + async def start_unix_server( + client_connected_cb: _ClientConnectedCallback, path: StrPath | None = None, *, limit: int = 65536, **kwds: Any ) -> Server: ... -if sys.platform != "win32": - if sys.version_info >= (3, 10): - async def open_unix_connection( - path: StrPath | None = None, *, limit: int = 65536, **kwds: Any - ) -> tuple[StreamReader, StreamWriter]: ... - async def start_unix_server( - client_connected_cb: _ClientConnectedCallback, path: StrPath | None = None, *, limit: int = 65536, **kwds: Any - ) -> Server: ... - else: - async def open_unix_connection( - path: StrPath | None = None, *, loop: events.AbstractEventLoop | None = None, limit: int = 65536, **kwds: Any - ) -> tuple[StreamReader, StreamWriter]: ... - async def start_unix_server( - client_connected_cb: _ClientConnectedCallback, - path: StrPath | None = None, - *, - loop: events.AbstractEventLoop | None = None, - limit: int = 65536, - **kwds: Any, - ) -> Server: ... - class FlowControlMixin(protocols.Protocol): def __init__(self, loop: events.AbstractEventLoop | None = None) -> None: ... @@ -141,7 +106,7 @@ class StreamWriter: class StreamReader: def __init__(self, limit: int = 65536, loop: events.AbstractEventLoop | None = None) -> None: ... - def exception(self) -> Exception: ... + def exception(self) -> Exception | None: ... def set_exception(self, exc: Exception) -> None: ... def set_transport(self, transport: transports.BaseTransport) -> None: ... def feed_eof(self) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/subprocess.pyi b/mypy/typeshed/stdlib/asyncio/subprocess.pyi index ceee2b5b90a09..6405e5ae14741 100644 --- a/mypy/typeshed/stdlib/asyncio/subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/subprocess.pyi @@ -101,7 +101,7 @@ if sys.version_info >= (3, 11): pipesize: int = -1, ) -> Process: ... -elif sys.version_info >= (3, 10): +else: async def create_subprocess_shell( cmd: str | bytes, stdin: int | IO[Any] | None = None, @@ -164,67 +164,3 @@ elif sys.version_info >= (3, 10): umask: int = -1, pipesize: int = -1, ) -> Process: ... - -else: # >= 3.9 - async def create_subprocess_shell( - cmd: str | bytes, - stdin: int | IO[Any] | None = None, - stdout: int | IO[Any] | None = None, - stderr: int | IO[Any] | None = None, - loop: events.AbstractEventLoop | None = None, - limit: int = 65536, - *, - # These parameters are forced to these values by BaseEventLoop.subprocess_shell - universal_newlines: Literal[False] = False, - shell: Literal[True] = True, - bufsize: Literal[0] = 0, - encoding: None = None, - errors: None = None, - text: Literal[False] | None = None, - # These parameters are taken by subprocess.Popen, which this ultimately delegates to - executable: StrOrBytesPath | None = None, - preexec_fn: Callable[[], Any] | None = None, - close_fds: bool = True, - cwd: StrOrBytesPath | None = None, - env: subprocess._ENV | None = None, - startupinfo: Any | None = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - group: None | str | int = None, - extra_groups: None | Collection[str | int] = None, - user: None | str | int = None, - umask: int = -1, - ) -> Process: ... - async def create_subprocess_exec( - program: StrOrBytesPath, - *args: StrOrBytesPath, - stdin: int | IO[Any] | None = None, - stdout: int | IO[Any] | None = None, - stderr: int | IO[Any] | None = None, - loop: events.AbstractEventLoop | None = None, - limit: int = 65536, - # These parameters are forced to these values by BaseEventLoop.subprocess_exec - universal_newlines: Literal[False] = False, - shell: Literal[False] = False, - bufsize: Literal[0] = 0, - encoding: None = None, - errors: None = None, - text: Literal[False] | None = None, - # These parameters are taken by subprocess.Popen, which this ultimately delegates to - executable: StrOrBytesPath | None = None, - preexec_fn: Callable[[], Any] | None = None, - close_fds: bool = True, - cwd: StrOrBytesPath | None = None, - env: subprocess._ENV | None = None, - startupinfo: Any | None = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - group: None | str | int = None, - extra_groups: None | Collection[str | int] = None, - user: None | str | int = None, - umask: int = -1, - ) -> Process: ... diff --git a/mypy/typeshed/stdlib/asyncio/taskgroups.pyi b/mypy/typeshed/stdlib/asyncio/taskgroups.pyi index 2968b07197614..886a79c4beb5a 100644 --- a/mypy/typeshed/stdlib/asyncio/taskgroups.pyi +++ b/mypy/typeshed/stdlib/asyncio/taskgroups.pyi @@ -37,3 +37,5 @@ class TaskGroup: ) -> Task[_T]: ... def _on_task_done(self, task: Task[object]) -> None: ... + if sys.version_info >= (3, 15): + def cancel(self) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index 06e9f381a89ff..66c31f15e6fb1 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -8,8 +8,7 @@ from _asyncio import ( _unregister_task as _unregister_task, ) from collections.abc import AsyncIterator, Awaitable, Coroutine, Generator, Iterable, Iterator -from typing import Any, Final, Literal, Protocol, TypeVar, overload, type_check_only -from typing_extensions import TypeAlias +from typing import Any, Final, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only from . import _CoroutineLike from .events import AbstractEventLoop @@ -88,17 +87,12 @@ ALL_COMPLETED: Final = concurrent.futures.ALL_COMPLETED if sys.version_info >= (3, 13): @type_check_only - class _SyncAndAsyncIterator(Iterator[_T_co], AsyncIterator[_T_co], Protocol[_T_co]): ... + class _SyncAndAsyncIterator(Iterator[Coroutine[Any, Any, _T]], AsyncIterator[Future[_T]], Protocol[_T]): ... - def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> _SyncAndAsyncIterator[Future[_T]]: ... - -elif sys.version_info >= (3, 10): - def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> Iterator[Future[_T]]: ... + def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> _SyncAndAsyncIterator[_T]: ... else: - def as_completed( - fs: Iterable[_FutureLike[_T]], *, loop: AbstractEventLoop | None = None, timeout: float | None = None - ) -> Iterator[Future[_T]]: ... + def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> Iterator[Future[_T]]: ... @overload def ensure_future(coro_or_future: _FT, *, loop: AbstractEventLoop | None = None) -> _FT: ... # type: ignore[overload-overlap] @@ -111,269 +105,133 @@ def ensure_future(coro_or_future: Awaitable[_T], *, loop: AbstractEventLoop | No # typing PR #1550 for discussion. # # N.B. Having overlapping overloads is the only way to get acceptable type inference in all edge cases. -if sys.version_info >= (3, 10): - @overload - def gather(coro_or_future1: _FutureLike[_T1], /, *, return_exceptions: Literal[False] = False) -> Future[tuple[_T1]]: ... # type: ignore[overload-overlap] - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], coro_or_future2: _FutureLike[_T2], /, *, return_exceptions: Literal[False] = False - ) -> Future[tuple[_T1, _T2]]: ... - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - /, - *, - return_exceptions: Literal[False] = False, - ) -> Future[tuple[_T1, _T2, _T3]]: ... - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - coro_or_future4: _FutureLike[_T4], - /, - *, - return_exceptions: Literal[False] = False, - ) -> Future[tuple[_T1, _T2, _T3, _T4]]: ... - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - coro_or_future4: _FutureLike[_T4], - coro_or_future5: _FutureLike[_T5], - /, - *, - return_exceptions: Literal[False] = False, - ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5]]: ... - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - coro_or_future4: _FutureLike[_T4], - coro_or_future5: _FutureLike[_T5], - coro_or_future6: _FutureLike[_T6], - /, - *, - return_exceptions: Literal[False] = False, - ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... - @overload - def gather(*coros_or_futures: _FutureLike[_T], return_exceptions: Literal[False] = False) -> Future[list[_T]]: ... # type: ignore[overload-overlap] - @overload - def gather(coro_or_future1: _FutureLike[_T1], /, *, return_exceptions: bool) -> Future[tuple[_T1 | BaseException]]: ... - @overload - def gather( - coro_or_future1: _FutureLike[_T1], coro_or_future2: _FutureLike[_T2], /, *, return_exceptions: bool - ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ... - @overload - def gather( - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - /, - *, - return_exceptions: bool, - ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException]]: ... - @overload - def gather( - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - coro_or_future4: _FutureLike[_T4], - /, - *, - return_exceptions: bool, - ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException]]: ... - @overload - def gather( - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - coro_or_future4: _FutureLike[_T4], - coro_or_future5: _FutureLike[_T5], - /, - *, - return_exceptions: bool, - ) -> Future[ - tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException, _T5 | BaseException] - ]: ... - @overload - def gather( - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - coro_or_future4: _FutureLike[_T4], - coro_or_future5: _FutureLike[_T5], - coro_or_future6: _FutureLike[_T6], - /, - *, - return_exceptions: bool, - ) -> Future[ - tuple[ - _T1 | BaseException, - _T2 | BaseException, - _T3 | BaseException, - _T4 | BaseException, - _T5 | BaseException, - _T6 | BaseException, - ] - ]: ... - @overload - def gather(*coros_or_futures: _FutureLike[_T], return_exceptions: bool) -> Future[list[_T | BaseException]]: ... - -else: - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], /, *, loop: AbstractEventLoop | None = None, return_exceptions: Literal[False] = False - ) -> Future[tuple[_T1]]: ... - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - /, - *, - loop: AbstractEventLoop | None = None, - return_exceptions: Literal[False] = False, - ) -> Future[tuple[_T1, _T2]]: ... - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - /, - *, - loop: AbstractEventLoop | None = None, - return_exceptions: Literal[False] = False, - ) -> Future[tuple[_T1, _T2, _T3]]: ... - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - coro_or_future4: _FutureLike[_T4], - /, - *, - loop: AbstractEventLoop | None = None, - return_exceptions: Literal[False] = False, - ) -> Future[tuple[_T1, _T2, _T3, _T4]]: ... - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - coro_or_future4: _FutureLike[_T4], - coro_or_future5: _FutureLike[_T5], - /, - *, - loop: AbstractEventLoop | None = None, - return_exceptions: Literal[False] = False, - ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5]]: ... - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - coro_or_future4: _FutureLike[_T4], - coro_or_future5: _FutureLike[_T5], - coro_or_future6: _FutureLike[_T6], - /, - *, - loop: AbstractEventLoop | None = None, - return_exceptions: Literal[False] = False, - ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... - @overload - def gather( # type: ignore[overload-overlap] - *coros_or_futures: _FutureLike[_T], loop: AbstractEventLoop | None = None, return_exceptions: Literal[False] = False - ) -> Future[list[_T]]: ... - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], /, *, loop: AbstractEventLoop | None = None, return_exceptions: bool - ) -> Future[tuple[_T1 | BaseException]]: ... - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - /, - *, - loop: AbstractEventLoop | None = None, - return_exceptions: bool, - ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ... - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - /, - *, - loop: AbstractEventLoop | None = None, - return_exceptions: bool, - ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException]]: ... - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - coro_or_future4: _FutureLike[_T4], - /, - *, - loop: AbstractEventLoop | None = None, - return_exceptions: bool, - ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException]]: ... - @overload - def gather( # type: ignore[overload-overlap] - coro_or_future1: _FutureLike[_T1], - coro_or_future2: _FutureLike[_T2], - coro_or_future3: _FutureLike[_T3], - coro_or_future4: _FutureLike[_T4], - coro_or_future5: _FutureLike[_T5], - coro_or_future6: _FutureLike[_T6], - /, - *, - loop: AbstractEventLoop | None = None, - return_exceptions: bool, - ) -> Future[ - tuple[ - _T1 | BaseException, - _T2 | BaseException, - _T3 | BaseException, - _T4 | BaseException, - _T5 | BaseException, - _T6 | BaseException, - ] - ]: ... - @overload - def gather( - *coros_or_futures: _FutureLike[_T], loop: AbstractEventLoop | None = None, return_exceptions: bool - ) -> Future[list[_T | BaseException]]: ... +@overload +def gather(coro_or_future1: _FutureLike[_T1], /, *, return_exceptions: Literal[False] = False) -> Future[tuple[_T1]]: ... # type: ignore[overload-overlap] +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], coro_or_future2: _FutureLike[_T2], /, *, return_exceptions: Literal[False] = False +) -> Future[tuple[_T1, _T2]]: ... +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + /, + *, + return_exceptions: Literal[False] = False, +) -> Future[tuple[_T1, _T2, _T3]]: ... +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + /, + *, + return_exceptions: Literal[False] = False, +) -> Future[tuple[_T1, _T2, _T3, _T4]]: ... +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + /, + *, + return_exceptions: Literal[False] = False, +) -> Future[tuple[_T1, _T2, _T3, _T4, _T5]]: ... +@overload +def gather( # type: ignore[overload-overlap] + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + coro_or_future6: _FutureLike[_T6], + /, + *, + return_exceptions: Literal[False] = False, +) -> Future[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... +@overload +def gather(*coros_or_futures: _FutureLike[_T], return_exceptions: Literal[False] = False) -> Future[list[_T]]: ... # type: ignore[overload-overlap] +@overload +def gather(coro_or_future1: _FutureLike[_T1], /, *, return_exceptions: bool) -> Future[tuple[_T1 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], coro_or_future2: _FutureLike[_T2], /, *, return_exceptions: bool +) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + /, + *, + return_exceptions: bool, +) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + /, + *, + return_exceptions: bool, +) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + /, + *, + return_exceptions: bool, +) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException, _T5 | BaseException]]: ... +@overload +def gather( + coro_or_future1: _FutureLike[_T1], + coro_or_future2: _FutureLike[_T2], + coro_or_future3: _FutureLike[_T3], + coro_or_future4: _FutureLike[_T4], + coro_or_future5: _FutureLike[_T5], + coro_or_future6: _FutureLike[_T6], + /, + *, + return_exceptions: bool, +) -> Future[ + tuple[ + _T1 | BaseException, + _T2 | BaseException, + _T3 | BaseException, + _T4 | BaseException, + _T5 | BaseException, + _T6 | BaseException, + ] +]: ... +@overload +def gather(*coros_or_futures: _FutureLike[_T], return_exceptions: bool) -> Future[list[_T | BaseException]]: ... # unlike some asyncio apis, This does strict runtime checking of actually being a coroutine, not of any future-like. def run_coroutine_threadsafe(coro: Coroutine[Any, Any, _T], loop: AbstractEventLoop) -> concurrent.futures.Future[_T]: ... +def shield(arg: _FutureLike[_T]) -> Future[_T]: ... -if sys.version_info >= (3, 10): - def shield(arg: _FutureLike[_T]) -> Future[_T]: ... - @overload - async def sleep(delay: float) -> None: ... - @overload - async def sleep(delay: float, result: _T) -> _T: ... - async def wait_for(fut: _FutureLike[_T], timeout: float | None) -> _T: ... +@overload +async def sleep(delay: float) -> None: ... +@overload +async def sleep(delay: float, result: _T) -> _T: ... -else: - def shield(arg: _FutureLike[_T], *, loop: AbstractEventLoop | None = None) -> Future[_T]: ... - @overload - async def sleep(delay: float, *, loop: AbstractEventLoop | None = None) -> None: ... - @overload - async def sleep(delay: float, result: _T, *, loop: AbstractEventLoop | None = None) -> _T: ... - async def wait_for(fut: _FutureLike[_T], timeout: float | None, *, loop: AbstractEventLoop | None = None) -> _T: ... +async def wait_for(fut: _FutureLike[_T], timeout: float | None) -> _T: ... if sys.version_info >= (3, 11): async def wait( fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" ) -> tuple[set[_FT], set[_FT]]: ... -elif sys.version_info >= (3, 10): +else: @overload async def wait( # type: ignore[overload-overlap] fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" @@ -383,24 +241,6 @@ elif sys.version_info >= (3, 10): fs: Iterable[Awaitable[_T]], *, timeout: float | None = None, return_when: str = "ALL_COMPLETED" ) -> tuple[set[Task[_T]], set[Task[_T]]]: ... -else: - @overload - async def wait( # type: ignore[overload-overlap] - fs: Iterable[_FT], - *, - loop: AbstractEventLoop | None = None, - timeout: float | None = None, - return_when: str = "ALL_COMPLETED", - ) -> tuple[set[_FT], set[_FT]]: ... - @overload - async def wait( - fs: Iterable[Awaitable[_T]], - *, - loop: AbstractEventLoop | None = None, - timeout: float | None = None, - return_when: str = "ALL_COMPLETED", - ) -> tuple[set[Task[_T]], set[Task[_T]]]: ... - if sys.version_info >= (3, 12): _TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co] else: diff --git a/mypy/typeshed/stdlib/asyncio/threads.pyi b/mypy/typeshed/stdlib/asyncio/threads.pyi index 00aae2ea814cb..f1d8829180982 100644 --- a/mypy/typeshed/stdlib/asyncio/threads.pyi +++ b/mypy/typeshed/stdlib/asyncio/threads.pyi @@ -1,6 +1,5 @@ from collections.abc import Callable -from typing import TypeVar -from typing_extensions import ParamSpec +from typing import ParamSpec, TypeVar # Keep asyncio.__all__ updated with any changes to __all__ here __all__ = ("to_thread",) diff --git a/mypy/typeshed/stdlib/asyncio/tools.pyi b/mypy/typeshed/stdlib/asyncio/tools.pyi index bc8b809b9c055..36c65541c9cd0 100644 --- a/mypy/typeshed/stdlib/asyncio/tools.pyi +++ b/mypy/typeshed/stdlib/asyncio/tools.pyi @@ -42,5 +42,10 @@ def build_task_table(result: Iterable[_AwaitedInfo]) -> list[list[int | str]]: . if sys.version_info >= (3, 14): def exit_with_permission_help_text() -> None: ... -def display_awaited_by_tasks_table(pid: SupportsIndex) -> None: ... -def display_awaited_by_tasks_tree(pid: SupportsIndex) -> None: ... +if sys.version_info >= (3, 15): + def display_awaited_by_tasks_table(pid: SupportsIndex, retries: SupportsIndex = 3) -> None: ... + def display_awaited_by_tasks_tree(pid: SupportsIndex, retries: SupportsIndex = 3) -> None: ... + +else: + def display_awaited_by_tasks_table(pid: SupportsIndex) -> None: ... + def display_awaited_by_tasks_tree(pid: SupportsIndex) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/trsock.pyi b/mypy/typeshed/stdlib/asyncio/trsock.pyi index d3e95559ebefa..f621240d668a2 100644 --- a/mypy/typeshed/stdlib/asyncio/trsock.pyi +++ b/mypy/typeshed/stdlib/asyncio/trsock.pyi @@ -4,8 +4,8 @@ from _typeshed import ReadableBuffer from builtins import type as Type # alias to avoid name clashes with property named "type" from collections.abc import Iterable from types import TracebackType -from typing import Any, BinaryIO, NoReturn, overload -from typing_extensions import TypeAlias, deprecated +from typing import Any, BinaryIO, NoReturn, TypeAlias, overload +from typing_extensions import deprecated # These are based in socket, maybe move them out into _typeshed.pyi or such _Address: TypeAlias = socket._Address @@ -27,14 +27,17 @@ class TransportSocket: def dup(self) -> socket.socket: ... def get_inheritable(self) -> bool: ... def shutdown(self, how: int) -> None: ... + @overload def getsockopt(self, level: int, optname: int) -> int: ... @overload def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... + @overload def setsockopt(self, level: int, optname: int, value: int | ReadableBuffer) -> None: ... @overload def setsockopt(self, level: int, optname: int, value: None, optlen: int) -> None: ... + def getpeername(self) -> _RetAddress: ... def getsockname(self) -> _RetAddress: ... def getsockbyname(self) -> NoReturn: ... # This method doesn't exist on socket, yet is passed through? @@ -51,6 +54,7 @@ class TransportSocket: def connect_ex(self, address: _Address) -> int: ... @deprecated("Removed in Python 3.11") def bind(self, address: _Address) -> None: ... + if sys.platform == "win32": @deprecated("Removed in Python 3.11") def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> None: ... @@ -68,6 +72,7 @@ class TransportSocket: def close(self) -> None: ... @deprecated("Removed in Python 3.11") def detach(self) -> int: ... + if sys.platform == "linux": @deprecated("Removed in Python 3.11") def sendmsg_afalg( @@ -88,18 +93,21 @@ class TransportSocket: address: _Address | None = None, /, ) -> int: ... + @overload @deprecated("Removed in Python 3.11.") def sendto(self, data: ReadableBuffer, address: _Address) -> int: ... @overload @deprecated("Removed in Python 3.11.") def sendto(self, data: ReadableBuffer, flags: int, address: _Address) -> int: ... + @deprecated("Removed in Python 3.11.") def send(self, data: ReadableBuffer, flags: int = 0) -> int: ... @deprecated("Removed in Python 3.11.") def sendall(self, data: ReadableBuffer, flags: int = 0) -> None: ... @deprecated("Removed in Python 3.11.") def set_inheritable(self, inheritable: bool) -> None: ... + if sys.platform == "win32": @deprecated("Removed in Python 3.11.") def share(self, process_id: int) -> bytes: ... diff --git a/mypy/typeshed/stdlib/asyncio/unix_events.pyi b/mypy/typeshed/stdlib/asyncio/unix_events.pyi index 54a2a039749e3..368cac38302f6 100644 --- a/mypy/typeshed/stdlib/asyncio/unix_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/unix_events.pyi @@ -95,6 +95,7 @@ if sys.platform != "win32": if sys.version_info >= (3, 12): # Doesn't actually have ABCMeta metaclass at runtime, but mypy complains if we don't have it in the stub. # See discussion in #7412 + @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") class BaseChildWatcher(AbstractChildWatcher, metaclass=ABCMeta): def close(self) -> None: ... def is_active(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/asyncore.pyi b/mypy/typeshed/stdlib/asyncore.pyi index 36d1862fdda78..96f9f637c7333 100644 --- a/mypy/typeshed/stdlib/asyncore.pyi +++ b/mypy/typeshed/stdlib/asyncore.pyi @@ -1,8 +1,7 @@ import sys from _typeshed import FileDescriptorLike, ReadableBuffer from socket import socket -from typing import Any, overload -from typing_extensions import TypeAlias +from typing import Any, TypeAlias, overload # cyclic dependence with asynchat _MapType: TypeAlias = dict[int, Any] @@ -75,10 +74,12 @@ if sys.platform != "win32": def __init__(self, fd: int) -> None: ... def recv(self, bufsize: int, flags: int = ...) -> bytes: ... def send(self, data: bytes, flags: int = ...) -> int: ... + @overload def getsockopt(self, level: int, optname: int, buflen: None = None) -> int: ... @overload def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... + def read(self, bufsize: int, flags: int = ...) -> bytes: ... def write(self, data: bytes, flags: int = ...) -> int: ... def close(self) -> None: ... diff --git a/mypy/typeshed/stdlib/atexit.pyi b/mypy/typeshed/stdlib/atexit.pyi index 7f7b05ccc0a39..9177d80169be2 100644 --- a/mypy/typeshed/stdlib/atexit.pyi +++ b/mypy/typeshed/stdlib/atexit.pyi @@ -1,6 +1,5 @@ from collections.abc import Callable -from typing import TypeVar -from typing_extensions import ParamSpec +from typing import ParamSpec, TypeVar _T = TypeVar("_T") _P = ParamSpec("_P") diff --git a/mypy/typeshed/stdlib/audioop.pyi b/mypy/typeshed/stdlib/audioop.pyi index f3ce78ccb7fae..a7d5e8adb7a52 100644 --- a/mypy/typeshed/stdlib/audioop.pyi +++ b/mypy/typeshed/stdlib/audioop.pyi @@ -1,4 +1,5 @@ -from typing_extensions import Buffer, TypeAlias +from typing import TypeAlias +from typing_extensions import Buffer _AdpcmState: TypeAlias = tuple[int, int] _RatecvState: TypeAlias = tuple[int, tuple[tuple[int, int], ...]] diff --git a/mypy/typeshed/stdlib/base64.pyi b/mypy/typeshed/stdlib/base64.pyi index 279d74a94ebe2..67bc37309a976 100644 --- a/mypy/typeshed/stdlib/base64.pyi +++ b/mypy/typeshed/stdlib/base64.pyi @@ -13,6 +13,8 @@ __all__ = [ "b32decode", "b16encode", "b16decode", + "b32hexencode", + "b32hexdecode", "b85encode", "b85decode", "a85encode", @@ -23,39 +25,101 @@ __all__ = [ "urlsafe_b64decode", ] -if sys.version_info >= (3, 10): - __all__ += ["b32hexencode", "b32hexdecode"] if sys.version_info >= (3, 13): __all__ += ["z85decode", "z85encode"] -def b64encode(s: ReadableBuffer, altchars: ReadableBuffer | None = None) -> bytes: ... -def b64decode(s: str | ReadableBuffer, altchars: str | ReadableBuffer | None = None, validate: bool = False) -> bytes: ... +if sys.version_info >= (3, 15): + def b64encode( + s: ReadableBuffer, altchars: ReadableBuffer | None = None, *, padded: bool = True, wrapcol: int = 0 + ) -> bytes: ... + def b64decode( + s: str | ReadableBuffer, + altchars: str | ReadableBuffer | None = None, + validate: bool = ..., + *, + padded: bool = True, + ignorechars: ReadableBuffer = ..., + canonical: bool = False, + ) -> bytes: ... + +else: + def b64encode(s: ReadableBuffer, altchars: ReadableBuffer | None = None) -> bytes: ... + def b64decode(s: str | ReadableBuffer, altchars: str | ReadableBuffer | None = None, validate: bool = False) -> bytes: ... + def standard_b64encode(s: ReadableBuffer) -> bytes: ... def standard_b64decode(s: str | ReadableBuffer) -> bytes: ... -def urlsafe_b64encode(s: ReadableBuffer) -> bytes: ... -def urlsafe_b64decode(s: str | ReadableBuffer) -> bytes: ... -def b32encode(s: ReadableBuffer) -> bytes: ... -def b32decode(s: str | ReadableBuffer, casefold: bool = False, map01: str | ReadableBuffer | None = None) -> bytes: ... -def b16encode(s: ReadableBuffer) -> bytes: ... -def b16decode(s: str | ReadableBuffer, casefold: bool = False) -> bytes: ... - -if sys.version_info >= (3, 10): + +if sys.version_info >= (3, 15): + def urlsafe_b64encode(s: ReadableBuffer, *, padded: bool = True) -> bytes: ... + def urlsafe_b64decode(s: str | ReadableBuffer, *, padded: bool = False) -> bytes: ... + def b32encode(s: ReadableBuffer, *, padded: bool = True, wrapcol: int = 0) -> bytes: ... + def b32decode( + s: str | ReadableBuffer, + casefold: bool = False, + map01: str | ReadableBuffer | None = None, + *, + padded: bool = True, + ignorechars: ReadableBuffer = b"", + canonical: bool = False, + ) -> bytes: ... + def b16encode(s: ReadableBuffer, *, wrapcol: int = 0) -> bytes: ... + def b16decode(s: str | ReadableBuffer, casefold: bool = False, *, ignorechars: ReadableBuffer = b"") -> bytes: ... + +else: + def urlsafe_b64encode(s: ReadableBuffer) -> bytes: ... + def urlsafe_b64decode(s: str | ReadableBuffer) -> bytes: ... + def b32encode(s: ReadableBuffer) -> bytes: ... + def b32decode(s: str | ReadableBuffer, casefold: bool = False, map01: str | ReadableBuffer | None = None) -> bytes: ... + def b16encode(s: ReadableBuffer) -> bytes: ... + def b16decode(s: str | ReadableBuffer, casefold: bool = False) -> bytes: ... + +if sys.version_info >= (3, 15): + def b32hexencode(s: ReadableBuffer, *, padded: bool = True, wrapcol: int = 0) -> bytes: ... + def b32hexdecode( + s: str | ReadableBuffer, + casefold: bool = False, + *, + padded: bool = True, + ignorechars: ReadableBuffer = b"", + canonical: bool = False, + ) -> bytes: ... + +else: def b32hexencode(s: ReadableBuffer) -> bytes: ... def b32hexdecode(s: str | ReadableBuffer, casefold: bool = False) -> bytes: ... def a85encode( b: ReadableBuffer, *, foldspaces: bool = False, wrapcol: int = 0, pad: bool = False, adobe: bool = False ) -> bytes: ... -def a85decode( - b: str | ReadableBuffer, *, foldspaces: bool = False, adobe: bool = False, ignorechars: bytearray | bytes = b" \t\n\r\x0b" -) -> bytes: ... -def b85encode(b: ReadableBuffer, pad: bool = False) -> bytes: ... -def b85decode(b: str | ReadableBuffer) -> bytes: ... + +if sys.version_info >= (3, 15): + def a85decode( + b: str | ReadableBuffer, + *, + foldspaces: bool = False, + adobe: bool = False, + ignorechars: bytearray | bytes = b" \t\n\r\x0b", + canonical: bool = False, + ) -> bytes: ... + def b85encode(b: ReadableBuffer, pad: bool = False, *, wrapcol: int = 0) -> bytes: ... + def b85decode(b: str | ReadableBuffer, *, ignorechars: ReadableBuffer = b"", canonical: bool = False) -> bytes: ... + +else: + def a85decode( + b: str | ReadableBuffer, *, foldspaces: bool = False, adobe: bool = False, ignorechars: bytearray | bytes = b" \t\n\r\x0b" + ) -> bytes: ... + def b85encode(b: ReadableBuffer, pad: bool = False) -> bytes: ... + def b85decode(b: str | ReadableBuffer) -> bytes: ... + def decode(input: IO[bytes], output: IO[bytes]) -> None: ... def encode(input: IO[bytes], output: IO[bytes]) -> None: ... def encodebytes(s: ReadableBuffer) -> bytes: ... def decodebytes(s: ReadableBuffer) -> bytes: ... if sys.version_info >= (3, 13): - def z85encode(s: ReadableBuffer) -> bytes: ... - def z85decode(s: str | ReadableBuffer) -> bytes: ... + if sys.version_info >= (3, 15): + def z85encode(s: ReadableBuffer, pad: bool = False, *, wrapcol: int = 0) -> bytes: ... + def z85decode(s: str | ReadableBuffer, *, ignorechars: ReadableBuffer = b"", canonical: bool = False) -> bytes: ... + else: + def z85encode(s: ReadableBuffer) -> bytes: ... + def z85decode(s: str | ReadableBuffer) -> bytes: ... diff --git a/mypy/typeshed/stdlib/bdb.pyi b/mypy/typeshed/stdlib/bdb.pyi index b6be2210ffe2e..c2c45e2684b4b 100644 --- a/mypy/typeshed/stdlib/bdb.pyi +++ b/mypy/typeshed/stdlib/bdb.pyi @@ -1,10 +1,9 @@ import sys -from _typeshed import ExcInfo, TraceFunction, Unused +from _typeshed import ExcInfo, ReadableBuffer, TraceFunction, Unused from collections.abc import Callable, Iterable, Iterator, Mapping from contextlib import contextmanager from types import CodeType, FrameType, TracebackType -from typing import IO, Any, Final, Literal, SupportsInt, TypeVar -from typing_extensions import ParamSpec, TypeAlias +from typing import IO, Any, Final, Literal, ParamSpec, SupportsInt, TypeAlias, TypeVar __all__ = ["BdbQuit", "Bdb", "Breakpoint"] @@ -85,11 +84,21 @@ class Bdb: def get_all_breaks(self) -> dict[str, list[int]]: ... def get_stack(self, f: FrameType | None, t: TracebackType | None) -> tuple[list[tuple[FrameType, int]], int]: ... def format_stack_entry(self, frame_lineno: tuple[FrameType, int], lprefix: str = ": ") -> str: ... - def run( - self, cmd: str | CodeType, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None + def run( # matches `builtins.exec` + self, + cmd: str | ReadableBuffer | CodeType, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, ) -> None: ... - def runeval(self, expr: str, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None) -> None: ... - def runctx(self, cmd: str | CodeType, globals: dict[str, Any] | None, locals: Mapping[str, Any] | None) -> None: ... + def runctx( # matches `builtins.exec` + self, cmd: str | ReadableBuffer | CodeType, globals: dict[str, Any] | None, locals: Mapping[str, object] | None + ) -> None: ... + def runeval( # matches `builtins.eval` + self, + expr: str | ReadableBuffer | CodeType, + globals: dict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + ) -> Any: ... def runcall(self, func: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> _T | None: ... if sys.version_info >= (3, 14): def start_trace(self) -> None: ... diff --git a/mypy/typeshed/stdlib/binascii.pyi b/mypy/typeshed/stdlib/binascii.pyi index 5606d5cdf74d9..6840c68838119 100644 --- a/mypy/typeshed/stdlib/binascii.pyi +++ b/mypy/typeshed/stdlib/binascii.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import ReadableBuffer -from typing_extensions import TypeAlias, deprecated +from typing import TypeAlias +from typing_extensions import deprecated # Many functions in binascii accept buffer objects # or ASCII-only strings. @@ -9,13 +10,68 @@ _AsciiBuffer: TypeAlias = str | ReadableBuffer def a2b_uu(data: _AsciiBuffer, /) -> bytes: ... def b2a_uu(data: ReadableBuffer, /, *, backtick: bool = False) -> bytes: ... -if sys.version_info >= (3, 11): +if sys.version_info >= (3, 15): + ASCII85_ALPHABET: bytes + BINHEX_ALPHABET: bytes + CRYPT_ALPHABET: bytes + UU_ALPHABET: bytes + BASE64_ALPHABET: bytes + URLSAFE_BASE64_ALPHABET: bytes + BASE32_ALPHABET: bytes + BASE32HEX_ALPHABET: bytes + BASE85_ALPHABET: bytes + Z85_ALPHABET: bytes + def a2b_base64( + data: _AsciiBuffer, + /, + *, + strict_mode: bool = False, + alphabet: bytes = ..., + padded: bool = True, + ignorechars: ReadableBuffer = ..., + canonical: bool = False, + ) -> bytes: ... + def b2a_base64( + data: ReadableBuffer, /, *, newline: bool = True, alphabet: ReadableBuffer = ..., padded: bool = True, wrapcol: int = 0 + ) -> bytes: ... + def b2a_base32( + data: ReadableBuffer, /, *, alphabet: ReadableBuffer = ..., padded: bool = True, wrapcol: int = 0 + ) -> bytes: ... + def a2b_base32( + data: _AsciiBuffer, + /, + *, + alphabet: bytes = ..., + padded: bool = True, + ignorechars: ReadableBuffer = b"", + canonical: bool = False, + ) -> bytes: ... + def b2a_ascii85( + data: ReadableBuffer, /, *, foldspaces: bool = False, wrapcol: int = 0, pad: bool = False, adobe: bool = False + ) -> bytes: ... + def a2b_ascii85( + data: _AsciiBuffer, + /, + *, + foldspaces: bool = False, + adobe: bool = False, + ignorechars: ReadableBuffer = b"", + canonical: bool = False, + ) -> bytes: ... + def b2a_base85(data: ReadableBuffer, /, *, alphabet: ReadableBuffer = ..., pad: bool = False, wrapcol: int = 0) -> bytes: ... + def a2b_base85( + data: _AsciiBuffer, /, *, alphabet: bytes = ..., ignorechars: ReadableBuffer = b"", canonical: bool = False + ) -> bytes: ... + +elif sys.version_info >= (3, 11): def a2b_base64(data: _AsciiBuffer, /, *, strict_mode: bool = False) -> bytes: ... else: def a2b_base64(data: _AsciiBuffer, /) -> bytes: ... -def b2a_base64(data: ReadableBuffer, /, *, newline: bool = True) -> bytes: ... +if sys.version_info < (3, 15): + def b2a_base64(data: ReadableBuffer, /, *, newline: bool = True) -> bytes: ... + def a2b_qp(data: _AsciiBuffer, header: bool = False) -> bytes: ... def b2a_qp(data: ReadableBuffer, quotetabs: bool = False, istext: bool = True, header: bool = False) -> bytes: ... @@ -33,8 +89,14 @@ def crc_hqx(data: ReadableBuffer, crc: int, /) -> int: ... def crc32(data: ReadableBuffer, crc: int = 0, /) -> int: ... def b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = 1) -> bytes: ... def hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = 1) -> bytes: ... -def a2b_hex(hexstr: _AsciiBuffer, /) -> bytes: ... -def unhexlify(hexstr: _AsciiBuffer, /) -> bytes: ... + +if sys.version_info >= (3, 15): + def a2b_hex(hexstr: _AsciiBuffer, /, *, ignorechars: ReadableBuffer = b"") -> bytes: ... + def unhexlify(hexstr: _AsciiBuffer, /, *, ignorechars: ReadableBuffer = b"") -> bytes: ... + +else: + def a2b_hex(hexstr: _AsciiBuffer, /) -> bytes: ... + def unhexlify(hexstr: _AsciiBuffer, /) -> bytes: ... class Error(ValueError): ... class Incomplete(Exception): ... diff --git a/mypy/typeshed/stdlib/binhex.pyi b/mypy/typeshed/stdlib/binhex.pyi index bdead928468f4..f309f4e026a59 100644 --- a/mypy/typeshed/stdlib/binhex.pyi +++ b/mypy/typeshed/stdlib/binhex.pyi @@ -1,6 +1,5 @@ from _typeshed import SizedBuffer -from typing import IO, Any, Final -from typing_extensions import TypeAlias +from typing import IO, Any, Final, TypeAlias __all__ = ["binhex", "hexbin", "Error"] diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 25b21ba971540..1fa56c8de0d05 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -33,20 +33,22 @@ from _typeshed import ( from collections.abc import Awaitable, Callable, Iterable, Iterator, MutableSet, Reversible, Set as AbstractSet, Sized from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper from os import PathLike -from types import CellType, CodeType, GenericAlias, TracebackType +from types import CellType, CodeType, EllipsisType, GenericAlias, NotImplementedType, TracebackType # mypy crashes if any of {ByteString, Sequence, MutableSequence, Mapping, MutableMapping} # are imported from collections.abc in builtins.pyi -from typing import ( # noqa: Y022,UP035,RUF100 +from typing import ( # noqa: Y022,UP035 IO, Any, BinaryIO, ClassVar, + Concatenate, Final, Generic, Mapping, MutableMapping, MutableSequence, + ParamSpec, Protocol, Sequence, SupportsAbs, @@ -54,6 +56,8 @@ from typing import ( # noqa: Y022,UP035,RUF100 SupportsComplex, SupportsFloat, SupportsIndex, + TypeAlias, + TypeGuard, TypeVar, final, overload, @@ -61,18 +65,7 @@ from typing import ( # noqa: Y022,UP035,RUF100 ) # we can't import `Literal` from typing or mypy crashes: see #11247 -from typing_extensions import ( # noqa: Y023 - Concatenate, - Literal, - ParamSpec, - Self, - TypeAlias, - TypeGuard, - TypeIs, - TypeVarTuple, - deprecated, - disjoint_base, -) +from typing_extensions import Literal, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023, UP035 if sys.version_info >= (3, 14): from _typeshed import AnnotateFunc @@ -110,10 +103,12 @@ class object: __dict__: dict[str, Any] __module__: str __annotations__: dict[str, Any] + @property def __class__(self) -> type[Self]: ... @__class__.setter def __class__(self, type: type[Self], /) -> None: ... + def __init__(self) -> None: ... def __new__(cls) -> Self: ... # N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers. @@ -142,41 +137,43 @@ class object: @disjoint_base class staticmethod(Generic[_P, _R_co]): + __name__: str + __qualname__: str @property def __func__(self) -> Callable[_P, _R_co]: ... @property def __isabstractmethod__(self) -> bool: ... def __init__(self, f: Callable[_P, _R_co], /) -> None: ... + @overload def __get__(self, instance: None, owner: type, /) -> Callable[_P, _R_co]: ... @overload def __get__(self, instance: _T, owner: type[_T] | None = None, /) -> Callable[_P, _R_co]: ... - if sys.version_info >= (3, 10): - __name__: str - __qualname__: str - @property - def __wrapped__(self) -> Callable[_P, _R_co]: ... - def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R_co: ... + + @property + def __wrapped__(self) -> Callable[_P, _R_co]: ... + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R_co: ... if sys.version_info >= (3, 14): def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... __annotate__: AnnotateFunc | None @disjoint_base class classmethod(Generic[_T, _P, _R_co]): + __name__: str + __qualname__: str @property def __func__(self) -> Callable[Concatenate[type[_T], _P], _R_co]: ... @property def __isabstractmethod__(self) -> bool: ... def __init__(self, f: Callable[Concatenate[type[_T], _P], _R_co], /) -> None: ... + @overload def __get__(self, instance: _T, owner: type[_T] | None = None, /) -> Callable[_P, _R_co]: ... @overload def __get__(self, instance: None, owner: type[_T], /) -> Callable[_P, _R_co]: ... - if sys.version_info >= (3, 10): - __name__: str - __qualname__: str - @property - def __wrapped__(self) -> Callable[Concatenate[type[_T], _P], _R_co]: ... + + @property + def __wrapped__(self) -> Callable[Concatenate[type[_T], _P], _R_co]: ... if sys.version_info >= (3, 14): def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... __annotate__: AnnotateFunc | None @@ -207,16 +204,19 @@ class type: def __text_signature__(self) -> str | None: ... @property def __weakrefoffset__(self) -> int: ... + @overload def __init__(self, o: object, /) -> None: ... @overload def __init__(self, name: str, bases: tuple[type, ...], dict: dict[str, Any], /, **kwds: Any) -> None: ... + @overload def __new__(cls, o: object, /) -> type: ... @overload def __new__( cls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], /, **kwds: Any ) -> _typeshed.Self: ... + def __call__(self, *args: Any, **kwds: Any) -> Any: ... def __subclasses__(self: _typeshed.Self) -> list[_typeshed.Self]: ... # Note: the documentation doesn't specify what the return type is, the standard @@ -226,11 +226,10 @@ class type: def __subclasscheck__(self, subclass: type, /) -> bool: ... @classmethod def __prepare__(metacls, name: str, bases: tuple[type, ...], /, **kwds: Any) -> MutableMapping[str, object]: ... - if sys.version_info >= (3, 10): - # `int | str` produces an instance of `UnionType`, but `int | int` produces an instance of `type`, - # and `abc.ABC | abc.ABC` produces an instance of `abc.ABCMeta`. - def __or__(self: _typeshed.Self, value: Any, /) -> types.UnionType | _typeshed.Self: ... - def __ror__(self: _typeshed.Self, value: Any, /) -> types.UnionType | _typeshed.Self: ... + # `int | str` produces an instance of `UnionType`, but `int | int` produces an instance of `type`, + # and `abc.ABC | abc.ABC` produces an instance of `abc.ABCMeta`. + def __or__(self: _typeshed.Self, value: Any, /) -> types.UnionType | _typeshed.Self: ... + def __ror__(self: _typeshed.Self, value: Any, /) -> types.UnionType | _typeshed.Self: ... if sys.version_info >= (3, 12): __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] __annotations__: dict[str, AnnotationForm] @@ -256,6 +255,7 @@ class int: def __new__(cls, x: ConvertibleToInt = 0, /) -> Self: ... @overload def __new__(cls, x: str | bytes | bytearray, /, base: SupportsIndex) -> Self: ... + def as_integer_ratio(self) -> tuple[int, Literal[1]]: ... @property def real(self) -> int: ... @@ -267,8 +267,7 @@ class int: def denominator(self) -> Literal[1]: ... def conjugate(self) -> int: ... def bit_length(self) -> int: ... - if sys.version_info >= (3, 10): - def bit_count(self) -> int: ... + def bit_count(self) -> int: ... if sys.version_info >= (3, 11): def to_bytes( @@ -310,6 +309,7 @@ class int: def __rtruediv__(self, value: int, /) -> float: ... def __rmod__(self, value: int, /) -> int: ... def __rdivmod__(self, value: int, /) -> tuple[int, int]: ... + @overload def __pow__(self, x: Literal[0], /) -> Literal[1]: ... @overload @@ -324,6 +324,7 @@ class int: def __pow__(self, value: int, mod: None = None, /) -> Any: ... @overload def __pow__(self, value: int, mod: int, /) -> int: ... + def __rpow__(self, value: int, mod: int | None = None, /) -> Any: ... def __and__(self, value: int, /) -> int: ... def __or__(self, value: int, /) -> int: ... @@ -381,12 +382,14 @@ class float: def __truediv__(self, value: float, /) -> float: ... def __mod__(self, value: float, /) -> float: ... def __divmod__(self, value: float, /) -> tuple[float, float]: ... + @overload def __pow__(self, value: int, mod: None = None, /) -> float: ... # positive __value -> float; negative __value -> complex # return type must be Any as `float | complex` causes too many false-positive errors @overload def __pow__(self, value: float, mod: None = None, /) -> Any: ... + def __radd__(self, value: float, /) -> float: ... def __rsub__(self, value: float, /) -> float: ... def __rmul__(self, value: float, /) -> float: ... @@ -394,6 +397,7 @@ class float: def __rtruediv__(self, value: float, /) -> float: ... def __rmod__(self, value: float, /) -> float: ... def __rdivmod__(self, value: float, /) -> tuple[float, float]: ... + @overload def __rpow__(self, value: _PositiveInteger, mod: None = None, /) -> float: ... @overload @@ -401,14 +405,17 @@ class float: # Returning `complex` for the general case gives too many false-positive errors. @overload def __rpow__(self, value: float, mod: None = None, /) -> Any: ... + def __getnewargs__(self) -> tuple[float]: ... def __trunc__(self) -> int: ... def __ceil__(self) -> int: ... def __floor__(self) -> int: ... + @overload def __round__(self, ndigits: None = None, /) -> int: ... @overload def __round__(self, ndigits: SupportsIndex, /) -> float: ... + def __eq__(self, value: object, /) -> bool: ... def __ne__(self, value: object, /) -> bool: ... def __lt__(self, value: float, /) -> bool: ... @@ -438,6 +445,7 @@ class complex: ) -> Self: ... @overload def __new__(cls, real: str | SupportsComplex | SupportsFloat | SupportsIndex | complex) -> Self: ... + @property def real(self) -> float: ... @property @@ -484,14 +492,17 @@ class str(Sequence[str]): def capitalize(self) -> str: ... # type: ignore[misc] def casefold(self) -> str: ... # type: ignore[misc] def center(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] + def count(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... def encode(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: ... def endswith( self, suffix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> bool: ... def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ... # type: ignore[misc] + def find(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... def format(self, *args: object, **kwargs: object) -> str: ... + def format_map(self, mapping: _FormatMapMapping, /) -> str: ... def index(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... def isalnum(self) -> bool: ... @@ -511,6 +522,7 @@ class str(Sequence[str]): def lower(self) -> str: ... # type: ignore[misc] def lstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] def partition(self, sep: str, /) -> tuple[str, str, str]: ... # type: ignore[misc] + if sys.version_info >= (3, 13): def replace(self, old: str, new: str, /, count: SupportsIndex = -1) -> str: ... # type: ignore[misc] else: @@ -518,6 +530,7 @@ class str(Sequence[str]): def removeprefix(self, prefix: str, /) -> str: ... # type: ignore[misc] 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: ... def rjust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] @@ -526,18 +539,37 @@ class str(Sequence[str]): def rstrip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... # type: ignore[misc] 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: ... def strip(self, chars: str | None = None, /) -> str: ... # type: ignore[misc] def swapcase(self) -> str: ... # type: ignore[misc] def title(self) -> str: ... # type: ignore[misc] + def translate(self, table: _TranslateTable, /) -> str: ... def upper(self) -> str: ... # type: ignore[misc] def zfill(self, width: SupportsIndex, /) -> str: ... # type: ignore[misc] - @staticmethod - @overload - def maketrans(x: dict[int, _T] | dict[str, _T] | dict[str | int, _T], /) -> dict[int, _T]: ... + + if sys.version_info >= (3, 15): + @staticmethod + @overload + def maketrans( + x: ( + dict[int, _T] + | dict[str, _T] + | dict[str | int, _T] + | frozendict[int, _T] + | frozendict[str, _T] + | frozendict[str | int, _T] + ), + /, + ) -> dict[int, _T]: ... + else: + @staticmethod + @overload + def maketrans(x: dict[int, _T] | dict[str, _T] | dict[str | int, _T], /) -> dict[int, _T]: ... + @staticmethod @overload def maketrans(x: str, y: str, /) -> dict[int, int]: ... @@ -545,21 +577,26 @@ class str(Sequence[str]): @overload def maketrans(x: str, y: str, z: str, /) -> dict[int, int | None]: ... 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: ... def __getitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> str: ... # type: ignore[misc] + def __gt__(self, value: str, /) -> bool: ... def __hash__(self) -> int: ... 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: ... def __mul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] + def __ne__(self, value: object, /) -> bool: ... def __rmul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] + def __getnewargs__(self) -> tuple[str]: ... def __format__(self, format_spec: str, /) -> str: ... @@ -571,6 +608,7 @@ class bytes(Sequence[int]): def __new__(cls, string: str, /, encoding: str, errors: str = "strict") -> Self: ... @overload def __new__(cls) -> Self: ... + def capitalize(self) -> bytes: ... def center(self, width: SupportsIndex, fillchar: bytes = b" ", /) -> bytes: ... def count( @@ -605,7 +643,11 @@ class bytes(Sequence[int]): def lower(self) -> bytes: ... def lstrip(self, bytes: ReadableBuffer | None = None, /) -> bytes: ... def partition(self, sep: ReadableBuffer, /) -> tuple[bytes, bytes, bytes]: ... - def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytes: ... + if sys.version_info >= (3, 15): + def replace(self, old: ReadableBuffer, new: ReadableBuffer, /, count: SupportsIndex = -1) -> bytes: ... + else: + def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytes: ... + def removeprefix(self, prefix: ReadableBuffer, /) -> bytes: ... def removesuffix(self, suffix: ReadableBuffer, /) -> bytes: ... def rfind( @@ -633,6 +675,7 @@ class bytes(Sequence[int]): def translate(self, table: ReadableBuffer | None, /, delete: ReadableBuffer = b"") -> bytes: ... def upper(self) -> bytes: ... def zfill(self, width: SupportsIndex, /) -> bytes: ... + if sys.version_info >= (3, 14): @classmethod def fromhex(cls, string: str | ReadableBuffer, /) -> Self: ... @@ -645,10 +688,12 @@ class bytes(Sequence[int]): def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... def __hash__(self) -> int: ... + @overload def __getitem__(self, key: SupportsIndex, /) -> int: ... @overload def __getitem__(self, key: slice[SupportsIndex | None], /) -> bytes: ... + def __add__(self, value: ReadableBuffer, /) -> bytes: ... def __mul__(self, value: SupportsIndex, /) -> bytes: ... def __rmul__(self, value: SupportsIndex, /) -> bytes: ... @@ -675,6 +720,7 @@ class bytearray(MutableSequence[int]): def __init__(self, ints: Iterable[SupportsIndex] | SupportsIndex | ReadableBuffer, /) -> None: ... @overload def __init__(self, string: str, /, encoding: str, errors: str = "strict") -> None: ... + def append(self, item: SupportsIndex, /) -> None: ... def capitalize(self) -> bytearray: ... def center(self, width: SupportsIndex, fillchar: bytes = b" ", /) -> bytearray: ... @@ -717,7 +763,11 @@ class bytearray(MutableSequence[int]): def remove(self, value: int, /) -> None: ... def removeprefix(self, prefix: ReadableBuffer, /) -> bytearray: ... def removesuffix(self, suffix: ReadableBuffer, /) -> bytearray: ... - def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytearray: ... + if sys.version_info >= (3, 15): + def replace(self, old: ReadableBuffer, new: ReadableBuffer, /, count: SupportsIndex = -1) -> bytearray: ... + else: + def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytearray: ... + def rfind( self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> int: ... @@ -741,8 +791,12 @@ class bytearray(MutableSequence[int]): def swapcase(self) -> bytearray: ... def title(self) -> bytearray: ... def translate(self, table: ReadableBuffer | None, /, delete: bytes = b"") -> bytearray: ... + if sys.version_info >= (3, 15): + def take_bytes(self, n: int | None = None, /) -> bytes: ... + def upper(self) -> bytearray: ... def zfill(self, width: SupportsIndex, /) -> bytearray: ... + if sys.version_info >= (3, 14): @classmethod def fromhex(cls, string: str | ReadableBuffer, /) -> Self: ... @@ -755,14 +809,17 @@ class bytearray(MutableSequence[int]): def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... __hash__: ClassVar[None] # type: ignore[assignment] + @overload def __getitem__(self, key: SupportsIndex, /) -> int: ... @overload def __getitem__(self, key: slice[SupportsIndex | None], /) -> bytearray: ... + @overload def __setitem__(self, key: SupportsIndex, value: SupportsIndex, /) -> None: ... @overload def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[SupportsIndex] | bytes, /) -> None: ... + def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> None: ... def __add__(self, value: ReadableBuffer, /) -> bytearray: ... # The superclass wants us to accept Iterable[int], but that fails at runtime. @@ -824,6 +881,7 @@ class memoryview(Sequence[_I]): exc_tb: TracebackType | None, /, ) -> None: ... + @overload def cast(self, format: Literal["c", "@c"], shape: list[int] | tuple[int, ...] = ...) -> memoryview[bytes]: ... @overload @@ -832,24 +890,24 @@ class memoryview(Sequence[_I]): def cast(self, format: Literal["?"], shape: list[int] | tuple[int, ...] = ...) -> memoryview[bool]: ... @overload def cast(self, format: _IntegerFormats, shape: list[int] | tuple[int, ...] = ...) -> memoryview: ... + @overload def __getitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], /) -> _I: ... @overload def __getitem__(self, key: slice[SupportsIndex | None], /) -> memoryview[_I]: ... + def __contains__(self, x: object, /) -> bool: ... def __iter__(self) -> Iterator[_I]: ... def __len__(self) -> int: ... def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... + @overload def __setitem__(self, key: slice[SupportsIndex | None], value: ReadableBuffer, /) -> None: ... @overload def __setitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], value: _I, /) -> None: ... - if sys.version_info >= (3, 10): - def tobytes(self, order: Literal["C", "F", "A"] | None = "C") -> bytes: ... - else: - def tobytes(self, order: Literal["C", "F", "A"] | None = None) -> bytes: ... + def tobytes(self, order: Literal["C", "F", "A"] | None = "C") -> bytes: ... def tolist(self) -> list[int]: ... def toreadonly(self) -> memoryview: ... def release(self) -> None: ... @@ -871,32 +929,39 @@ class memoryview(Sequence[_I]): @final class bool(int): def __new__(cls, o: object = False, /) -> Self: ... + # The following overloads could be represented more elegantly with a TypeVar("_B", bool, int), # however mypy has a bug regarding TypeVar constraints (https://github.com/python/mypy/issues/11880). @overload def __and__(self, value: bool, /) -> bool: ... @overload def __and__(self, value: int, /) -> int: ... + @overload def __or__(self, value: bool, /) -> bool: ... @overload def __or__(self, value: int, /) -> int: ... + @overload def __xor__(self, value: bool, /) -> bool: ... @overload def __xor__(self, value: int, /) -> int: ... + @overload def __rand__(self, value: bool, /) -> bool: ... @overload def __rand__(self, value: int, /) -> int: ... + @overload def __ror__(self, value: bool, /) -> bool: ... @overload def __ror__(self, value: int, /) -> int: ... + @overload def __rxor__(self, value: bool, /) -> bool: ... @overload def __rxor__(self, value: int, /) -> int: ... + def __getnewargs__(self) -> tuple[int]: ... @deprecated("Will throw an error in Python 3.16. Use `not` for logical negation of bools instead.") def __invert__(self) -> int: ... @@ -909,6 +974,7 @@ class slice(Generic[_StartT_co, _StopT_co, _StepT_co]): def step(self) -> _StepT_co: ... @property def stop(self) -> _StopT_co: ... + # Note: __new__ overloads map `None` to `Any`, since users expect slice(x, None) # to be compatible with slice(None, x). # generic slice -------------------------------------------------------------------- @@ -933,6 +999,7 @@ class slice(Generic[_StartT_co, _StopT_co, _StepT_co]): def __new__(cls, start: None, stop: _T2, step: _T3, /) -> slice[Any, _T2, _T3]: ... @overload def __new__(cls, start: _T1, stop: _T2, step: _T3, /) -> slice[_T1, _T2, _T3]: ... + def __eq__(self, value: object, /) -> bool: ... if sys.version_info >= (3, 12): def __hash__(self) -> int: ... @@ -940,16 +1007,20 @@ class slice(Generic[_StartT_co, _StopT_co, _StepT_co]): __hash__: ClassVar[None] # type: ignore[assignment] def indices(self, len: SupportsIndex, /) -> tuple[int, int, int]: ... + if sys.version_info >= (3, 15): + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @disjoint_base class tuple(Sequence[_T_co]): def __new__(cls, iterable: Iterable[_T_co] = (), /) -> Self: ... def __len__(self) -> int: ... def __contains__(self, key: object, /) -> bool: ... + @overload def __getitem__(self, key: SupportsIndex, /) -> _T_co: ... @overload def __getitem__(self, key: slice[SupportsIndex | None], /) -> tuple[_T_co, ...]: ... + def __iter__(self) -> Iterator[_T_co]: ... def __lt__(self, value: tuple[_T_co, ...], /) -> bool: ... def __le__(self, value: tuple[_T_co, ...], /) -> bool: ... @@ -957,10 +1028,12 @@ class tuple(Sequence[_T_co]): def __ge__(self, value: tuple[_T_co, ...], /) -> bool: ... def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... + @overload def __add__(self, value: tuple[_T_co, ...], /) -> tuple[_T_co, ...]: ... @overload def __add__(self, value: tuple[_T, ...], /) -> tuple[_T_co | _T, ...]: ... + def __mul__(self, value: SupportsIndex, /) -> tuple[_T_co, ...]: ... def __rmul__(self, value: SupportsIndex, /) -> tuple[_T_co, ...]: ... def count(self, value: Any, /) -> int: ... @@ -988,9 +1061,8 @@ class function: if sys.version_info >= (3, 14): __annotate__: AnnotateFunc | None __kwdefaults__: dict[str, Any] | None - if sys.version_info >= (3, 10): - @property - def __builtins__(self) -> dict[str, Any]: ... + @property + def __builtins__(self) -> dict[str, Any]: ... if sys.version_info >= (3, 12): __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] @@ -1024,6 +1096,7 @@ class list(MutableSequence[_T]): def __init__(self) -> None: ... @overload def __init__(self, iterable: Iterable[_T], /) -> None: ... + def copy(self) -> list[_T]: ... def append(self, object: _T, /) -> None: ... def extend(self, iterable: Iterable[_T], /) -> None: ... @@ -1034,6 +1107,7 @@ class list(MutableSequence[_T]): def count(self, value: _T, /) -> int: ... def insert(self, index: SupportsIndex, object: _T, /) -> None: ... def remove(self, value: _T, /) -> None: ... + # Signature of `list.sort` should be kept inline with `collections.UserList.sort()` # and multiprocessing.managers.ListProxy.sort() # @@ -1043,23 +1117,29 @@ class list(MutableSequence[_T]): def sort(self: list[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None: ... @overload def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None: ... + def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... __hash__: ClassVar[None] # type: ignore[assignment] + @overload def __getitem__(self, i: SupportsIndex, /) -> _T: ... @overload def __getitem__(self, s: slice[SupportsIndex | None], /) -> list[_T]: ... + @overload def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ... @overload def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[_T], /) -> None: ... + def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> None: ... + # Overloading looks unnecessary, but is needed to work around complex mypy problems @overload def __add__(self, value: list[_T], /) -> list[_T]: ... @overload def __add__(self, value: list[_S], /) -> list[_S | _T]: ... + def __iadd__(self, value: Iterable[_T], /) -> Self: ... # type: ignore[misc] def __mul__(self, value: SupportsIndex, /) -> list[_T]: ... def __rmul__(self, value: SupportsIndex, /) -> list[_T]: ... @@ -1105,11 +1185,13 @@ class dict(MutableMapping[_KT, _VT]): def __init__(self: dict[str, str], iterable: Iterable[list[str]], /) -> None: ... @overload def __init__(self: dict[bytes, bytes], iterable: Iterable[list[bytes]], /) -> None: ... + def __new__(cls, /, *args: Any, **kwargs: Any) -> Self: ... def copy(self) -> dict[_KT, _VT]: ... def keys(self) -> dict_keys[_KT, _VT]: ... def values(self) -> dict_values[_KT, _VT]: ... def items(self) -> dict_items[_KT, _VT]: ... + # Signature of `dict.fromkeys` should be kept identical to # `fromkeys` methods of `OrderedDict`/`ChainMap`/`UserDict` in `collections` # TODO: the true signature of `dict.fromkeys` is not expressible in the current type system. @@ -1120,6 +1202,7 @@ class dict(MutableMapping[_KT, _VT]): @classmethod @overload def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> dict[_T, _S]: ... + # Positional-only in dict, but not in MutableMapping @overload # type: ignore[override] def get(self, key: _KT, default: None = None, /) -> _VT | None: ... @@ -1127,12 +1210,14 @@ class dict(MutableMapping[_KT, _VT]): def get(self, key: _KT, default: _VT, /) -> _VT: ... @overload def get(self, key: _KT, default: _T, /) -> _VT | _T: ... + @overload def pop(self, key: _KT, /) -> _VT: ... @overload def pop(self, key: _KT, default: _VT, /) -> _VT: ... @overload def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... + def __len__(self) -> int: ... def __getitem__(self, key: _KT, /) -> _VT: ... def __setitem__(self, key: _KT, value: _VT, /) -> None: ... @@ -1142,26 +1227,103 @@ class dict(MutableMapping[_KT, _VT]): def __reversed__(self) -> Iterator[_KT]: ... __hash__: ClassVar[None] # type: ignore[assignment] def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... - @overload - def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... - @overload - def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... - @overload - def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... - @overload - def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + if sys.version_info >= (3, 15): + @overload + def __or__(self, value: dict[_KT, _VT] | frozendict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload + def __or__(self, value: dict[_T1, _T2] | frozendict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + @overload + def __ror__(self, value: frozendict[_KT, _VT], /) -> frozendict[_KT, _VT]: ... + @overload + def __ror__(self, value: frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... + else: + @overload + def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload + def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + @overload + def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + # dict.__ior__ should be kept roughly in line with MutableMapping.update() @overload # type: ignore[misc] def __ior__(self, value: SupportsKeysAndGetItem[_KT, _VT], /) -> Self: ... @overload def __ior__(self, value: Iterable[tuple[_KT, _VT]], /) -> Self: ... +if sys.version_info >= (3, 15): + @disjoint_base + class frozendict(Mapping[_KT, _VT]): + @overload + def __new__(cls, /) -> frozendict[Any, Any]: ... + @overload + def __new__(cls: type[frozendict[str, _VT]], /, **kwargs: _VT) -> frozendict[str, _VT]: ... + @overload + def __new__(cls, map: SupportsKeysAndGetItem[_KT, _VT], /) -> frozendict[_KT, _VT]: ... + @overload + def __new__( + cls: type[frozendict[str, _VT]], map: SupportsKeysAndGetItem[str, _VT], /, **kwargs: _VT + ) -> frozendict[str, _VT]: ... + @overload + def __new__(cls, iterable: Iterable[tuple[_KT, _VT]], /) -> frozendict[_KT, _VT]: ... + @overload + def __new__( + cls: type[frozendict[str, _VT]], iterable: Iterable[tuple[str, _VT]], /, **kwargs: _VT + ) -> frozendict[str, _VT]: ... + + def __init__(self) -> None: ... + def copy(self) -> frozendict[_KT, _VT]: ... + + @overload + @classmethod + def fromkeys(cls, iterable: Iterable[_T], value: None = None, /) -> frozendict[_T, Any | None]: ... + @overload + @classmethod + def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> frozendict[_T, _S]: ... + + @overload # type: ignore[override] + def get(self, key: _KT, default: None = None, /) -> _VT | None: ... + @overload + def get(self, key: _KT, default: _VT, /) -> _VT: ... + @overload + def get(self, key: _KT, default: _T, /) -> _VT | _T: ... + + def keys(self) -> dict_keys[_KT, _VT]: ... + def values(self) -> dict_values[_KT, _VT]: ... + def items(self) -> dict_items[_KT, _VT]: ... + def __len__(self) -> int: ... + def __getitem__(self, key: _KT, /) -> _VT: ... + def __reversed__(self) -> Iterator[_KT]: ... + def __iter__(self) -> Iterator[_KT]: ... + def __hash__(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + @overload + def __or__(self, value: dict[_KT, _VT] | frozendict[_KT, _VT], /) -> frozendict[_KT, _VT]: ... + @overload + def __or__(self, value: dict[_T1, _T2] | frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + @overload + def __ror__(self, value: frozendict[_KT, _VT], /) -> frozendict[_KT, _VT]: ... + @overload + def __ror__(self, value: frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... + @disjoint_base class set(MutableSet[_T]): @overload def __init__(self) -> None: ... @overload def __init__(self, iterable: Iterable[_T], /) -> None: ... + def add(self, element: _T, /) -> None: ... def copy(self) -> set[_T]: ... def difference(self, *s: Iterable[object]) -> set[_T]: ... @@ -1202,6 +1364,7 @@ class frozenset(AbstractSet[_T_co]): def __new__(cls) -> Self: ... @overload def __new__(cls, iterable: Iterable[_T_co], /) -> Self: ... + def copy(self) -> frozenset[_T_co]: ... def difference(self, *s: Iterable[object]) -> frozenset[_T_co]: ... def intersection(self, *s: Iterable[object]) -> frozenset[_T_co]: ... @@ -1240,10 +1403,12 @@ class range(Sequence[int]): def stop(self) -> int: ... @property def step(self) -> int: ... + @overload def __new__(cls, stop: SupportsIndex, /) -> Self: ... @overload def __new__(cls, start: SupportsIndex, stop: SupportsIndex, step: SupportsIndex = 1, /) -> Self: ... + def count(self, value: int, /) -> int: ... def index(self, value: int, /) -> int: ... # type: ignore[override] def __len__(self) -> int: ... @@ -1251,10 +1416,12 @@ class range(Sequence[int]): def __hash__(self) -> int: ... def __contains__(self, key: object, /) -> bool: ... def __iter__(self) -> Iterator[int]: ... + @overload def __getitem__(self, key: SupportsIndex, /) -> int: ... @overload def __getitem__(self, key: slice[SupportsIndex | None], /) -> range: ... + def __reversed__(self) -> Iterator[int]: ... @disjoint_base @@ -1276,10 +1443,12 @@ class property: 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: ... + @overload def __get__(self, instance: None, owner: type, /) -> Self: ... @overload def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ... + def __set__(self, instance: Any, value: Any, /) -> None: ... def __delete__(self, instance: Any, /) -> None: ... @@ -1287,77 +1456,132 @@ def abs(x: SupportsAbs[_T], /) -> _T: ... def all(iterable: Iterable[object], /) -> bool: ... def any(iterable: Iterable[object], /) -> bool: ... def ascii(obj: object, /) -> str: ... -def bin(number: SupportsIndex, /) -> str: ... + +if sys.version_info >= (3, 15): + def bin(integer: SupportsIndex, /) -> str: ... + +else: + def bin(number: SupportsIndex, /) -> str: ... + def breakpoint(*args: Any, **kws: Any) -> None: ... def callable(obj: object, /) -> TypeIs[Callable[..., object]]: ... def chr(i: SupportsIndex, /) -> str: ... +def aiter(async_iterable: SupportsAiter[_SupportsAnextT_co], /) -> _SupportsAnextT_co: ... -if sys.version_info >= (3, 10): - def aiter(async_iterable: SupportsAiter[_SupportsAnextT_co], /) -> _SupportsAnextT_co: ... - @type_check_only - class _SupportsSynchronousAnext(Protocol[_AwaitableT_co]): - def __anext__(self) -> _AwaitableT_co: ... +@type_check_only +class _SupportsSynchronousAnext(Protocol[_AwaitableT_co]): + def __anext__(self) -> _AwaitableT_co: ... - @overload - # `anext` is not, in fact, an async function. When default is not provided - # `anext` is just a passthrough for `obj.__anext__` - # See discussion in #7491 and pure-Python implementation of `anext` at https://github.com/python/cpython/blob/ea786a882b9ed4261eafabad6011bc7ef3b5bf94/Lib/test/test_asyncgen.py#L52-L80 - def anext(i: _SupportsSynchronousAnext[_AwaitableT], /) -> _AwaitableT: ... - @overload - async def anext(i: SupportsAnext[_T], default: _VT, /) -> _T | _VT: ... +@overload +# `anext` is not, in fact, an async function. When default is not provided +# `anext` is just a passthrough for `obj.__anext__` +# See discussion in #7491 and pure-Python implementation of `anext` at https://github.com/python/cpython/blob/ea786a882b9ed4261eafabad6011bc7ef3b5bf94/Lib/test/test_asyncgen.py#L52-L80 +def anext(i: _SupportsSynchronousAnext[_AwaitableT], /) -> _AwaitableT: ... +@overload +async def anext(i: SupportsAnext[_T], default: _VT, /) -> _T | _VT: ... # compile() returns a CodeType, unless the flags argument includes PyCF_ONLY_AST (=1024), # in which case it returns ast.AST. We have overloads for flag 0 (the default) and for # explicitly passing PyCF_ONLY_AST. We fall back to Any for other values of flags. -@overload -def compile( - source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, - filename: str | bytes | PathLike[Any], - mode: str, - flags: Literal[0], - dont_inherit: bool = False, - optimize: int = -1, - *, - _feature_version: int = -1, -) -> CodeType: ... -@overload -def compile( - source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, - filename: str | bytes | PathLike[Any], - mode: str, - *, - dont_inherit: bool = False, - optimize: int = -1, - _feature_version: int = -1, -) -> CodeType: ... -@overload -def compile( - source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, - filename: str | bytes | PathLike[Any], - mode: str, - flags: Literal[1024], - dont_inherit: bool = False, - optimize: int = -1, - *, - _feature_version: int = -1, -) -> _ast.AST: ... -@overload -def compile( - source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, - filename: str | bytes | PathLike[Any], - mode: str, - flags: int, - dont_inherit: bool = False, - optimize: int = -1, - *, - _feature_version: int = -1, -) -> Any: ... +if sys.version_info >= (3, 15): + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: Literal[0], + dont_inherit: bool = False, + optimize: int = -1, + *, + module: str | None = None, + _feature_version: int = -1, + ) -> CodeType: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + *, + dont_inherit: bool = False, + optimize: int = -1, + module: str | None = None, + _feature_version: int = -1, + ) -> CodeType: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: Literal[1024], + dont_inherit: bool = False, + optimize: int = -1, + *, + module: str | None = None, + _feature_version: int = -1, + ) -> _ast.AST: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: int, + dont_inherit: bool = False, + optimize: int = -1, + *, + module: str | None = None, + _feature_version: int = -1, + ) -> Any: ... +else: + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: Literal[0], + dont_inherit: bool = False, + optimize: int = -1, + *, + _feature_version: int = -1, + ) -> CodeType: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + *, + dont_inherit: bool = False, + optimize: int = -1, + _feature_version: int = -1, + ) -> CodeType: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: Literal[1024], + dont_inherit: bool = False, + optimize: int = -1, + *, + _feature_version: int = -1, + ) -> _ast.AST: ... + @overload + def compile( + source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive, + filename: str | bytes | PathLike[Any], + mode: str, + flags: int, + dont_inherit: bool = False, + optimize: int = -1, + *, + _feature_version: int = -1, + ) -> Any: ... copyright: _sitebuiltins._Printer credits: _sitebuiltins._Printer def delattr(obj: object, name: str, /) -> None: ... def dir(o: object = ..., /) -> list[str]: ... + @overload def divmod(x: SupportsDivMod[_T_contra, _T_co], y: _T_contra, /) -> _T_co: ... @overload @@ -1365,7 +1589,15 @@ def divmod(x: _T_contra, y: SupportsRDivMod[_T_contra, _T_co], /) -> _T_co: ... # The `globals` argument to `eval` has to be `dict[str, Any]` rather than `dict[str, object]` due to invariance. # (The `globals` argument has to be a "real dict", rather than any old mapping, unlike the `locals` argument.) -if sys.version_info >= (3, 13): +if sys.version_info >= (3, 15): + def eval( + source: str | ReadableBuffer | CodeType, + /, + globals: dict[str, Any] | frozendict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + ) -> Any: ... + +elif sys.version_info >= (3, 13): def eval( source: str | ReadableBuffer | CodeType, /, @@ -1382,7 +1614,17 @@ else: ) -> Any: ... # Comment above regarding `eval` applies to `exec` as well -if sys.version_info >= (3, 13): +if sys.version_info >= (3, 15): + def exec( + source: str | ReadableBuffer | CodeType, + /, + globals: dict[str, Any] | frozendict[str, Any] | None = None, + locals: Mapping[str, object] | None = None, + *, + closure: tuple[CellType, ...] | None = None, + ) -> None: ... + +elif sys.version_info >= (3, 13): def exec( source: str | ReadableBuffer | CodeType, /, @@ -1422,10 +1664,12 @@ class filter(Iterator[_T]): def __new__(cls, function: Callable[[_S], TypeIs[_T]], iterable: Iterable[_S], /) -> Self: ... @overload def __new__(cls, function: Callable[[_T], Any], iterable: Iterable[_T], /) -> Self: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T: ... def format(value: object, format_spec: str = "", /) -> str: ... + @overload def getattr(o: object, name: str, /) -> Any: ... @@ -1442,15 +1686,22 @@ def getattr(o: object, name: str, default: list[Any], /) -> Any | list[Any]: ... def getattr(o: object, name: str, default: dict[Any, Any], /) -> Any | dict[Any, Any]: ... @overload def getattr(o: object, name: str, default: _T, /) -> Any | _T: ... + def globals() -> dict[str, Any]: ... def hasattr(obj: object, name: str, /) -> bool: ... def hash(obj: object, /) -> int: ... help: _sitebuiltins._Helper -def hex(number: SupportsIndex, /) -> str: ... +if sys.version_info >= (3, 15): + def hex(integer: SupportsIndex, /) -> str: ... + +else: + def hex(number: SupportsIndex, /) -> str: ... + def id(obj: object, /) -> int: ... def input(prompt: object = "", /) -> str: ... + @type_check_only class _GetItemIterable(Protocol[_T_co]): def __getitem__(self, i: int, /) -> _T_co: ... @@ -1464,10 +1715,7 @@ def iter(object: Callable[[], _T | None], sentinel: None, /) -> Iterator[_T]: .. @overload def iter(object: Callable[[], _T], sentinel: object, /) -> Iterator[_T]: ... -if sys.version_info >= (3, 10): - _ClassInfo: TypeAlias = type | types.UnionType | tuple[_ClassInfo, ...] -else: - _ClassInfo: TypeAlias = type | tuple[_ClassInfo, ...] +_ClassInfo: TypeAlias = type | types.UnionType | tuple[_ClassInfo, ...] def isinstance(obj: object, class_or_tuple: _ClassInfo, /) -> bool: ... def issubclass(cls: type, class_or_tuple: _ClassInfo, /) -> bool: ... @@ -1476,6 +1724,7 @@ def len(obj: Sized, /) -> int: ... license: _sitebuiltins._Printer def locals() -> dict[str, Any]: ... + @disjoint_base class map(Iterator[_S]): # 3.14 adds `strict` argument. @@ -1597,6 +1846,7 @@ def max(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison def max(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, default: _T) -> SupportsRichComparisonT | _T: ... @overload def max(iterable: Iterable[_T1], /, *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ... + @overload def min( arg1: SupportsRichComparisonT, arg2: SupportsRichComparisonT, /, *_args: SupportsRichComparisonT, key: None = None @@ -1611,11 +1861,17 @@ def min(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison def min(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, default: _T) -> SupportsRichComparisonT | _T: ... @overload def min(iterable: Iterable[_T1], /, *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ... + @overload def next(i: SupportsNext[_T], /) -> _T: ... @overload def next(i: SupportsNext[_T], default: _VT, /) -> _T | _VT: ... -def oct(number: SupportsIndex, /) -> str: ... + +if sys.version_info >= (3, 15): + def oct(integer: SupportsIndex, /) -> str: ... + +else: + def oct(number: SupportsIndex, /) -> str: ... _Opener: TypeAlias = Callable[[str, int], int] @@ -1705,7 +1961,9 @@ def open( closefd: bool = True, opener: _Opener | None = None, ) -> IO[Any]: ... + def ord(c: str | bytes | bytearray, /) -> int: ... + @type_check_only class _SupportsWriteAndFlush(SupportsWrite[_T_contra], SupportsFlush, Protocol[_T_contra]): ... @@ -1789,6 +2047,7 @@ class reversed(Iterator[_T]): def __new__(cls, sequence: Reversible[_T], /) -> Iterator[_T]: ... # type: ignore[misc] @overload def __new__(cls, sequence: SupportsLenAndGetItem[_T], /) -> Iterator[_T]: ... # type: ignore[misc] + def __iter__(self) -> Self: ... def __next__(self) -> _T: ... def __length_hint__(self) -> int: ... @@ -1815,6 +2074,18 @@ def round(number: _SupportsRound2[_T], ndigits: SupportsIndex) -> _T: ... # See https://github.com/python/typeshed/pull/6292#discussion_r748875189 # for why arg 3 of `setattr` should be annotated with `Any` and not `object` def setattr(obj: object, name: str, value: Any, /) -> None: ... + +if sys.version_info >= (3, 15): + @final + class sentinel: + __name__: str + __module__: str + def __new__(cls, name: str, /) -> Self: ... + def __copy__(self, /) -> Self: ... + def __deepcopy__(self, memo: Any, /) -> Self: ... + def __or__(self, other: Any, /) -> Any: ... + def __ror__(self, other: Any, /) -> Any: ... + @overload def sorted( iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, reverse: bool = False @@ -1847,84 +2118,48 @@ def sum(iterable: Iterable[_AddableT1], /, start: _AddableT2) -> _AddableT1 | _A def vars(object: type, /) -> types.MappingProxyType[str, Any]: ... @overload def vars(object: Any = ..., /) -> dict[str, Any]: ... + @disjoint_base class zip(Iterator[_T_co]): - if sys.version_info >= (3, 10): - @overload - def __new__(cls, *, strict: bool = False) -> zip[Any]: ... - @overload - def __new__(cls, iter1: Iterable[_T1], /, *, strict: bool = False) -> zip[tuple[_T1]]: ... - @overload - def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, strict: bool = False) -> zip[tuple[_T1, _T2]]: ... - @overload - def __new__( - cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /, *, strict: bool = False - ) -> zip[tuple[_T1, _T2, _T3]]: ... - @overload - def __new__( - cls, - iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3], - iter4: Iterable[_T4], - /, - *, - strict: bool = False, - ) -> zip[tuple[_T1, _T2, _T3, _T4]]: ... - @overload - def __new__( - cls, - iter1: Iterable[_T1], - iter2: Iterable[_T2], - iter3: Iterable[_T3], - iter4: Iterable[_T4], - iter5: Iterable[_T5], - /, - *, - strict: bool = False, - ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]: ... - @overload - def __new__( - cls, - iter1: Iterable[Any], - iter2: Iterable[Any], - iter3: Iterable[Any], - iter4: Iterable[Any], - iter5: Iterable[Any], - iter6: Iterable[Any], - /, - *iterables: Iterable[Any], - strict: bool = False, - ) -> zip[tuple[Any, ...]]: ... - else: - @overload - def __new__(cls) -> zip[Any]: ... - @overload - def __new__(cls, iter1: Iterable[_T1], /) -> zip[tuple[_T1]]: ... - @overload - def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> zip[tuple[_T1, _T2]]: ... - @overload - def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /) -> zip[tuple[_T1, _T2, _T3]]: ... - @overload - def __new__( - cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], / - ) -> zip[tuple[_T1, _T2, _T3, _T4]]: ... - @overload - def __new__( - cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], / - ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]: ... - @overload - def __new__( - cls, - iter1: Iterable[Any], - iter2: Iterable[Any], - iter3: Iterable[Any], - iter4: Iterable[Any], - iter5: Iterable[Any], - iter6: Iterable[Any], - /, - *iterables: Iterable[Any], - ) -> zip[tuple[Any, ...]]: ... + @overload + def __new__(cls, *, strict: bool = False) -> zip[Any]: ... + @overload + def __new__(cls, iter1: Iterable[_T1], /, *, strict: bool = False) -> zip[tuple[_T1]]: ... + @overload + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, strict: bool = False) -> zip[tuple[_T1, _T2]]: ... + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /, *, strict: bool = False + ) -> zip[tuple[_T1, _T2, _T3]]: ... + @overload + def __new__( + cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /, *, strict: bool = False + ) -> zip[tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def __new__( + cls, + iter1: Iterable[_T1], + iter2: Iterable[_T2], + iter3: Iterable[_T3], + iter4: Iterable[_T4], + iter5: Iterable[_T5], + /, + *, + strict: bool = False, + ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def __new__( + cls, + iter1: Iterable[Any], + iter2: Iterable[Any], + iter3: Iterable[Any], + iter4: Iterable[Any], + iter5: Iterable[Any], + iter6: Iterable[Any], + /, + *iterables: Iterable[Any], + strict: bool = False, + ) -> zip[tuple[Any, ...]]: ... def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... @@ -1938,31 +2173,24 @@ def __import__( fromlist: Sequence[str] | None = (), level: int = 0, ) -> types.ModuleType: ... -def __build_class__(func: Callable[[], CellType | Any], name: str, /, *bases: Any, metaclass: Any = ..., **kwds: Any) -> Any: ... -if sys.version_info >= (3, 10): - from types import EllipsisType, NotImplementedType - - # Backwards compatibility hack for folks who relied on the ellipsis type - # existing in typeshed in Python 3.9 and earlier. - ellipsis = EllipsisType - - Ellipsis: EllipsisType - NotImplemented: NotImplementedType -else: - # Actually the type of Ellipsis is , but since it's - # not exposed anywhere under that name, we make it private here. - @final - @type_check_only - class ellipsis: ... +if sys.version_info >= (3, 15): + def __lazy_import__( + name: str, + globals: Mapping[str, object] | None = None, + locals: Mapping[str, object] | None = None, + fromlist: Sequence[str] | None = (), + level: int = 0, + ) -> Any: ... - Ellipsis: ellipsis +def __build_class__(func: Callable[[], CellType | Any], name: str, /, *bases: Any, metaclass: Any = ..., **kwds: Any) -> Any: ... - @final - @type_check_only - class _NotImplementedType(Any): ... +# Backwards compatibility hack for folks who relied on the ellipsis type +# existing in typeshed in Python 3.9 and earlier. +ellipsis = EllipsisType - NotImplemented: _NotImplementedType +Ellipsis: EllipsisType +NotImplemented: NotImplementedType @disjoint_base class BaseException: @@ -2015,15 +2243,11 @@ if sys.platform == "win32": class ArithmeticError(Exception): ... class AssertionError(Exception): ... -if sys.version_info >= (3, 10): - @disjoint_base - class AttributeError(Exception): - def __init__(self, *args: object, name: str | None = None, obj: object = None) -> None: ... - name: str | None - obj: object - -else: - class AttributeError(Exception): ... +@disjoint_base +class AttributeError(Exception): + def __init__(self, *args: object, name: str | None = None, obj: object = None) -> None: ... + name: str | None + obj: object class BufferError(Exception): ... class EOFError(Exception): ... @@ -2037,17 +2261,16 @@ class ImportError(Exception): if sys.version_info >= (3, 12): name_from: str | None # undocumented +if sys.version_info >= (3, 15): + class ImportCycleError(ImportError): ... + class LookupError(Exception): ... class MemoryError(Exception): ... -if sys.version_info >= (3, 10): - @disjoint_base - class NameError(Exception): - def __init__(self, *args: object, name: str | None = None) -> None: ... - name: str | None - -else: - class NameError(Exception): ... +@disjoint_base +class NameError(Exception): + def __init__(self, *args: object, name: str | None = None) -> None: ... + name: str | None class ReferenceError(Exception): ... class RuntimeError(Exception): ... @@ -2063,9 +2286,8 @@ class SyntaxError(Exception): # Errors are displayed differently if this attribute exists on the exception. # The value is always None. print_file_and_line: None - if sys.version_info >= (3, 10): - end_lineno: int | None - end_offset: int | None + end_lineno: int | None + end_offset: int | None @overload def __init__(self) -> None: ... @@ -2074,12 +2296,11 @@ class SyntaxError(Exception): # Second argument is the tuple (filename, lineno, offset, text) @overload def __init__(self, msg: str, info: tuple[str | None, int | None, int | None, str | None], /) -> None: ... - if sys.version_info >= (3, 10): - # end_lineno and end_offset must both be provided if one is. - @overload - def __init__( - self, msg: str, info: tuple[str | None, int | None, int | None, str | None, int | None, int | None], / - ) -> None: ... + # end_lineno and end_offset must both be provided if one is. + @overload + def __init__( + self, msg: str, info: tuple[str | None, int | None, int | None, str | None, int | None, int | None], / + ) -> None: ... # If you provide more than two arguments, it still creates the SyntaxError, but # the arguments from the info tuple are not parsed. This form is omitted. @@ -2155,9 +2376,7 @@ class ImportWarning(Warning): ... class UnicodeWarning(Warning): ... class BytesWarning(Warning): ... class ResourceWarning(Warning): ... - -if sys.version_info >= (3, 10): - class EncodingWarning(Warning): ... +class EncodingWarning(Warning): ... if sys.version_info >= (3, 11): _BaseExceptionT_co = TypeVar("_BaseExceptionT_co", bound=BaseException, covariant=True, default=BaseException) @@ -2174,6 +2393,7 @@ if sys.version_info >= (3, 11): def message(self) -> str: ... @property def exceptions(self) -> tuple[_BaseExceptionT_co | BaseExceptionGroup[_BaseExceptionT_co], ...]: ... + @overload def subgroup( self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / @@ -2186,6 +2406,7 @@ if sys.version_info >= (3, 11): def subgroup( self, matcher_value: Callable[[_BaseExceptionT_co | Self], bool], / ) -> BaseExceptionGroup[_BaseExceptionT_co] | None: ... + @overload def split( self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / @@ -2198,11 +2419,13 @@ if sys.version_info >= (3, 11): def split( self, matcher_value: Callable[[_BaseExceptionT_co | Self], bool], / ) -> tuple[BaseExceptionGroup[_BaseExceptionT_co] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ... + # In reality it is `NonEmptySequence`: @overload def derive(self, excs: Sequence[_ExceptionT], /) -> ExceptionGroup[_ExceptionT]: ... @overload def derive(self, excs: Sequence[_BaseExceptionT], /) -> BaseExceptionGroup[_BaseExceptionT]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class ExceptionGroup(BaseExceptionGroup[_ExceptionT_co], Exception): @@ -2210,6 +2433,7 @@ if sys.version_info >= (3, 11): def __init__(self, message: str, exceptions: Sequence[_ExceptionT_co], /) -> None: ... @property def exceptions(self) -> tuple[_ExceptionT_co | ExceptionGroup[_ExceptionT_co], ...]: ... + # We accept a narrower type, but that's OK. @overload # type: ignore[override] def subgroup( @@ -2219,6 +2443,7 @@ if sys.version_info >= (3, 11): def subgroup( self, matcher_value: Callable[[_ExceptionT_co | Self], bool], / ) -> ExceptionGroup[_ExceptionT_co] | None: ... + @overload # type: ignore[override] def split( self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], / diff --git a/mypy/typeshed/stdlib/bz2.pyi b/mypy/typeshed/stdlib/bz2.pyi index 7bd829d040cb8..fec6b30af2f5a 100644 --- a/mypy/typeshed/stdlib/bz2.pyi +++ b/mypy/typeshed/stdlib/bz2.pyi @@ -3,8 +3,8 @@ from _bz2 import BZ2Compressor as BZ2Compressor, BZ2Decompressor as BZ2Decompres from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer from collections.abc import Iterable from io import TextIOWrapper -from typing import IO, Literal, Protocol, SupportsIndex, overload, type_check_only -from typing_extensions import Self, TypeAlias +from typing import IO, Literal, Protocol, SupportsIndex, TypeAlias, overload, type_check_only +from typing_extensions import Self if sys.version_info >= (3, 14): from compression._common._streams import BaseStream, _Reader @@ -100,6 +100,7 @@ def open( class BZ2File(BaseStream, IO[bytes]): def __enter__(self) -> Self: ... + @overload def __init__(self, filename: _WritableFileobj, mode: _WriteBinaryMode, *, compresslevel: int = 9) -> None: ... @overload @@ -108,6 +109,7 @@ class BZ2File(BaseStream, IO[bytes]): def __init__( self, filename: StrOrBytesPath, mode: _ReadBinaryMode | _WriteBinaryMode = "r", *, compresslevel: int = 9 ) -> None: ... + def read(self, size: int | None = -1) -> bytes: ... def read1(self, size: int = -1) -> bytes: ... def readline(self, size: SupportsIndex = -1) -> bytes: ... # type: ignore[override] diff --git a/mypy/typeshed/stdlib/cProfile.pyi b/mypy/typeshed/stdlib/cProfile.pyi index e921584d43905..0e414206f5156 100644 --- a/mypy/typeshed/stdlib/cProfile.pyi +++ b/mypy/typeshed/stdlib/cProfile.pyi @@ -1,9 +1,10 @@ import _lsprof +import sys from _typeshed import StrOrBytesPath, Unused from collections.abc import Callable, Mapping from types import CodeType -from typing import Any, TypeVar -from typing_extensions import ParamSpec, Self, TypeAlias +from typing import Any, ParamSpec, TypeAlias, TypeVar +from typing_extensions import Self __all__ = ["run", "runctx", "Profile"] @@ -28,4 +29,5 @@ class Profile(_lsprof.Profiler): def __enter__(self) -> Self: ... def __exit__(self, *exc_info: Unused) -> None: ... -def label(code: str | CodeType) -> _Label: ... # undocumented +if sys.version_info < (3, 15): + def label(code: str | CodeType) -> _Label: ... # undocumented diff --git a/mypy/typeshed/stdlib/calendar.pyi b/mypy/typeshed/stdlib/calendar.pyi index 0d3a0a7490a33..45c0c7b8346cd 100644 --- a/mypy/typeshed/stdlib/calendar.pyi +++ b/mypy/typeshed/stdlib/calendar.pyi @@ -2,12 +2,18 @@ import datetime import enum import sys from _typeshed import Unused -from collections.abc import Iterable, Sequence +from collections.abc import Iterable from time import struct_time -from typing import ClassVar, Final -from typing_extensions import TypeAlias +from typing import ClassVar, Final, TypeAlias, overload __all__ = [ + "FRIDAY", + "MONDAY", + "SATURDAY", + "SUNDAY", + "THURSDAY", + "TUESDAY", + "WEDNESDAY", "IllegalMonthError", "IllegalWeekdayError", "setfirstweekday", @@ -34,8 +40,6 @@ __all__ = [ "weekheader", ] -if sys.version_info >= (3, 10): - __all__ += ["FRIDAY", "MONDAY", "SATURDAY", "SUNDAY", "THURSDAY", "TUESDAY", "WEDNESDAY"] if sys.version_info >= (3, 12): __all__ += [ "Day", @@ -53,6 +57,8 @@ if sys.version_info >= (3, 12): "NOVEMBER", "DECEMBER", ] +if sys.version_info >= (3, 15): + __all__ += ["standalone_month_name", "standalone_month_abbr"] _LocaleType: TypeAlias = tuple[str | None, str | None] @@ -88,9 +94,9 @@ class Calendar: def itermonthdays4(self, year: int, month: int) -> Iterable[tuple[int, int, int, int]]: ... class TextCalendar(Calendar): - def prweek(self, theweek: int, width: int) -> None: ... + def prweek(self, theweek: Iterable[tuple[int, int]], width: int) -> None: ... def formatday(self, day: int, weekday: int, width: int) -> str: ... - def formatweek(self, theweek: int, width: int) -> str: ... + def formatweek(self, theweek: Iterable[tuple[int, int]], width: int) -> str: ... def formatweekday(self, day: int, width: int) -> str: ... def formatweekheader(self, width: int) -> str: ... def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = True) -> str: ... @@ -123,6 +129,11 @@ class HTMLCalendar(Calendar): def formatweekheader(self) -> str: ... def formatmonthname(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... def formatmonth(self, theyear: int, themonth: int, withyear: bool = True) -> str: ... + if sys.version_info >= (3, 15): + def formatmonthpage( + self, theyear: int, themonth: int, width: int = 3, css: str | None = "calendar.css", encoding: str | None = None + ) -> bytes: ... + def formatyear(self, theyear: int, width: int = 3) -> str: ... def formatyearpage( self, theyear: int, width: int = 3, css: str | None = "calendar.css", encoding: str | None = None @@ -145,14 +156,36 @@ c: TextCalendar def setfirstweekday(firstweekday: int) -> None: ... def format(cols: int, colwidth: int = 20, spacing: int = 6) -> str: ... -def formatstring(cols: int, colwidth: int = 20, spacing: int = 6) -> str: ... +def formatstring(cols: Iterable[str], colwidth: int = 20, spacing: int = 6) -> str: ... def timegm(tuple: tuple[int, ...] | struct_time) -> int: ... # Data attributes -day_name: Sequence[str] -day_abbr: Sequence[str] -month_name: Sequence[str] -month_abbr: Sequence[str] +class _localized_month: + format: str + def __init__(self, format: str) -> None: ... + + @overload + def __getitem__(self, i: int) -> str: ... + @overload + def __getitem__(self, i: slice) -> list[str]: ... + + def __len__(self) -> int: ... + +class _localized_day: + format: str + def __init__(self, format: str) -> None: ... + + @overload + def __getitem__(self, i: int) -> str: ... + @overload + def __getitem__(self, i: slice) -> list[str]: ... + + def __len__(self) -> int: ... + +day_name: _localized_day +day_abbr: _localized_day +month_name: _localized_month +month_abbr: _localized_month if sys.version_info >= (3, 12): class Month(enum.IntEnum): @@ -208,3 +241,7 @@ else: SUNDAY: Final = 6 EPOCH: Final = 1970 + +if sys.version_info >= (3, 15): + standalone_month_name: _localized_month + standalone_month_abbr: _localized_month diff --git a/mypy/typeshed/stdlib/cgi.pyi b/mypy/typeshed/stdlib/cgi.pyi index 0f9d4343b6307..b7f88ded315f4 100644 --- a/mypy/typeshed/stdlib/cgi.pyi +++ b/mypy/typeshed/stdlib/cgi.pyi @@ -32,6 +32,7 @@ def parse( def parse_multipart( fp: IO[Any], pdict: SupportsGetItem[str, bytes], encoding: str = "utf-8", errors: str = "replace", separator: str = "&" ) -> dict[str, list[Any]]: ... + @type_check_only class _Environ(Protocol): def __getitem__(self, k: str, /) -> str: ... diff --git a/mypy/typeshed/stdlib/cmath.pyi b/mypy/typeshed/stdlib/cmath.pyi index fdf8ae7bfed8d..554eb54e2e4cc 100644 --- a/mypy/typeshed/stdlib/cmath.pyi +++ b/mypy/typeshed/stdlib/cmath.pyi @@ -1,5 +1,4 @@ -from typing import Final, SupportsComplex, SupportsFloat, SupportsIndex -from typing_extensions import TypeAlias +from typing import Final, SupportsComplex, SupportsFloat, SupportsIndex, TypeAlias e: Final[float] pi: Final[float] diff --git a/mypy/typeshed/stdlib/codecs.pyi b/mypy/typeshed/stdlib/codecs.pyi index 9164a4a626d4f..b341d0f813c41 100644 --- a/mypy/typeshed/stdlib/codecs.pyi +++ b/mypy/typeshed/stdlib/codecs.pyi @@ -4,8 +4,8 @@ from _codecs import * from _typeshed import ReadableBuffer from abc import abstractmethod from collections.abc import Callable, Generator, Iterable -from typing import Any, BinaryIO, ClassVar, Final, Literal, Protocol, TextIO, overload, type_check_only -from typing_extensions import Self, TypeAlias, deprecated, disjoint_base +from typing import Any, BinaryIO, ClassVar, Final, Literal, Protocol, TextIO, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated, disjoint_base __all__ = [ "register", @@ -185,10 +185,12 @@ else: def getencoder(encoding: str) -> _Encoder: ... def getdecoder(encoding: str) -> _Decoder: ... def getincrementalencoder(encoding: str) -> _IncrementalEncoder: ... + @overload def getincrementaldecoder(encoding: _BufferedEncoding) -> _BufferedIncrementalDecoder: ... @overload def getincrementaldecoder(encoding: str) -> _IncrementalDecoder: ... + def getreader(encoding: str) -> _StreamReader: ... def getwriter(encoding: str) -> _StreamWriter: ... @deprecated("Deprecated since Python 3.14. Use `open()` instead.") diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index 95f13b0c8dd2b..d9c2e342c5871 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -1,25 +1,24 @@ import sys from _collections_abc import dict_items, dict_keys, dict_values from _typeshed import SupportsItems, SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT +from collections.abc import ( + Callable, + ItemsView, + Iterable, + Iterator, + KeysView, + Mapping, + MutableMapping, + MutableSequence, + Sequence, + ValuesView, +) from types import GenericAlias from typing import Any, ClassVar, Generic, NoReturn, SupportsIndex, TypeVar, final, overload, type_check_only from typing_extensions import Self, disjoint_base -if sys.version_info >= (3, 10): - from collections.abc import ( - Callable, - ItemsView, - Iterable, - Iterator, - KeysView, - Mapping, - MutableMapping, - MutableSequence, - Sequence, - ValuesView, - ) -else: - from _collections_abc import * +if sys.version_info >= (3, 15): + from builtins import frozendict __all__ = ["ChainMap", "Counter", "OrderedDict", "UserDict", "UserList", "UserString", "defaultdict", "deque", "namedtuple"] @@ -44,6 +43,7 @@ def namedtuple( class UserDict(MutableMapping[_KT, _VT]): data: dict[_KT, _VT] + # __init__ should be kept roughly in line with `dict.__init__`, which has the same semantics @overload def __init__(self, dict: None = None, /) -> None: ... @@ -73,6 +73,7 @@ class UserDict(MutableMapping[_KT, _VT]): def __init__(self: UserDict[str, str], iterable: Iterable[list[str]], /) -> None: ... @overload def __init__(self: UserDict[bytes, bytes], iterable: Iterable[list[bytes]], /) -> None: ... + def __len__(self) -> int: ... def __getitem__(self, key: _KT) -> _VT: ... def __setitem__(self, key: _KT, item: _VT) -> None: ... @@ -91,19 +92,23 @@ class UserDict(MutableMapping[_KT, _VT]): @classmethod @overload def fromkeys(cls, iterable: Iterable[_T], value: _S) -> UserDict[_T, _S]: ... + @overload def __or__(self, other: UserDict[_KT, _VT] | dict[_KT, _VT]) -> Self: ... @overload def __or__(self, other: UserDict[_T1, _T2] | dict[_T1, _T2]) -> UserDict[_KT | _T1, _VT | _T2]: ... + @overload def __ror__(self, other: UserDict[_KT, _VT] | dict[_KT, _VT]) -> Self: ... @overload def __ror__(self, other: UserDict[_T1, _T2] | dict[_T1, _T2]) -> UserDict[_KT | _T1, _VT | _T2]: ... + # UserDict.__ior__ should be kept roughly in line with MutableMapping.update() @overload # type: ignore[misc] def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... @overload def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... + if sys.version_info >= (3, 12): @overload def get(self, key: _KT, default: None = None) -> _VT | None: ... @@ -114,10 +119,12 @@ class UserDict(MutableMapping[_KT, _VT]): class UserList(MutableSequence[_T]): data: list[_T] + @overload def __init__(self, initlist: None = None) -> None: ... @overload def __init__(self, initlist: Iterable[_T]) -> None: ... + __hash__: ClassVar[None] # type: ignore[assignment] def __lt__(self, other: list[_T] | UserList[_T]) -> bool: ... def __le__(self, other: list[_T] | UserList[_T]) -> bool: ... @@ -126,14 +133,17 @@ class UserList(MutableSequence[_T]): def __eq__(self, other: object) -> bool: ... def __contains__(self, item: object) -> bool: ... def __len__(self) -> int: ... + @overload def __getitem__(self, i: SupportsIndex) -> _T: ... @overload def __getitem__(self, i: slice[SupportsIndex | None]) -> Self: ... + @overload def __setitem__(self, i: SupportsIndex, item: _T) -> None: ... @overload def __setitem__(self, i: slice[SupportsIndex | None], item: Iterable[_T]) -> None: ... + def __delitem__(self, i: SupportsIndex | slice[SupportsIndex | None]) -> None: ... def __add__(self, other: Iterable[_T]) -> Self: ... def __radd__(self, other: Iterable[_T]) -> Self: ... @@ -152,11 +162,13 @@ class UserList(MutableSequence[_T]): # to `list.index`. In order to give more precise types, we pretend that the # `item` argument is positional-only. def index(self, item: _T, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ... + # All arguments are passed to `list.sort` at runtime, so the signature should be kept in line with `list.sort`. @overload def sort(self: UserList[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None: ... @overload def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None: ... + def extend(self, other: Iterable[_T]) -> None: ... class UserString(Sequence[UserString]): @@ -235,10 +247,12 @@ class UserString(Sequence[UserString]): class deque(MutableSequence[_T]): @property def maxlen(self) -> int | None: ... + @overload def __init__(self, *, maxlen: int | None = None) -> None: ... @overload def __init__(self, iterable: Iterable[_T], maxlen: int | None = None) -> None: ... + def append(self, x: _T, /) -> None: ... def appendleft(self, x: _T, /) -> None: ... def copy(self) -> Self: ... @@ -280,17 +294,20 @@ class Counter(dict[_T, int], Generic[_T]): def __init__(self, mapping: SupportsKeysAndGetItem[_T, int], /) -> None: ... @overload def __init__(self, iterable: Iterable[_T], /) -> None: ... + def copy(self) -> Self: ... def elements(self) -> Iterator[_T]: ... def most_common(self, n: int | None = None) -> list[tuple[_T, int]]: ... @classmethod def fromkeys(cls, iterable: Any, v: int | None = None) -> NoReturn: ... # type: ignore[override] + @overload def subtract(self, iterable: None = None, /) -> None: ... @overload def subtract(self, mapping: Mapping[_T, int], /) -> None: ... @overload def subtract(self, iterable: Iterable[_T], /) -> None: ... + # Unlike dict.update(), use Mapping instead of SupportsKeysAndGetItem for the first overload # (source code does an `isinstance(other, Mapping)` check) # @@ -303,16 +320,23 @@ class Counter(dict[_T, int], Generic[_T]): def update(self, iterable: Iterable[_T], /, **kwargs: int) -> None: ... @overload def update(self, iterable: None = None, /, **kwargs: int) -> None: ... + + def total(self) -> int: ... def __missing__(self, key: _T) -> int: ... def __delitem__(self, elem: object) -> None: ... - if sys.version_info >= (3, 10): - def __eq__(self, other: object) -> bool: ... - def __ne__(self, other: object) -> bool: ... - + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __le__(self, other: Counter[Any]) -> bool: ... + def __lt__(self, other: Counter[Any]) -> bool: ... + def __ge__(self, other: Counter[Any]) -> bool: ... + def __gt__(self, other: Counter[Any]) -> bool: ... def __add__(self, other: Counter[_S]) -> Counter[_T | _S]: ... def __sub__(self, other: Counter[_T]) -> Counter[_T]: ... def __and__(self, other: Counter[_T]) -> Counter[_T]: ... def __or__(self, other: Counter[_S]) -> Counter[_T | _S]: ... # type: ignore[override] + if sys.version_info >= (3, 15): + def __xor__(self, other: Counter[_S]) -> Counter[_T | _S]: ... # type: ignore[override] + def __pos__(self) -> Counter[_T]: ... def __neg__(self) -> Counter[_T]: ... # several type: ignores because __iadd__ is supposedly incompatible with __add__, etc. @@ -320,12 +344,8 @@ class Counter(dict[_T, int], Generic[_T]): def __isub__(self, other: SupportsItems[_T, int]) -> Self: ... def __iand__(self, other: SupportsItems[_T, int]) -> Self: ... def __ior__(self, other: SupportsItems[_T, int]) -> Self: ... # type: ignore[override,misc] - if sys.version_info >= (3, 10): - def total(self) -> int: ... - def __le__(self, other: Counter[Any]) -> bool: ... - def __lt__(self, other: Counter[Any]) -> bool: ... - def __ge__(self, other: Counter[Any]) -> bool: ... - def __gt__(self, other: Counter[Any]) -> bool: ... + if sys.version_info >= (3, 15): + def __ixor__(self, other: Counter[_T]) -> Self: ... # type: ignore[misc] # The pure-Python implementations of the "views" classes # These are exposed at runtime in `collections/__init__.py` @@ -366,6 +386,7 @@ class OrderedDict(dict[_KT, _VT]): def keys(self) -> _odict_keys[_KT, _VT]: ... def items(self) -> _odict_items[_KT, _VT]: ... def values(self) -> _odict_values[_KT, _VT]: ... + # The signature of OrderedDict.fromkeys should be kept in line with `dict.fromkeys`, modulo positional-only differences. # Like dict.fromkeys, its true signature is not expressible in the current type system. # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963. @@ -375,11 +396,13 @@ class OrderedDict(dict[_KT, _VT]): @classmethod @overload def fromkeys(cls, iterable: Iterable[_T], value: _S) -> OrderedDict[_T, _S]: ... + # Keep OrderedDict.setdefault in line with MutableMapping.setdefault, modulo positional-only differences. @overload def setdefault(self: OrderedDict[_KT, _T | None], key: _KT, default: None = None) -> _T | None: ... @overload def setdefault(self, key: _KT, default: _VT) -> _VT: ... + # Same as dict.pop, but accepts keyword arguments @overload def pop(self, key: _KT) -> _VT: ... @@ -387,19 +410,36 @@ class OrderedDict(dict[_KT, _VT]): def pop(self, key: _KT, default: _VT) -> _VT: ... @overload def pop(self, key: _KT, default: _T) -> _VT | _T: ... + def __eq__(self, value: object, /) -> bool: ... - @overload - def __or__(self, value: dict[_KT, _VT], /) -> Self: ... - @overload - def __or__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... - @overload - def __ror__(self, value: dict[_KT, _VT], /) -> Self: ... - @overload - def __ror__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] + + if sys.version_info >= (3, 15): + @overload + def __or__(self, value: dict[_KT, _VT] | frozendict[_KT, _VT], /) -> Self: ... + @overload + def __or__(self, value: dict[_T1, _T2] | frozendict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... + + @overload # type: ignore[override] + def __ror__(self, value: dict[_KT, _VT] | frozendict[_KT, _VT], /) -> Self: ... # type: ignore[override,misc] + @overload + def __ror__( # type: ignore[misc] + self, value: dict[_T1, _T2] | frozendict[_T1, _T2], / + ) -> OrderedDict[_KT | _T1, _VT | _T2]: ... + else: + @overload + def __or__(self, value: dict[_KT, _VT], /) -> Self: ... + @overload + def __or__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... + + @overload + def __ror__(self, value: dict[_KT, _VT], /) -> Self: ... + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] @disjoint_base class defaultdict(dict[_KT, _VT]): default_factory: Callable[[], _VT] | None + @overload def __init__(self) -> None: ... @overload @@ -433,14 +473,19 @@ class defaultdict(dict[_KT, _VT]): /, **kwargs: _VT, ) -> None: ... + def __missing__(self, key: _KT, /) -> _VT: ... def __copy__(self) -> Self: ... def copy(self) -> Self: ... - @overload + + # defaultdict rejects frozendict in its direct __or__/__ror__ methods, even though dict accepts it. + # See https://github.com/python/cpython/issues/149534. + @overload # type: ignore[override] def __or__(self, value: dict[_KT, _VT], /) -> Self: ... @overload def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... - @overload + + @overload # type: ignore[override] def __ror__(self, value: dict[_KT, _VT], /) -> Self: ... @overload def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] @@ -457,25 +502,30 @@ class ChainMap(MutableMapping[_KT, _VT]): def __iter__(self) -> Iterator[_KT]: ... def __len__(self) -> int: ... def __contains__(self, key: object) -> bool: ... + @overload def get(self, key: _KT, default: None = None) -> _VT | None: ... @overload def get(self, key: _KT, default: _VT) -> _VT: ... @overload def get(self, key: _KT, default: _T) -> _VT | _T: ... + def __missing__(self, key: _KT) -> _VT: ... # undocumented def __bool__(self) -> bool: ... + # Keep ChainMap.setdefault in line with MutableMapping.setdefault, modulo positional-only differences. @overload def setdefault(self: ChainMap[_KT, _T | None], key: _KT, default: None = None) -> _T | None: ... @overload def setdefault(self, key: _KT, default: _VT) -> _VT: ... + @overload def pop(self, key: _KT) -> _VT: ... @overload def pop(self, key: _KT, default: _VT) -> _VT: ... @overload def pop(self, key: _KT, default: _T) -> _VT | _T: ... + def copy(self) -> Self: ... __copy__ = copy # All arguments to `fromkeys` are passed to `dict.fromkeys` at runtime, @@ -496,14 +546,17 @@ class ChainMap(MutableMapping[_KT, _VT]): @classmethod @overload def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> ChainMap[_T, _S]: ... + @overload def __or__(self, other: Mapping[_KT, _VT]) -> Self: ... @overload def __or__(self, other: Mapping[_T1, _T2]) -> ChainMap[_KT | _T1, _VT | _T2]: ... + @overload def __ror__(self, other: Mapping[_KT, _VT]) -> Self: ... @overload def __ror__(self, other: Mapping[_T1, _T2]) -> ChainMap[_KT | _T1, _VT | _T2]: ... + # ChainMap.__ior__ should be kept roughly in line with MutableMapping.update() @overload # type: ignore[misc] def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... diff --git a/mypy/typeshed/stdlib/colorsys.pyi b/mypy/typeshed/stdlib/colorsys.pyi index 4afcb5392b58e..d4edab12ecc70 100644 --- a/mypy/typeshed/stdlib/colorsys.pyi +++ b/mypy/typeshed/stdlib/colorsys.pyi @@ -9,7 +9,7 @@ def hls_to_rgb(h: float, l: float, s: float) -> tuple[float, float, float]: ... def rgb_to_hsv(r: float, g: float, b: float) -> tuple[float, float, float]: ... def hsv_to_rgb(h: float, s: float, v: float) -> tuple[float, float, float]: ... -# TODO: undocumented +# undocumented ONE_SIXTH: Final[float] ONE_THIRD: Final[float] TWO_THIRD: Final[float] diff --git a/mypy/typeshed/stdlib/compileall.pyi b/mypy/typeshed/stdlib/compileall.pyi index 8972d50a4a634..49a4c69dd3fb0 100644 --- a/mypy/typeshed/stdlib/compileall.pyi +++ b/mypy/typeshed/stdlib/compileall.pyi @@ -1,4 +1,3 @@ -import sys from _typeshed import StrPath from py_compile import PycInvalidationMode from typing import Any, Protocol, type_check_only @@ -9,74 +8,38 @@ __all__ = ["compile_dir", "compile_file", "compile_path"] class _SupportsSearch(Protocol): def search(self, string: str, /) -> Any: ... -if sys.version_info >= (3, 10): - def compile_dir( - dir: StrPath, - maxlevels: int | None = None, - ddir: StrPath | None = None, - force: bool = False, - rx: _SupportsSearch | None = None, - quiet: int = 0, - legacy: bool = False, - optimize: int = -1, - workers: int = 1, - invalidation_mode: PycInvalidationMode | None = None, - *, - stripdir: StrPath | None = None, - prependdir: StrPath | None = None, - limit_sl_dest: StrPath | None = None, - hardlink_dupes: bool = False, - ) -> bool: ... - def compile_file( - fullname: StrPath, - ddir: StrPath | None = None, - force: bool = False, - rx: _SupportsSearch | None = None, - quiet: int = 0, - legacy: bool = False, - optimize: int = -1, - invalidation_mode: PycInvalidationMode | None = None, - *, - stripdir: StrPath | None = None, - prependdir: StrPath | None = None, - limit_sl_dest: StrPath | None = None, - hardlink_dupes: bool = False, - ) -> bool: ... - -else: - def compile_dir( - dir: StrPath, - maxlevels: int | None = None, - ddir: StrPath | None = None, - force: bool = False, - rx: _SupportsSearch | None = None, - quiet: int = 0, - legacy: bool = False, - optimize: int = -1, - workers: int = 1, - invalidation_mode: PycInvalidationMode | None = None, - *, - stripdir: str | None = None, # https://bugs.python.org/issue40447 - prependdir: StrPath | None = None, - limit_sl_dest: StrPath | None = None, - hardlink_dupes: bool = False, - ) -> bool: ... - def compile_file( - fullname: StrPath, - ddir: StrPath | None = None, - force: bool = False, - rx: _SupportsSearch | None = None, - quiet: int = 0, - legacy: bool = False, - optimize: int = -1, - invalidation_mode: PycInvalidationMode | None = None, - *, - stripdir: str | None = None, # https://bugs.python.org/issue40447 - prependdir: StrPath | None = None, - limit_sl_dest: StrPath | None = None, - hardlink_dupes: bool = False, - ) -> bool: ... - +def compile_dir( + dir: StrPath, + maxlevels: int | None = None, + ddir: StrPath | None = None, + force: bool = False, + rx: _SupportsSearch | None = None, + quiet: int = 0, + legacy: bool = False, + optimize: int = -1, + workers: int = 1, + invalidation_mode: PycInvalidationMode | None = None, + *, + stripdir: StrPath | None = None, + prependdir: StrPath | None = None, + limit_sl_dest: StrPath | None = None, + hardlink_dupes: bool = False, +) -> bool: ... +def compile_file( + fullname: StrPath, + ddir: StrPath | None = None, + force: bool = False, + rx: _SupportsSearch | None = None, + quiet: int = 0, + legacy: bool = False, + optimize: int = -1, + invalidation_mode: PycInvalidationMode | None = None, + *, + stripdir: StrPath | None = None, + prependdir: StrPath | None = None, + limit_sl_dest: StrPath | None = None, + hardlink_dupes: bool = False, +) -> bool: ... def compile_path( skip_curdir: bool = ..., maxlevels: int = 0, diff --git a/mypy/typeshed/stdlib/compression/zstd/__init__.pyi b/mypy/typeshed/stdlib/compression/zstd/__init__.pyi index acfbe4913b5da..8673c59a41c22 100644 --- a/mypy/typeshed/stdlib/compression/zstd/__init__.pyi +++ b/mypy/typeshed/stdlib/compression/zstd/__init__.pyi @@ -52,6 +52,7 @@ def compress( def decompress( data: ReadableBuffer, zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, options: Mapping[int, int] | None = None ) -> bytes: ... + @final class CompressionParameter(enum.IntEnum): compression_level = _zstd.ZSTD_c_compressionLevel diff --git a/mypy/typeshed/stdlib/compression/zstd/_zstdfile.pyi b/mypy/typeshed/stdlib/compression/zstd/_zstdfile.pyi index d37e6b1741664..b16b43c1da0ae 100644 --- a/mypy/typeshed/stdlib/compression/zstd/_zstdfile.pyi +++ b/mypy/typeshed/stdlib/compression/zstd/_zstdfile.pyi @@ -3,8 +3,7 @@ from collections.abc import Mapping from compression._common import _streams from compression.zstd import ZstdDict from io import TextIOWrapper, _WrappedBuffer -from typing import Literal, Protocol, overload, type_check_only -from typing_extensions import TypeAlias +from typing import Literal, Protocol, TypeAlias, overload, type_check_only from _zstd import ZstdCompressor, _ZstdCompressorFlushBlock, _ZstdCompressorFlushFrame @@ -49,6 +48,7 @@ class ZstdFile(_streams.BaseStream): options: Mapping[int, int] | None = None, zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, ) -> None: ... + def write(self, data: ReadableBuffer, /) -> int: ... def flush(self, mode: _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 1) -> bytes: ... # type: ignore[override] def read(self, size: int | None = -1) -> bytes: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi index be48a6e4289c8..05680b5de4619 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi @@ -4,8 +4,8 @@ from _typeshed import Unused from collections.abc import Callable, Iterable, Iterator from logging import Logger from types import GenericAlias, TracebackType -from typing import Any, Final, Generic, NamedTuple, Protocol, TypeVar, type_check_only -from typing_extensions import ParamSpec, Self +from typing import Any, Final, Generic, NamedTuple, ParamSpec, Protocol, TypeVar, type_check_only +from typing_extensions import Self FIRST_COMPLETED: Final = "FIRST_COMPLETED" FIRST_EXCEPTION: Final = "FIRST_EXCEPTION" diff --git a/mypy/typeshed/stdlib/concurrent/futures/interpreter.pyi b/mypy/typeshed/stdlib/concurrent/futures/interpreter.pyi index e101022babcb6..f6925806a5eb9 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/interpreter.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/interpreter.pyi @@ -1,8 +1,8 @@ import sys from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor -from typing import Any, Literal, Protocol, overload, type_check_only -from typing_extensions import ParamSpec, Self, TypeAlias, TypeVar, TypeVarTuple, Unpack +from typing import Any, Literal, ParamSpec, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self, TypeVar, TypeVarTuple, Unpack _Task: TypeAlias = tuple[bytes, Literal["function", "script"]] _Ts = TypeVarTuple("_Ts") @@ -25,6 +25,7 @@ if sys.version_info >= (3, 14): class WorkerContext(ThreadWorkerContext): interp: Interpreter | None results: Queue | None + @overload # type: ignore[override] @classmethod def prepare( @@ -33,6 +34,7 @@ if sys.version_info >= (3, 14): @overload @classmethod def prepare(cls, initializer: Callable[[], object], initargs: tuple[()]) -> tuple[Callable[[], Self], _TaskFunc]: ... + def __init__(self, initdata: _Task) -> None: ... def __del__(self) -> None: ... def run(self, task: _Task) -> None: ... # type: ignore[override] @@ -52,6 +54,7 @@ if sys.version_info >= (3, 14): def prepare_context( cls, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]] ) -> tuple[Callable[[], WorkerContext], _TaskFunc]: ... + @overload def __init__( self, diff --git a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi index 50a6a9c6f43ea..685bf1cfc104a 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi @@ -3,8 +3,8 @@ import sys from collections.abc import Callable, Iterable, Mapping, Set as AbstractSet from threading import Lock, Semaphore, Thread from types import GenericAlias -from typing import Any, Generic, Protocol, TypeVar, overload, type_check_only -from typing_extensions import Self, TypeAlias, TypeVarTuple, Unpack +from typing import Any, Generic, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, TypeVarTuple, Unpack from weakref import ref from ._base import BrokenExecutor, Executor, Future @@ -43,10 +43,12 @@ if sys.version_info >= (3, 14): def prepare( cls, initializer: Callable[[], object], initargs: tuple[()] ) -> tuple[Callable[[], Self], _ResolveTaskFunc]: ... + @overload def __init__(self, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]]) -> None: ... @overload def __init__(self, initializer: Callable[[], object], initargs: tuple[()]) -> None: ... + def initialize(self) -> None: ... def finalize(self) -> None: ... def run(self, task: _Task) -> None: ... @@ -136,5 +138,6 @@ class ThreadPoolExecutor(Executor): initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]], ) -> None: ... + def _adjust_thread_count(self) -> None: ... def _initializer_failed(self) -> None: ... diff --git a/mypy/typeshed/stdlib/concurrent/interpreters/__init__.pyi b/mypy/typeshed/stdlib/concurrent/interpreters/__init__.pyi index 171fadb2202be..d19db09642602 100644 --- a/mypy/typeshed/stdlib/concurrent/interpreters/__init__.pyi +++ b/mypy/typeshed/stdlib/concurrent/interpreters/__init__.pyi @@ -2,8 +2,8 @@ import sys import threading import types from collections.abc import Callable -from typing import Any, Literal, TypeVar -from typing_extensions import ParamSpec, Self +from typing import Any, Literal, ParamSpec, TypeVar +from typing_extensions import Self if sys.version_info >= (3, 14): # needed to satisfy pyright checks for Python <= 3.13 from _interpreters import ( diff --git a/mypy/typeshed/stdlib/concurrent/interpreters/_crossinterp.pyi b/mypy/typeshed/stdlib/concurrent/interpreters/_crossinterp.pyi index 50fe7cf0b4ba4..c8e29aaafa18a 100644 --- a/mypy/typeshed/stdlib/concurrent/interpreters/_crossinterp.pyi +++ b/mypy/typeshed/stdlib/concurrent/interpreters/_crossinterp.pyi @@ -1,7 +1,7 @@ import sys from collections.abc import Callable -from typing import Final, NewType -from typing_extensions import Never, Self, TypeAlias +from typing import Final, NewType, TypeAlias +from typing_extensions import Never, Self if sys.version_info >= (3, 14): # needed to satisfy pyright checks for Python <= 3.13 from _interpqueues import _UnboundOp diff --git a/mypy/typeshed/stdlib/configparser.pyi b/mypy/typeshed/stdlib/configparser.pyi index 9b3f02324b7fd..385336ec154ab 100644 --- a/mypy/typeshed/stdlib/configparser.pyi +++ b/mypy/typeshed/stdlib/configparser.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import BytesPath, GenericPath, MaybeNone, StrOrBytesPath, StrPath, SupportsWrite from collections.abc import Callable, ItemsView, Iterable, Iterator, Mapping, MutableMapping, Sequence from re import Pattern -from typing import Any, AnyStr, ClassVar, Final, Literal, TypeVar, overload, type_check_only -from typing_extensions import TypeAlias, deprecated +from typing import Any, AnyStr, ClassVar, Final, Literal, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import deprecated if sys.version_info >= (3, 14): __all__ = ( @@ -269,6 +269,7 @@ class RawConfigParser(_Parser): def has_section(self, section: _SectionName) -> bool: ... def options(self, section: _SectionName) -> list[str]: ... def has_option(self, section: _SectionName, option: str) -> bool: ... + @overload def read(self, filenames: GenericPath[AnyStr], encoding: str | None = None) -> list[AnyStr]: ... @overload @@ -277,12 +278,14 @@ class RawConfigParser(_Parser): def read(self, filenames: Iterable[BytesPath], encoding: str | None = None) -> list[bytes]: ... @overload def read(self, filenames: Iterable[StrOrBytesPath], encoding: str | None = None) -> list[str | bytes]: ... + def read_file(self, f: Iterable[str], source: str | None = None) -> None: ... def read_string(self, string: str, source: str = "") -> None: ... def read_dict(self, dictionary: Mapping[str, Mapping[str, Any]], source: str = "") -> None: ... if sys.version_info < (3, 12): @deprecated("Deprecated since Python 3.2; removed in Python 3.12. Use `parser.read_file()` instead.") def readfp(self, fp: Iterable[str], filename: str | None = None) -> None: ... + # These get* methods are partially applied (with the same names) in # SectionProxy; the stubs should be kept updated together @overload @@ -291,18 +294,21 @@ class RawConfigParser(_Parser): def getint( self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T ) -> int | _T: ... + @overload def getfloat(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> float: ... @overload def getfloat( self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T ) -> float | _T: ... + @overload def getboolean(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> bool: ... @overload def getboolean( self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T ) -> bool | _T: ... + def _get_conv( self, section: _SectionName, @@ -313,6 +319,7 @@ class RawConfigParser(_Parser): vars: _Section | None = None, fallback: _T = ..., ) -> _T: ... + # This is incompatible with MutableMapping so we ignore the type @overload # type: ignore[override] def get(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> str | MaybeNone: ... @@ -320,10 +327,12 @@ class RawConfigParser(_Parser): def get( self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T ) -> str | _T | MaybeNone: ... + @overload def items(self, *, raw: bool = False, vars: _Section | None = None) -> ItemsView[str, SectionProxy]: ... @overload def items(self, section: _SectionName, raw: bool = False, vars: _Section | None = None) -> list[tuple[str, str]]: ... + def set(self, section: _SectionName, option: str, value: str | None = None) -> None: ... def write(self, fp: SupportsWrite[str], space_around_delimiters: bool = True) -> None: ... def remove_option(self, section: _SectionName, option: str) -> bool: ... @@ -357,6 +366,7 @@ class SectionProxy(MutableMapping[str, str]): def parser(self) -> RawConfigParser: ... @property def name(self) -> str: ... + # This is incompatible with MutableMapping so we ignore the type @overload # type: ignore[override] def get( @@ -380,20 +390,24 @@ class SectionProxy(MutableMapping[str, str]): _impl: Any | None = None, **kwargs: Any, # passed to the underlying parser's get() method ) -> str | _T: ... + # These are partially-applied version of the methods with the same names in # RawConfigParser; the stubs should be kept updated together @overload def getint(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> int | None: ... @overload def getint(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> int | _T: ... + @overload def getfloat(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> float | None: ... @overload def getfloat(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> float | _T: ... + @overload def getboolean(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> bool | None: ... @overload def getboolean(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> bool | _T: ... + # SectionProxy can have arbitrary attributes when custom converters are used def __getattr__(self, key: str) -> Callable[..., Any]: ... diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index 0670787a5db1b..73cdda3b8f342 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -4,10 +4,11 @@ from _typeshed import FileDescriptorOrPath, Unused from abc import ABC, abstractmethod from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Generator, Iterator from types import TracebackType -from typing import Any, Generic, Protocol, TypeVar, overload, runtime_checkable, type_check_only -from typing_extensions import ParamSpec, Self, TypeAlias +from typing import Any, Generic, ParamSpec, Protocol, TypeAlias, TypeVar, overload, runtime_checkable, type_check_only +from typing_extensions import Self __all__ = [ + "aclosing", "contextmanager", "closing", "AbstractContextManager", @@ -22,9 +23,6 @@ __all__ = [ "nullcontext", ] -if sys.version_info >= (3, 10): - __all__ += ["aclosing"] - if sys.version_info >= (3, 11): __all__ += ["chdir"] @@ -88,31 +86,23 @@ class _GeneratorContextManager( def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ... -if sys.version_info >= (3, 10): - _AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]]) - - class AsyncContextDecorator: - def _recreate_cm(self) -> Self: ... - def __call__(self, func: _AF) -> _AF: ... - - class _AsyncGeneratorContextManager( - _GeneratorContextManagerBase[AsyncGenerator[_T_co, _SendT_contra]], - AbstractAsyncContextManager[_T_co, bool | None], - AsyncContextDecorator, - ): - async def __aexit__( - self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None - ) -> bool | None: ... - -else: - class _AsyncGeneratorContextManager( - _GeneratorContextManagerBase[AsyncGenerator[_T_co, _SendT_contra]], AbstractAsyncContextManager[_T_co, bool | None] - ): - async def __aexit__( - self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None - ) -> bool | None: ... +_AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]]) + +class AsyncContextDecorator: + def _recreate_cm(self) -> Self: ... + def __call__(self, func: _AF) -> _AF: ... + +class _AsyncGeneratorContextManager( + _GeneratorContextManagerBase[AsyncGenerator[_T_co, _SendT_contra]], + AbstractAsyncContextManager[_T_co, bool | None], + AsyncContextDecorator, +): + async def __aexit__( + self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... def asynccontextmanager(func: Callable[_P, AsyncIterator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ... + @type_check_only class _SupportsClose(Protocol): def close(self) -> object: ... @@ -123,16 +113,15 @@ class closing(AbstractContextManager[_SupportsCloseT, None]): def __init__(self, thing: _SupportsCloseT) -> None: ... def __exit__(self, *exc_info: Unused) -> None: ... -if sys.version_info >= (3, 10): - @type_check_only - class _SupportsAclose(Protocol): - def aclose(self) -> Awaitable[object]: ... +@type_check_only +class _SupportsAclose(Protocol): + def aclose(self) -> Awaitable[object]: ... - _SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) +_SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) - class aclosing(AbstractAsyncContextManager[_SupportsAcloseT, None]): - def __init__(self, thing: _SupportsAcloseT) -> None: ... - async def __aexit__(self, *exc_info: Unused) -> None: ... +class aclosing(AbstractAsyncContextManager[_SupportsAcloseT, None]): + def __init__(self, thing: _SupportsAcloseT) -> None: ... + async def __aexit__(self, *exc_info: Unused) -> None: ... class suppress(AbstractContextManager[None, bool]): def __init__(self, *exceptions: type[BaseException]) -> None: ... @@ -199,27 +188,18 @@ class AsyncExitStack(_BaseExitStackAbstract[_ExitT_co]): self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, / ) -> _ExitT_co: ... -if sys.version_info >= (3, 10): - class nullcontext(AbstractContextManager[_T, None], AbstractAsyncContextManager[_T, None]): - enter_result: _T - @overload - def __init__(self: nullcontext[None]) -> None: ... - @overload - def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 - def __enter__(self) -> _T: ... - def __exit__(self, *exctype: Unused) -> None: ... - async def __aenter__(self) -> _T: ... - async def __aexit__(self, *exctype: Unused) -> None: ... - -else: - class nullcontext(AbstractContextManager[_T, None]): - enter_result: _T - @overload - def __init__(self: nullcontext[None]) -> None: ... - @overload - def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 - def __enter__(self) -> _T: ... - def __exit__(self, *exctype: Unused) -> None: ... +class nullcontext(AbstractContextManager[_T, None], AbstractAsyncContextManager[_T, None]): + enter_result: _T + + @overload + def __init__(self: nullcontext[None]) -> None: ... + @overload + def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 + + def __enter__(self) -> _T: ... + def __exit__(self, *exctype: Unused) -> None: ... + async def __aenter__(self) -> _T: ... + async def __aexit__(self, *exctype: Unused) -> None: ... if sys.version_info >= (3, 11): _T_fd_or_any_path = TypeVar("_T_fd_or_any_path", bound=FileDescriptorOrPath) diff --git a/mypy/typeshed/stdlib/copyreg.pyi b/mypy/typeshed/stdlib/copyreg.pyi index 8f7fd957fc526..3bfc0de8158f1 100644 --- a/mypy/typeshed/stdlib/copyreg.pyi +++ b/mypy/typeshed/stdlib/copyreg.pyi @@ -1,6 +1,5 @@ from collections.abc import Callable, Hashable -from typing import Any, SupportsInt, TypeVar -from typing_extensions import TypeAlias +from typing import Any, SupportsInt, TypeAlias, TypeVar _T = TypeVar("_T") _Reduce: TypeAlias = tuple[Callable[..., _T], tuple[Any, ...]] | tuple[Callable[..., _T], tuple[Any, ...], Any | None] diff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi index 4ed0ab1d83b82..f3b4286a6b495 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi @@ -19,11 +19,7 @@ from _csv import ( if sys.version_info >= (3, 12): from _csv import QUOTE_NOTNULL as QUOTE_NOTNULL, QUOTE_STRINGS as QUOTE_STRINGS -if sys.version_info >= (3, 10): - from _csv import Reader, Writer -else: - from _csv import _reader as Reader, _writer as Writer - +from _csv import Reader, Writer from _typeshed import SupportsWrite from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence from types import GenericAlias @@ -80,6 +76,7 @@ class DictReader(Iterator[dict[_T | Any, str | Any]], Generic[_T]): reader: Reader dialect: _DialectLike line_num: int + @overload def __init__( self, @@ -116,6 +113,7 @@ class DictReader(Iterator[dict[_T | Any, str | Any]], Generic[_T]): quoting: _QuotingType = 0, strict: bool = False, ) -> None: ... + def __iter__(self) -> Self: ... def __next__(self) -> dict[_T | Any, str | Any]: ... if sys.version_info >= (3, 12): diff --git a/mypy/typeshed/stdlib/ctypes/__init__.pyi b/mypy/typeshed/stdlib/ctypes/__init__.pyi index 8d048aa97e7d5..7eee1b760063f 100644 --- a/mypy/typeshed/stdlib/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/ctypes/__init__.pyi @@ -26,8 +26,8 @@ from _ctypes import ( from _typeshed import StrPath, SupportsBool, SupportsLen from ctypes._endian import BigEndianStructure as BigEndianStructure, LittleEndianStructure as LittleEndianStructure from types import GenericAlias -from typing import Any, ClassVar, Final, Generic, Literal, TypeVar, overload, type_check_only -from typing_extensions import Self, TypeAlias, deprecated +from typing import Any, ClassVar, Final, Generic, Literal, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, deprecated if sys.platform == "win32": from _ctypes import FormatError as FormatError, get_last_error as get_last_error, set_last_error as set_last_error @@ -50,6 +50,7 @@ if sys.version_info >= (3, 14): def POINTER(cls: None) -> type[c_void_p]: ... @overload def POINTER(cls: type[_CT]) -> type[_Pointer[_CT]]: ... + def pointer(obj: _CT) -> _Pointer[_CT]: ... else: @@ -166,15 +167,12 @@ c_buffer = create_string_buffer def create_unicode_buffer(init: int | str, size: int | None = None) -> Array[c_wchar]: ... -if sys.version_info >= (3, 13): +if sys.version_info < (3, 15): @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") def SetPointerType(pointer: type[_Pointer[Any]], cls: _CTypeBaseType) -> None: ... - @deprecated("Soft deprecated since Python 3.13. Use multiplication instead.") - def ARRAY(typ: _CT, len: int) -> Array[_CT]: ... -else: - def SetPointerType(pointer: type[_Pointer[Any]], cls: _CTypeBaseType) -> None: ... - def ARRAY(typ: _CT, len: int) -> Array[_CT]: ... +@deprecated("Soft deprecated since Python 3.13. Use multiplication instead.") +def ARRAY(typ: _CT, len: int) -> Array[_CT]: ... if sys.platform == "win32": def DllCanUnloadNow() -> int: ... @@ -221,86 +219,146 @@ class py_object(_CanCastTo, _SimpleCData[_T]): class c_bool(_SimpleCData[bool]): _type_: ClassVar[Literal["?"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] def __init__(self, value: SupportsBool | SupportsLen | None = ...) -> None: ... class c_byte(_SimpleCData[int]): _type_: ClassVar[Literal["b"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_ubyte(_SimpleCData[int]): _type_: ClassVar[Literal["B"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_short(_SimpleCData[int]): _type_: ClassVar[Literal["h"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_ushort(_SimpleCData[int]): _type_: ClassVar[Literal["H"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_long(_SimpleCData[int]): _type_: ClassVar[Literal["l"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_ulong(_SimpleCData[int]): _type_: ClassVar[Literal["L"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_int(_SimpleCData[int]): # can be an alias for c_long _type_: ClassVar[Literal["i", "l"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_uint(_SimpleCData[int]): # can be an alias for c_ulong _type_: ClassVar[Literal["I", "L"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_longlong(_SimpleCData[int]): # can be an alias for c_long _type_: ClassVar[Literal["q", "l"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_ulonglong(_SimpleCData[int]): # can be an alias for c_ulong _type_: ClassVar[Literal["Q", "L"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] c_int8 = c_byte c_uint8 = c_ubyte class c_int16(_SimpleCData[int]): # can be an alias for c_short or c_int _type_: ClassVar[Literal["h", "i"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_uint16(_SimpleCData[int]): # can be an alias for c_ushort or c_uint _type_: ClassVar[Literal["H", "I"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_int32(_SimpleCData[int]): # can be an alias for c_int or c_long _type_: ClassVar[Literal["i", "l"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_uint32(_SimpleCData[int]): # can be an alias for c_uint or c_ulong _type_: ClassVar[Literal["I", "L"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_int64(_SimpleCData[int]): # can be an alias for c_long or c_longlong _type_: ClassVar[Literal["l", "q"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_uint64(_SimpleCData[int]): # can be an alias for c_ulong or c_ulonglong _type_: ClassVar[Literal["L", "Q"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_ssize_t(_SimpleCData[int]): # alias for c_int, c_long, or c_longlong _type_: ClassVar[Literal["i", "l", "q"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_size_t(_SimpleCData[int]): # alias for c_uint, c_ulong, or c_ulonglong _type_: ClassVar[Literal["I", "L", "Q"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_float(_SimpleCData[float]): _type_: ClassVar[Literal["f"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_double(_SimpleCData[float]): _type_: ClassVar[Literal["d"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_longdouble(_SimpleCData[float]): # can be an alias for c_double _type_: ClassVar[Literal["d", "g"]] if sys.version_info >= (3, 14) and sys.platform != "win32": + # NOTE: currently (3.14.4) the `__ctype_{be,le}__` attributes of these complex types are missing at runtime: + # https://github.com/python/cpython/issues/148464 + class c_double_complex(_SimpleCData[complex]): - _type_: ClassVar[Literal["D"]] + if sys.version_info >= (3, 15): + _type_: ClassVar[Literal["Zd"]] + else: + _type_: ClassVar[Literal["D"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_float_complex(_SimpleCData[complex]): - _type_: ClassVar[Literal["F"]] + if sys.version_info >= (3, 15): + _type_: ClassVar[Literal["Zf"]] + else: + _type_: ClassVar[Literal["F"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] class c_longdouble_complex(_SimpleCData[complex]): - _type_: ClassVar[Literal["G"]] + if sys.version_info >= (3, 15): + _type_: ClassVar[Literal["Zg"]] + else: + _type_: ClassVar[Literal["G"]] class c_char(_SimpleCData[bytes]): _type_: ClassVar[Literal["c"]] + __ctype_be__: ClassVar[type[Self]] + __ctype_le__: ClassVar[type[Self]] def __init__(self, value: int | bytes | bytearray = ...) -> None: ... class c_char_p(_PointerLike, _SimpleCData[bytes | None]): diff --git a/mypy/typeshed/stdlib/ctypes/wintypes.pyi b/mypy/typeshed/stdlib/ctypes/wintypes.pyi index 0f0d61a396d5f..b94c5e74148a2 100644 --- a/mypy/typeshed/stdlib/ctypes/wintypes.pyi +++ b/mypy/typeshed/stdlib/ctypes/wintypes.pyi @@ -21,8 +21,8 @@ from ctypes import ( c_wchar, c_wchar_p, ) -from typing import Any, Final, TypeVar -from typing_extensions import Self, TypeAlias +from typing import Any, Final, TypeAlias, TypeVar +from typing_extensions import Self if sys.version_info >= (3, 12): from ctypes import c_ubyte diff --git a/mypy/typeshed/stdlib/curses/__init__.pyi b/mypy/typeshed/stdlib/curses/__init__.pyi index 3e32487ad99f2..cf50481108786 100644 --- a/mypy/typeshed/stdlib/curses/__init__.pyi +++ b/mypy/typeshed/stdlib/curses/__init__.pyi @@ -1,10 +1,8 @@ -import sys from _curses import * from _curses import window as window from _typeshed import structseq from collections.abc import Callable -from typing import Final, TypeVar, final, type_check_only -from typing_extensions import Concatenate, ParamSpec +from typing import Concatenate, Final, ParamSpec, TypeVar, final, type_check_only # NOTE: The _curses module is ordinarily only available on Unix, but the # windows-curses package makes it available on Windows as well with the same @@ -30,8 +28,7 @@ def wrapper(func: Callable[Concatenate[window, _P], _T], /, *arg: _P.args, **kwd @final @type_check_only class _ncurses_version(structseq[int], tuple[int, int, int]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("major", "minor", "patch") + __match_args__: Final = ("major", "minor", "patch") @property def major(self) -> int: ... diff --git a/mypy/typeshed/stdlib/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index 3a1c8cb5d62dd..1a7b8fd645589 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -17,6 +17,7 @@ __all__ = [ "Field", "FrozenInstanceError", "InitVar", + "KW_ONLY", "MISSING", "fields", "asdict", @@ -26,9 +27,6 @@ __all__ = [ "is_dataclass", ] -if sys.version_info >= (3, 10): - __all__ += ["KW_ONLY"] - _DataclassT = TypeVar("_DataclassT", bound=DataclassInstance) @type_check_only @@ -60,13 +58,13 @@ class _MISSING_TYPE(enum.Enum): MISSING: Final = _MISSING_TYPE.MISSING -if sys.version_info >= (3, 10): - class KW_ONLY: ... +class KW_ONLY: ... @overload def asdict(obj: DataclassInstance) -> dict[str, Any]: ... @overload def asdict(obj: DataclassInstance, *, dict_factory: Callable[[list[tuple[str, Any]]], _T]) -> _T: ... + @overload def astuple(obj: DataclassInstance) -> tuple[Any, ...]: ... @overload @@ -105,8 +103,7 @@ if sys.version_info >= (3, 11): slots: bool = False, weakref_slot: bool = False, ) -> Callable[[type[_T]], type[_T]]: ... - -elif sys.version_info >= (3, 10): +else: @overload def dataclass( cls: type[_T], @@ -138,32 +135,6 @@ elif sys.version_info >= (3, 10): slots: bool = False, ) -> Callable[[type[_T]], type[_T]]: ... -else: - @overload - def dataclass( - cls: type[_T], - /, - *, - init: bool = True, - repr: bool = True, - eq: bool = True, - order: bool = False, - unsafe_hash: bool = False, - frozen: bool = False, - ) -> type[_T]: ... - @overload - def dataclass( - cls: None = None, - /, - *, - init: bool = True, - repr: bool = True, - eq: bool = True, - order: bool = False, - unsafe_hash: bool = False, - frozen: bool = False, - ) -> Callable[[type[_T]], type[_T]]: ... - # See https://github.com/python/mypy/issues/10750 @type_check_only class _DefaultFactory(Protocol[_T_co]): @@ -185,7 +156,7 @@ class Field(Generic[_T]): "doc", "_field_type", ) - elif sys.version_info >= (3, 10): + else: __slots__ = ( "name", "type", @@ -199,8 +170,6 @@ class Field(Generic[_T]): "kw_only", "_field_type", ) - else: - __slots__ = ("name", "type", "default", "default_factory", "repr", "hash", "init", "compare", "metadata", "_field_type") name: str type: Type[_T] | str | Any default: _T | Literal[_MISSING_TYPE.MISSING] @@ -214,8 +183,7 @@ class Field(Generic[_T]): if sys.version_info >= (3, 14): doc: str | None - if sys.version_info >= (3, 10): - kw_only: bool | Literal[_MISSING_TYPE.MISSING] + kw_only: bool | Literal[_MISSING_TYPE.MISSING] if sys.version_info >= (3, 14): def __init__( @@ -230,18 +198,6 @@ class Field(Generic[_T]): kw_only: bool, doc: str | None, ) -> None: ... - elif sys.version_info >= (3, 10): - def __init__( - self, - default: _T, - default_factory: Callable[[], _T], - init: bool, - repr: bool, - hash: bool | None, - compare: bool, - metadata: Mapping[Any, Any], - kw_only: bool, - ) -> None: ... else: def __init__( self, @@ -252,6 +208,7 @@ class Field(Generic[_T]): hash: bool | None, compare: bool, metadata: Mapping[Any, Any], + kw_only: bool, ) -> None: ... def __set_name__(self, owner: Type[Any], name: str) -> None: ... @@ -299,8 +256,7 @@ if sys.version_info >= (3, 14): kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., doc: str | None = None, ) -> Any: ... - -elif sys.version_info >= (3, 10): +else: @overload # `default` and `default_factory` are optional and mutually exclusive. def field( *, @@ -338,41 +294,6 @@ elif sys.version_info >= (3, 10): kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ..., ) -> Any: ... -else: - @overload # `default` and `default_factory` are optional and mutually exclusive. - def field( - *, - default: _T, - default_factory: Literal[_MISSING_TYPE.MISSING] = ..., - init: bool = True, - repr: bool = True, - hash: bool | None = None, - compare: bool = True, - metadata: Mapping[Any, Any] | None = None, - ) -> _T: ... - @overload - def field( - *, - default: Literal[_MISSING_TYPE.MISSING] = ..., - default_factory: Callable[[], _T], - init: bool = True, - repr: bool = True, - hash: bool | None = None, - compare: bool = True, - metadata: Mapping[Any, Any] | None = None, - ) -> _T: ... - @overload - def field( - *, - default: Literal[_MISSING_TYPE.MISSING] = ..., - default_factory: Literal[_MISSING_TYPE.MISSING] = ..., - init: bool = True, - repr: bool = True, - hash: bool | None = None, - compare: bool = True, - metadata: Mapping[Any, Any] | None = None, - ) -> Any: ... - def fields(class_or_instance: DataclassInstance | type[DataclassInstance]) -> tuple[Field[Any], ...]: ... # HACK: `obj: Never` typing matches if object argument is using `Any` type. @@ -389,6 +310,7 @@ class InitVar(Generic[_T]): __slots__ = ("type",) type: Type[_T] def __init__(self, type: Type[_T]) -> None: ... + @overload def __class_getitem__(cls, type: Type[_T]) -> InitVar[_T]: ... # pyright: ignore[reportInvalidTypeForm] @overload @@ -454,7 +376,7 @@ elif sys.version_info >= (3, 11): weakref_slot: bool = False, ) -> type: ... -elif sys.version_info >= (3, 10): +else: def make_dataclass( cls_name: str, fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]], @@ -472,19 +394,4 @@ elif sys.version_info >= (3, 10): slots: bool = False, ) -> type: ... -else: - def make_dataclass( - cls_name: str, - fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]], - *, - bases: tuple[type, ...] = (), - namespace: dict[str, Any] | None = None, - init: bool = True, - repr: bool = True, - eq: bool = True, - order: bool = False, - unsafe_hash: bool = False, - frozen: bool = False, - ) -> type: ... - def replace(obj: _DataclassT, /, **changes: Any) -> _DataclassT: ... diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index 8a0536c006d57..95c62a9c1b712 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -1,8 +1,8 @@ import sys from abc import abstractmethod from time import struct_time -from typing import ClassVar, Final, NoReturn, SupportsIndex, final, overload, type_check_only -from typing_extensions import CapsuleType, Self, TypeAlias, deprecated, disjoint_base +from typing import ClassVar, Final, NoReturn, SupportsIndex, TypeAlias, final, overload, type_check_only +from typing_extensions import CapsuleType, Self, deprecated, disjoint_base if sys.version_info >= (3, 11): __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR", "UTC") @@ -63,8 +63,14 @@ class date: def today(cls) -> Self: ... @classmethod def fromordinal(cls, n: int, /) -> Self: ... - @classmethod - def fromisoformat(cls, date_string: str, /) -> Self: ... + + if sys.version_info >= (3, 15): + @classmethod + def fromisoformat(cls, string: str, /) -> Self: ... + else: + @classmethod + def fromisoformat(cls, date_string: str, /) -> Self: ... + @classmethod def fromisocalendar(cls, year: int, week: int, day: int) -> Self: ... @property @@ -76,8 +82,12 @@ class date: def ctime(self) -> str: ... if sys.version_info >= (3, 14): - @classmethod - def strptime(cls, date_string: str, format: str, /) -> Self: ... + if sys.version_info >= (3, 15): + @classmethod + def strptime(cls, string: str, format: str, /) -> Self: ... + else: + @classmethod + def strptime(cls, date_string: str, format: str, /) -> Self: ... # On <3.12, the name of the parameter in the pure-Python implementation # didn't match the name in the C implementation, @@ -102,12 +112,14 @@ class date: def __eq__(self, value: object, /) -> bool: ... def __add__(self, value: timedelta, /) -> Self: ... def __radd__(self, value: timedelta, /) -> Self: ... + @overload def __sub__(self, value: datetime, /) -> NoReturn: ... @overload def __sub__(self, value: Self, /) -> timedelta: ... @overload def __sub__(self, value: timedelta, /) -> Self: ... + def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... @@ -147,12 +159,21 @@ class time: def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... def isoformat(self, timespec: str = "auto") -> str: ... - @classmethod - def fromisoformat(cls, time_string: str, /) -> Self: ... - if sys.version_info >= (3, 14): + if sys.version_info >= (3, 15): @classmethod - def strptime(cls, date_string: str, format: str, /) -> Self: ... + def fromisoformat(cls, string: str, /) -> Self: ... + else: + @classmethod + def fromisoformat(cls, time_string: str, /) -> Self: ... + + if sys.version_info >= (3, 14): + if sys.version_info >= (3, 15): + @classmethod + def strptime(cls, string: str, format: str, /) -> Self: ... + else: + @classmethod + def strptime(cls, date_string: str, format: str, /) -> Self: ... # On <3.12, the name of the parameter in the pure-Python implementation # didn't match the name in the C implementation, @@ -224,14 +245,17 @@ class timedelta: def __abs__(self) -> timedelta: ... def __mul__(self, value: float, /) -> timedelta: ... def __rmul__(self, value: float, /) -> timedelta: ... + @overload def __floordiv__(self, value: timedelta, /) -> int: ... @overload def __floordiv__(self, value: int, /) -> timedelta: ... + @overload def __truediv__(self, value: timedelta, /) -> float: ... @overload def __truediv__(self, value: float, /) -> timedelta: ... + def __mod__(self, value: timedelta, /) -> timedelta: ... def __divmod__(self, value: timedelta, /) -> tuple[int, timedelta]: ... def __le__(self, value: timedelta, /) -> bool: ... @@ -291,6 +315,10 @@ class datetime(date): def utcnow(cls) -> Self: ... @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 timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... def date(self) -> _Date: ... @@ -327,8 +355,14 @@ class datetime(date): ) -> Self: ... def astimezone(self, tz: _TzInfo | None = None) -> Self: ... def isoformat(self, sep: str = "T", timespec: str = "auto") -> str: ... - @classmethod - def strptime(cls, date_string: str, format: str, /) -> Self: ... + + if sys.version_info >= (3, 15): + @classmethod + def strptime(cls, string: str, format: str, /) -> Self: ... + else: + @classmethod + def strptime(cls, date_string: str, format: str, /) -> Self: ... + def utcoffset(self) -> timedelta | None: ... def tzname(self) -> str | None: ... def dst(self) -> timedelta | None: ... @@ -338,6 +372,7 @@ class datetime(date): 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__(self, value: Self, /) -> timedelta: ... @overload diff --git a/mypy/typeshed/stdlib/dbm/__init__.pyi b/mypy/typeshed/stdlib/dbm/__init__.pyi index 7cbb63cf2f06e..0871381e8ec0f 100644 --- a/mypy/typeshed/stdlib/dbm/__init__.pyi +++ b/mypy/typeshed/stdlib/dbm/__init__.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import StrOrBytesPath from collections.abc import Iterator, MutableMapping from types import TracebackType -from typing import Literal, type_check_only -from typing_extensions import Self, TypeAlias +from typing import Literal, TypeAlias, type_check_only +from typing_extensions import Self __all__ = ["open", "whichdb", "error"] diff --git a/mypy/typeshed/stdlib/dbm/dumb.pyi b/mypy/typeshed/stdlib/dbm/dumb.pyi index 1c0b7756f2925..d5a769e6a1c25 100644 --- a/mypy/typeshed/stdlib/dbm/dumb.pyi +++ b/mypy/typeshed/stdlib/dbm/dumb.pyi @@ -2,7 +2,8 @@ import sys from _typeshed import StrOrBytesPath from collections.abc import Iterator, MutableMapping from types import TracebackType -from typing_extensions import Self, TypeAlias +from typing import TypeAlias +from typing_extensions import Self __all__ = ["error", "open"] @@ -17,6 +18,9 @@ error = OSError class _Database(MutableMapping[_KeyType, bytes]): def __init__(self, filebasename: str, mode: str, flag: str = "c") -> None: ... def sync(self) -> None: ... + if sys.version_info >= (3, 15): + def reorganize(self) -> None: ... + def iterkeys(self) -> Iterator[bytes]: ... # undocumented def close(self) -> None: ... def __getitem__(self, key: _KeyType) -> bytes: ... diff --git a/mypy/typeshed/stdlib/dbm/sqlite3.pyi b/mypy/typeshed/stdlib/dbm/sqlite3.pyi index e2fba93b20017..e7034cfde50d1 100644 --- a/mypy/typeshed/stdlib/dbm/sqlite3.pyi +++ b/mypy/typeshed/stdlib/dbm/sqlite3.pyi @@ -1,7 +1,8 @@ +import sys from _typeshed import ReadableBuffer, StrOrBytesPath, Unused from collections.abc import Generator, MutableMapping -from typing import Final, Literal -from typing_extensions import LiteralString, Self, TypeAlias +from typing import Final, Literal, TypeAlias +from typing_extensions import LiteralString, Self BUILD_TABLE: Final[LiteralString] GET_SIZE: Final[LiteralString] @@ -9,6 +10,8 @@ LOOKUP_KEY: Final[LiteralString] STORE_KV: Final[LiteralString] DELETE_KEY: Final[LiteralString] ITER_KEYS: Final[LiteralString] +if sys.version_info >= (3, 15): + REORGANIZE: Final[LiteralString] _SqliteData: TypeAlias = str | ReadableBuffer | int | float @@ -25,5 +28,7 @@ class _Database(MutableMapping[bytes, bytes]): def keys(self) -> list[bytes]: ... # type: ignore[override] def __enter__(self) -> Self: ... def __exit__(self, *args: Unused) -> None: ... + if sys.version_info >= (3, 15): + def reorganize(self) -> None: ... def open(filename: StrOrBytesPath, /, flag: Literal["r", "w", "c", "n"] = "r", mode: int = 0o666) -> _Database: ... diff --git a/mypy/typeshed/stdlib/decimal.pyi b/mypy/typeshed/stdlib/decimal.pyi index 2e06c2d1b724a..f16fa8aaae31f 100644 --- a/mypy/typeshed/stdlib/decimal.pyi +++ b/mypy/typeshed/stdlib/decimal.pyi @@ -26,11 +26,13 @@ from _decimal import ( ) from collections.abc import Container, Sequence from types import TracebackType -from typing import Any, ClassVar, Literal, NamedTuple, final, overload, type_check_only -from typing_extensions import Self, TypeAlias, disjoint_base +from typing import Any, ClassVar, Literal, NamedTuple, TypeAlias, final, overload, type_check_only +from typing_extensions import Self, disjoint_base if sys.version_info >= (3, 14): from _decimal import IEEE_CONTEXT_MAX_BITS as IEEE_CONTEXT_MAX_BITS, IEEEContext as IEEEContext +if sys.version_info >= (3, 15): + from _decimal import SPEC_VERSION as SPEC_VERSION _Decimal: TypeAlias = Decimal | int _DecimalNew: TypeAlias = Decimal | float | str | tuple[int, Sequence[int], int] @@ -116,10 +118,12 @@ class Decimal: def imag(self) -> Decimal: ... def conjugate(self) -> Decimal: ... def __complex__(self) -> complex: ... + @overload def __round__(self) -> int: ... @overload def __round__(self, ndigits: int, /) -> Decimal: ... + def __floor__(self) -> int: ... def __ceil__(self) -> int: ... def fma(self, other: _Decimal, third: _Decimal, context: Context | None = None) -> Decimal: ... diff --git a/mypy/typeshed/stdlib/difflib.pyi b/mypy/typeshed/stdlib/difflib.pyi index 6efe68322bb65..a3bda7f9b2d0c 100644 --- a/mypy/typeshed/stdlib/difflib.pyi +++ b/mypy/typeshed/stdlib/difflib.pyi @@ -39,6 +39,7 @@ class SequenceMatcher(Generic[_T]): b: Sequence[str] = "", autojunk: bool = True, ) -> None: ... + def set_seqs(self, a: Sequence[_T], b: Sequence[_T]) -> None: ... def set_seq1(self, a: Sequence[_T]) -> None: ... def set_seq2(self, b: Sequence[_T]) -> None: ... @@ -69,16 +70,33 @@ else: def IS_LINE_JUNK(line: str, pat: Callable[[str], re.Match[str] | None] = ...) -> bool: ... def IS_CHARACTER_JUNK(ch: str, ws: str = " \t") -> bool: ... # ws is undocumented -def unified_diff( - a: Sequence[str], - b: Sequence[str], - fromfile: str = "", - tofile: str = "", - fromfiledate: str = "", - tofiledate: str = "", - n: int = 3, - lineterm: str = "\n", -) -> Iterator[str]: ... + +if sys.version_info >= (3, 15): + def unified_diff( + a: Sequence[str], + b: Sequence[str], + fromfile: str = "", + tofile: str = "", + fromfiledate: str = "", + tofiledate: str = "", + n: int = 3, + lineterm: str = "\n", + *, + color: bool = False, + ) -> Iterator[str]: ... + +else: + def unified_diff( + a: Sequence[str], + b: Sequence[str], + fromfile: str = "", + tofile: str = "", + fromfiledate: str = "", + tofiledate: str = "", + n: int = 3, + lineterm: str = "\n", + ) -> Iterator[str]: ... + def context_diff( a: Sequence[str], b: Sequence[str], diff --git a/mypy/typeshed/stdlib/dis.pyi b/mypy/typeshed/stdlib/dis.pyi index 52794a588ca83..0ad928934671b 100644 --- a/mypy/typeshed/stdlib/dis.pyi +++ b/mypy/typeshed/stdlib/dis.pyi @@ -3,7 +3,7 @@ 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_extensions import Self, TypeAlias, deprecated, disjoint_base +from typing_extensions import Self, deprecated, disjoint_base __all__ = [ "code_info", @@ -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/distutils/archive_util.pyi b/mypy/typeshed/stdlib/distutils/archive_util.pyi index 16684ff069568..5de23bad6bdb3 100644 --- a/mypy/typeshed/stdlib/distutils/archive_util.pyi +++ b/mypy/typeshed/stdlib/distutils/archive_util.pyi @@ -23,6 +23,7 @@ def make_archive( owner: str | None = None, group: str | None = None, ) -> str: ... + def make_tarball( base_name: str, base_dir: StrPath, diff --git a/mypy/typeshed/stdlib/distutils/ccompiler.pyi b/mypy/typeshed/stdlib/distutils/ccompiler.pyi index 5bff209807eef..83bbada6c4c48 100644 --- a/mypy/typeshed/stdlib/distutils/ccompiler.pyi +++ b/mypy/typeshed/stdlib/distutils/ccompiler.pyi @@ -1,8 +1,8 @@ from _typeshed import BytesPath, StrPath, Unused from collections.abc import Callable, Iterable, Sequence from distutils.file_util import _BytesPathT, _StrPathT -from typing import Literal, overload -from typing_extensions import TypeAlias, TypeVarTuple, Unpack +from typing import Literal, TypeAlias, overload +from typing_extensions import TypeVarTuple, Unpack _Macro: TypeAlias = tuple[str] | tuple[str, str | None] _Ts = TypeVarTuple("_Ts") @@ -148,29 +148,35 @@ class CCompiler: extra_preargs: list[str] | None = None, extra_postargs: list[str] | None = None, ) -> None: ... + @overload def executable_filename(self, basename: str, strip_dir: Literal[0, False] = 0, output_dir: StrPath = "") -> str: ... @overload def executable_filename(self, basename: StrPath, strip_dir: Literal[1, True], output_dir: StrPath = "") -> str: ... + def library_filename( self, libname: str, lib_type: str = "static", strip_dir: bool | Literal[0, 1] = 0, output_dir: StrPath = "" ) -> str: ... def object_filenames( self, source_filenames: Iterable[StrPath], strip_dir: bool | Literal[0, 1] = 0, output_dir: StrPath | None = "" ) -> list[str]: ... + @overload def shared_object_filename(self, basename: str, strip_dir: Literal[0, False] = 0, output_dir: StrPath = "") -> str: ... @overload def shared_object_filename(self, basename: StrPath, strip_dir: Literal[1, True], output_dir: StrPath = "") -> str: ... + def execute( self, func: Callable[[Unpack[_Ts]], Unused], args: tuple[Unpack[_Ts]], msg: str | None = None, level: int = 1 ) -> None: ... def spawn(self, cmd: Iterable[str]) -> None: ... def mkpath(self, name: str, mode: int = 0o777) -> None: ... + @overload def move_file(self, src: StrPath, dst: _StrPathT) -> _StrPathT | str: ... @overload def move_file(self, src: BytesPath, dst: _BytesPathT) -> _BytesPathT | bytes: ... + def announce(self, msg: str, level: int = 1) -> None: ... def warn(self, msg: str) -> None: ... def debug_print(self, msg: str) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/cmd.pyi b/mypy/typeshed/stdlib/distutils/cmd.pyi index 7f97bc3a2c9e0..35b991aba0883 100644 --- a/mypy/typeshed/stdlib/distutils/cmd.pyi +++ b/mypy/typeshed/stdlib/distutils/cmd.pyi @@ -49,6 +49,7 @@ class Command: def ensure_dirname(self, option: str) -> None: ... def get_command_name(self) -> str: ... def set_undefined_options(self, src_cmd: str, *option_pairs: tuple[str, str]) -> None: ... + # NOTE: This list comes directly from the distutils/command folder. Minus bdist_msi and bdist_wininst. @overload def get_finalized_command(self, command: Literal["bdist"], create: bool | Literal[0, 1] = 1) -> bdist: ... @@ -94,6 +95,7 @@ class Command: def get_finalized_command(self, command: Literal["upload"], create: bool | Literal[0, 1] = 1) -> upload: ... @overload def get_finalized_command(self, command: str, create: bool | Literal[0, 1] = 1) -> Command: ... + @overload def reinitialize_command(self, command: Literal["bdist"], reinit_subcommands: bool | Literal[0, 1] = 0) -> bdist: ... @overload @@ -154,6 +156,7 @@ class Command: def reinitialize_command(self, command: str, reinit_subcommands: bool | Literal[0, 1] = 0) -> Command: ... @overload def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool | Literal[0, 1] = 0) -> _CommandT: ... + def run_command(self, command: str) -> None: ... def get_sub_commands(self) -> list[str]: ... def warn(self, msg: str) -> None: ... @@ -161,6 +164,7 @@ class Command: self, func: Callable[[Unpack[_Ts]], Unused], args: tuple[Unpack[_Ts]], msg: str | None = None, level: int = 1 ) -> None: ... def mkpath(self, name: str, mode: int = 0o777) -> None: ... + @overload def copy_file( self, @@ -181,6 +185,7 @@ class Command: link: str | None = None, level: Unused = 1, ) -> tuple[_BytesPathT | bytes, bool]: ... + def copy_tree( self, infile: StrPath, @@ -190,11 +195,14 @@ class Command: preserve_symlinks: bool | Literal[0, 1] = 0, level: Unused = 1, ) -> list[str]: ... + @overload def move_file(self, src: StrPath, dst: _StrPathT, level: Unused = 1) -> _StrPathT | str: ... @overload def move_file(self, src: BytesPath, dst: _BytesPathT, level: Unused = 1) -> _BytesPathT | bytes: ... + def spawn(self, cmd: Iterable[str], search_path: bool | Literal[0, 1] = 1, level: Unused = 1) -> None: ... + @overload def make_archive( self, @@ -215,6 +223,7 @@ class Command: owner: str | None = None, group: str | None = None, ) -> str: ... + def make_file( self, infiles: str | list[str] | tuple[str, ...], diff --git a/mypy/typeshed/stdlib/distutils/command/__init__.pyi b/mypy/typeshed/stdlib/distutils/command/__init__.pyi index 4d7372858af34..856c5eb8b44ad 100644 --- a/mypy/typeshed/stdlib/distutils/command/__init__.pyi +++ b/mypy/typeshed/stdlib/distutils/command/__init__.pyi @@ -1,5 +1,3 @@ -import sys - from . import ( bdist, bdist_dumb, @@ -41,8 +39,3 @@ __all__ = [ "check", "upload", ] - -if sys.version_info < (3, 10): - from . import bdist_wininst - - __all__ += ["bdist_wininst"] diff --git a/mypy/typeshed/stdlib/distutils/command/bdist_wininst.pyi b/mypy/typeshed/stdlib/distutils/command/bdist_wininst.pyi deleted file mode 100644 index cf333bc5400dd..0000000000000 --- a/mypy/typeshed/stdlib/distutils/command/bdist_wininst.pyi +++ /dev/null @@ -1,16 +0,0 @@ -from _typeshed import StrOrBytesPath -from distutils.cmd import Command -from typing import ClassVar - -class bdist_wininst(Command): - description: ClassVar[str] - user_options: ClassVar[list[tuple[str, str | None, str]]] - boolean_options: ClassVar[list[str]] - - def initialize_options(self) -> None: ... - def finalize_options(self) -> None: ... - def run(self) -> None: ... - def get_inidata(self) -> str: ... - def create_exe(self, arcname: StrOrBytesPath, fullname: str, bitmap: StrOrBytesPath | None = None) -> None: ... - def get_installer_filename(self, fullname: str) -> str: ... - def get_exe_bytes(self) -> bytes: ... diff --git a/mypy/typeshed/stdlib/distutils/command/check.pyi b/mypy/typeshed/stdlib/distutils/command/check.pyi index 2c807fd2c4396..f2034e6555fcc 100644 --- a/mypy/typeshed/stdlib/distutils/command/check.pyi +++ b/mypy/typeshed/stdlib/distutils/command/check.pyi @@ -1,6 +1,5 @@ from _typeshed import Incomplete -from typing import Any, ClassVar, Final, Literal -from typing_extensions import TypeAlias +from typing import Any, ClassVar, Final, Literal, TypeAlias from ..cmd import Command diff --git a/mypy/typeshed/stdlib/distutils/command/install.pyi b/mypy/typeshed/stdlib/distutils/command/install.pyi index 1714e01a2c284..7e11cf257c2c3 100644 --- a/mypy/typeshed/stdlib/distutils/command/install.pyi +++ b/mypy/typeshed/stdlib/distutils/command/install.pyi @@ -1,4 +1,3 @@ -import sys from _typeshed import Incomplete from collections.abc import Callable from typing import Any, ClassVar, Final, Literal @@ -10,9 +9,6 @@ HAS_USER_SITE: Final[bool] SCHEME_KEYS: Final[tuple[Literal["purelib"], Literal["platlib"], Literal["headers"], Literal["scripts"], Literal["data"]]] INSTALL_SCHEMES: Final[dict[str, dict[str, str]]] -if sys.version_info < (3, 10): - WINDOWS_SCHEME: Final[dict[str, str]] - class install(Command): description: str user_options: ClassVar[list[tuple[str, str | None, str]]] diff --git a/mypy/typeshed/stdlib/distutils/dist.pyi b/mypy/typeshed/stdlib/distutils/dist.pyi index 412b94131b54e..58650e853cce6 100644 --- a/mypy/typeshed/stdlib/distutils/dist.pyi +++ b/mypy/typeshed/stdlib/distutils/dist.pyi @@ -22,8 +22,7 @@ from distutils.command.register import register from distutils.command.sdist import sdist from distutils.command.upload import upload from re import Pattern -from typing import IO, ClassVar, Literal, TypeVar, overload -from typing_extensions import TypeAlias +from typing import IO, ClassVar, Literal, TypeAlias, TypeVar, overload command_re: Pattern[str] @@ -122,6 +121,7 @@ class Distribution: def print_commands(self) -> None: ... def get_command_list(self): ... def get_command_packages(self): ... + # NOTE: This list comes directly from the distutils/command folder. Minus bdist_msi and bdist_wininst. @overload def get_command_obj(self, command: Literal["bdist"], create: Literal[1, True] = 1) -> bdist: ... @@ -168,6 +168,7 @@ class Distribution: # Not replicating the overloads for "Command | None", user may use "isinstance" @overload def get_command_obj(self, command: str, create: Literal[0, False]) -> Command | None: ... + @overload def get_command_class(self, command: Literal["bdist"]) -> type[bdist]: ... @overload @@ -210,6 +211,7 @@ class Distribution: def get_command_class(self, command: Literal["upload"]) -> type[upload]: ... @overload def get_command_class(self, command: str) -> type[Command]: ... + @overload def reinitialize_command(self, command: Literal["bdist"], reinit_subcommands: bool = False) -> bdist: ... @overload @@ -256,6 +258,7 @@ class Distribution: def reinitialize_command(self, command: str, reinit_subcommands: bool = False) -> Command: ... @overload def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool = False) -> _CommandT: ... + def announce(self, msg, level: int = 2) -> None: ... def run_commands(self) -> None: ... def run_command(self, command: str) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi index f3fa2a1255a6d..676ce1bea313e 100644 --- a/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi +++ b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi @@ -1,8 +1,7 @@ from collections.abc import Iterable, Mapping from getopt import _SliceableT, _StrSequenceT_co from re import Pattern -from typing import Any, Final, overload -from typing_extensions import TypeAlias +from typing import Any, Final, TypeAlias, overload _Option: TypeAlias = tuple[str, str | None, str] @@ -13,6 +12,7 @@ longopt_xlate: Final[dict[int, int]] class FancyGetopt: def __init__(self, option_table: list[_Option] | None = None) -> None: ... + # TODO: kinda wrong, `getopt(object=object())` is invalid @overload def getopt( @@ -22,6 +22,7 @@ class FancyGetopt: def getopt( self, args: _SliceableT[_StrSequenceT_co] | None, object: Any ) -> _StrSequenceT_co: ... # object is an arbitrary non-slotted object + def get_option_order(self) -> list[tuple[str, str]]: ... def generate_help(self, header: str | None = None) -> list[str]: ... diff --git a/mypy/typeshed/stdlib/distutils/file_util.pyi b/mypy/typeshed/stdlib/distutils/file_util.pyi index c763f91a958d7..9d5bf5080b058 100644 --- a/mypy/typeshed/stdlib/distutils/file_util.pyi +++ b/mypy/typeshed/stdlib/distutils/file_util.pyi @@ -27,6 +27,7 @@ def copy_file( verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0, ) -> tuple[_BytesPathT | bytes, bool]: ... + @overload def move_file( src: StrPath, dst: _StrPathT, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0 @@ -35,4 +36,5 @@ def move_file( def move_file( src: BytesPath, dst: _BytesPathT, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0 ) -> _BytesPathT | bytes: ... + def write_file(filename: StrOrBytesPath, contents: Iterable[str]) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/filelist.pyi b/mypy/typeshed/stdlib/distutils/filelist.pyi index 607a78a1fbaca..c3347fe7d1d20 100644 --- a/mypy/typeshed/stdlib/distutils/filelist.pyi +++ b/mypy/typeshed/stdlib/distutils/filelist.pyi @@ -15,6 +15,7 @@ class FileList: def sort(self) -> None: ... def remove_duplicates(self) -> None: ... def process_template_line(self, line: str) -> None: ... + @overload def include_pattern( self, pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[0, False] = 0 @@ -29,6 +30,7 @@ class FileList: prefix: str | None = None, is_regex: bool | Literal[0, 1] = 0, ) -> bool: ... + @overload def exclude_pattern( self, pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[0, False] = 0 @@ -46,6 +48,7 @@ class FileList: def findall(dir: str = ".") -> list[str]: ... def glob_to_re(pattern: str) -> str: ... + @overload def translate_pattern( pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[False, 0] = 0 diff --git a/mypy/typeshed/stdlib/distutils/sysconfig.pyi b/mypy/typeshed/stdlib/distutils/sysconfig.pyi index 4a9c45eb562a4..7c8e0e7b149e0 100644 --- a/mypy/typeshed/stdlib/distutils/sysconfig.pyi +++ b/mypy/typeshed/stdlib/distutils/sysconfig.pyi @@ -1,4 +1,3 @@ -import sys from collections.abc import Mapping from distutils.ccompiler import CCompiler from typing import Final, Literal, overload @@ -12,15 +11,18 @@ project_base: Final[str] python_build: Final[bool] def expand_makefile_vars(s: str, vars: Mapping[str, str]) -> str: ... + @overload @deprecated("SO is deprecated, use EXT_SUFFIX. Support is removed in Python 3.11") def get_config_var(name: Literal["SO"]) -> int | str | None: ... @overload def get_config_var(name: str) -> int | str | None: ... + @overload def get_config_vars() -> dict[str, str | int]: ... @overload def get_config_vars(arg: str, /, *args: str) -> list[str | int]: ... + def get_config_h_filename() -> str: ... def get_makefile_filename() -> str: ... def get_python_inc(plat_specific: bool | Literal[0, 1] = 0, prefix: str | None = None) -> str: ... @@ -28,6 +30,3 @@ def get_python_lib( plat_specific: bool | Literal[0, 1] = 0, standard_lib: bool | Literal[0, 1] = 0, prefix: str | None = None ) -> str: ... def customize_compiler(compiler: CCompiler) -> None: ... - -if sys.version_info < (3, 10): - def get_python_version() -> str: ... diff --git a/mypy/typeshed/stdlib/doctest.pyi b/mypy/typeshed/stdlib/doctest.pyi index 1bb96e1a77868..32c68e3f2c7b3 100644 --- a/mypy/typeshed/stdlib/doctest.pyi +++ b/mypy/typeshed/stdlib/doctest.pyi @@ -3,8 +3,8 @@ import types import unittest from _typeshed import ExcInfo from collections.abc import Callable -from typing import Any, Final, NamedTuple, type_check_only -from typing_extensions import Self, TypeAlias +from typing import Any, Final, NamedTuple, TypeAlias, type_check_only +from typing_extensions import Self __all__ = [ "register_optionflag", diff --git a/mypy/typeshed/stdlib/email/__init__.pyi b/mypy/typeshed/stdlib/email/__init__.pyi index 53f8c350b01e3..aabdca32d506d 100644 --- a/mypy/typeshed/stdlib/email/__init__.pyi +++ b/mypy/typeshed/stdlib/email/__init__.pyi @@ -2,8 +2,7 @@ from collections.abc import Callable from email._policybase import _MessageT from email.message import Message from email.policy import Policy -from typing import IO, overload -from typing_extensions import TypeAlias +from typing import IO, TypeAlias, overload # At runtime, listing submodules in __all__ without them being imported is # valid, and causes them to be included in a star import. See #6523 @@ -38,6 +37,7 @@ def message_from_string(s: str) -> Message: ... def message_from_string(s: str, _class: Callable[[], _MessageT]) -> _MessageT: ... @overload def message_from_string(s: str, _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT]) -> _MessageT: ... + @overload def message_from_bytes(s: bytes | bytearray) -> Message: ... @overload @@ -46,12 +46,14 @@ def message_from_bytes(s: bytes | bytearray, _class: Callable[[], _MessageT]) -> def message_from_bytes( s: bytes | bytearray, _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT] ) -> _MessageT: ... + @overload def message_from_file(fp: IO[str]) -> Message: ... @overload def message_from_file(fp: IO[str], _class: Callable[[], _MessageT]) -> _MessageT: ... @overload def message_from_file(fp: IO[str], _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT]) -> _MessageT: ... + @overload def message_from_binary_file(fp: IO[bytes]) -> Message: ... @overload diff --git a/mypy/typeshed/stdlib/email/_header_value_parser.pyi b/mypy/typeshed/stdlib/email/_header_value_parser.pyi index a6d7c48d69cd8..e75e7ba1cf06c 100644 --- a/mypy/typeshed/stdlib/email/_header_value_parser.pyi +++ b/mypy/typeshed/stdlib/email/_header_value_parser.pyi @@ -17,18 +17,17 @@ TOKEN_ENDS: Final[set[str]] ASPECIALS: Final[set[str]] ATTRIBUTE_ENDS: Final[set[str]] EXTENDED_ATTRIBUTE_ENDS: Final[set[str]] -# Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 +# Added in Python 3.10.15, 3.11.10, 3.12.5 NLSET: Final[set[str]] -# Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 +# Added in Python 3.10.15, 3.11.10, 3.12.5 SPECIALSNL: Final[set[str]] -# Added in Python 3.9.23, 3.10.17, 3.11.12, 3.12.9, 3.13.2 +# Added in Python 3.10.17, 3.11.12, 3.12.9, 3.13.2 def make_quoted_pairs(value: Any) -> str: ... def quote_string(value: Any) -> str: ... -if sys.version_info >= (3, 10): - # Added in Python 3.10.20, 3.11.15, 3.12.13, 3.13.12, 3.14.3 - def make_parenthesis_pairs(value: Any) -> str: ... +# Added in Python 3.10.20, 3.11.15, 3.12.13, 3.13.12, 3.14.3 +def make_parenthesis_pairs(value: Any) -> str: ... rfc2047_matcher: Final[Pattern[str]] diff --git a/mypy/typeshed/stdlib/email/charset.pyi b/mypy/typeshed/stdlib/email/charset.pyi index e1930835bbd11..353cdeb0b9ddd 100644 --- a/mypy/typeshed/stdlib/email/charset.pyi +++ b/mypy/typeshed/stdlib/email/charset.pyi @@ -27,10 +27,12 @@ class Charset: def get_output_charset(self) -> str | None: ... def header_encode(self, string: str) -> str: ... def header_encode_lines(self, string: str, maxlengths: Iterator[int]) -> list[str | None]: ... + @overload def body_encode(self, string: None) -> None: ... @overload def body_encode(self, string: str | bytes) -> str: ... + __hash__: ClassVar[None] # type: ignore[assignment] def __eq__(self, other: object) -> bool: ... def __ne__(self, value: object, /) -> bool: ... diff --git a/mypy/typeshed/stdlib/email/errors.pyi b/mypy/typeshed/stdlib/email/errors.pyi index b501a58665560..4da60250965e5 100644 --- a/mypy/typeshed/stdlib/email/errors.pyi +++ b/mypy/typeshed/stdlib/email/errors.pyi @@ -1,5 +1,3 @@ -import sys - class MessageError(Exception): ... class MessageParseError(MessageError): ... class HeaderParseError(MessageParseError): ... @@ -37,6 +35,4 @@ class NonPrintableDefect(HeaderDefect): class ObsoleteHeaderDefect(HeaderDefect): ... class NonASCIILocalPartDefect(HeaderDefect): ... - -if sys.version_info >= (3, 10): - class InvalidDateDefect(HeaderDefect): ... +class InvalidDateDefect(HeaderDefect): ... diff --git a/mypy/typeshed/stdlib/email/feedparser.pyi b/mypy/typeshed/stdlib/email/feedparser.pyi index d9279e9cd996d..ec92eef678861 100644 --- a/mypy/typeshed/stdlib/email/feedparser.pyi +++ b/mypy/typeshed/stdlib/email/feedparser.pyi @@ -11,6 +11,7 @@ class FeedParser(Generic[_MessageT]): def __init__(self: FeedParser[Message], _factory: None = None, *, policy: Policy[Message] = ...) -> None: ... @overload def __init__(self, _factory: Callable[[], _MessageT], *, policy: Policy[_MessageT] = ...) -> None: ... + def feed(self, data: str) -> None: ... def close(self) -> _MessageT: ... @@ -19,4 +20,5 @@ class BytesFeedParser(FeedParser[_MessageT]): def __init__(self: BytesFeedParser[Message], _factory: None = None, *, policy: Policy[Message] = ...) -> None: ... @overload def __init__(self, _factory: Callable[[], _MessageT], *, policy: Policy[_MessageT] = ...) -> None: ... + def feed(self, data: bytes | bytearray) -> None: ... # type: ignore[override] diff --git a/mypy/typeshed/stdlib/email/generator.pyi b/mypy/typeshed/stdlib/email/generator.pyi index d30e686299fab..c2a9bb0921d78 100644 --- a/mypy/typeshed/stdlib/email/generator.pyi +++ b/mypy/typeshed/stdlib/email/generator.pyi @@ -12,6 +12,7 @@ _MessageT = TypeVar("_MessageT", bound=Message[Any, Any], default=Any) class Generator(Generic[_MessageT]): maxheaderlen: int | None policy: Policy[_MessageT] | None + @overload def __init__( self: Generator[Any], # The Policy of the message is used. @@ -30,6 +31,7 @@ class Generator(Generic[_MessageT]): *, policy: Policy[_MessageT], ) -> None: ... + def write(self, s: str) -> None: ... def flatten(self, msg: _MessageT, unixfrom: bool = False, linesep: str | None = None) -> None: ... def clone(self, fp: SupportsWrite[str]) -> Self: ... diff --git a/mypy/typeshed/stdlib/email/message.pyi b/mypy/typeshed/stdlib/email/message.pyi index 08ba88b4ee6da..784c2cace4255 100644 --- a/mypy/typeshed/stdlib/email/message.pyi +++ b/mypy/typeshed/stdlib/email/message.pyi @@ -5,8 +5,8 @@ from email.charset import Charset from email.contentmanager import ContentManager from email.errors import MessageDefect from email.policy import Policy -from typing import Any, Generic, Literal, Protocol, TypeVar, overload, type_check_only -from typing_extensions import Self, TypeAlias +from typing import Any, Generic, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self __all__ = ["Message", "EmailMessage"] @@ -44,6 +44,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): def set_unixfrom(self, unixfrom: str) -> None: ... def get_unixfrom(self) -> str | None: ... def attach(self, payload: _PayloadType) -> None: ... + # `i: int` without a multipart payload results in an error # `| MaybeNone` acts like `| Any`: can be None for cleared or unset payload, but annoying to check @overload # multipart @@ -56,6 +57,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): def get_payload(self, i: None = None, *, decode: Literal[True]) -> _EncodedPayloadType | MaybeNone: ... @overload # not multipart, IDEM but w/o kwarg def get_payload(self, i: None, decode: Literal[True]) -> _EncodedPayloadType | MaybeNone: ... + # If `charset=None` and payload supports both `encode` AND `decode`, # then an invalid payload could be passed, but this is unlikely # Not[_SupportsEncodeToPayload] @@ -69,6 +71,7 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): payload: _SupportsEncodeToPayload | _SupportsDecodeToPayload | _PayloadType | _MultipartPayloadType, charset: Charset | str, ) -> None: ... + def set_charset(self, charset: _CharsetType) -> None: ... def get_charset(self) -> _CharsetType: ... def __len__(self) -> int: ... @@ -84,14 +87,17 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): def keys(self) -> list[str]: ... def values(self) -> list[_HeaderT_co]: ... def items(self) -> list[tuple[str, _HeaderT_co]]: ... + @overload def get(self, name: str, failobj: None = None) -> _HeaderT_co | None: ... @overload def get(self, name: str, failobj: _T) -> _HeaderT_co | _T: ... + @overload def get_all(self, name: str, failobj: None = None) -> list[_HeaderT_co] | None: ... @overload def get_all(self, name: str, failobj: _T) -> list[_HeaderT_co] | _T: ... + def add_header(self, _name: str, _value: str, **_params: _ParamsType) -> None: ... def replace_header(self, _name: str, _value: _HeaderParamT_contra) -> None: ... def get_content_type(self) -> str: ... @@ -99,37 +105,46 @@ class Message(Generic[_HeaderT_co, _HeaderParamT_contra]): def get_content_subtype(self) -> str: ... def get_default_type(self) -> str: ... def set_default_type(self, ctype: str) -> None: ... + @overload def get_params( self, failobj: None = None, header: str = "content-type", unquote: bool = True ) -> list[tuple[str, str]] | None: ... @overload def get_params(self, failobj: _T, header: str = "content-type", unquote: bool = True) -> list[tuple[str, str]] | _T: ... + @overload def get_param( self, param: str, failobj: None = None, header: str = "content-type", unquote: bool = True ) -> _ParamType | None: ... @overload def get_param(self, param: str, failobj: _T, header: str = "content-type", unquote: bool = True) -> _ParamType | _T: ... + def del_param(self, param: str, header: str = "content-type", requote: bool = True) -> None: ... def set_type(self, type: str, header: str = "Content-Type", requote: bool = True) -> None: ... + @overload def get_filename(self, failobj: None = None) -> str | None: ... @overload def get_filename(self, failobj: _T) -> str | _T: ... + @overload def get_boundary(self, failobj: None = None) -> str | None: ... @overload def get_boundary(self, failobj: _T) -> str | _T: ... + def set_boundary(self, boundary: str) -> None: ... + @overload def get_content_charset(self) -> str | None: ... @overload def get_content_charset(self, failobj: _T) -> str | _T: ... + @overload def get_charsets(self, failobj: None = None) -> list[str | None]: ... @overload def get_charsets(self, failobj: _T) -> list[str | _T]: ... + def walk(self) -> Generator[Self]: ... def get_content_disposition(self) -> str | None: ... def as_string(self, unixfrom: bool = False, maxheaderlen: int = 0, policy: Policy[Any] | None = None) -> str: ... diff --git a/mypy/typeshed/stdlib/email/parser.pyi b/mypy/typeshed/stdlib/email/parser.pyi index a4924a6cbd88f..f1b418ee30a02 100644 --- a/mypy/typeshed/stdlib/email/parser.pyi +++ b/mypy/typeshed/stdlib/email/parser.pyi @@ -16,6 +16,7 @@ class Parser(Generic[_MessageT]): def __init__(self, _class: None = None, *, policy: Policy[_MessageT]) -> None: ... @overload def __init__(self, _class: Callable[[], _MessageT] | None, *, policy: Policy[_MessageT] = ...) -> None: ... + def parse(self, fp: SupportsRead[str], headersonly: bool = False) -> _MessageT: ... def parsestr(self, text: str, headersonly: bool = False) -> _MessageT: ... @@ -25,12 +26,14 @@ class HeaderParser(Parser[_MessageT]): class BytesParser(Generic[_MessageT]): parser: Parser[_MessageT] + @overload def __init__(self: BytesParser[Message[str, str]], _class: None = None) -> None: ... @overload def __init__(self, _class: None = None, *, policy: Policy[_MessageT]) -> None: ... @overload def __init__(self, _class: Callable[[], _MessageT], *, policy: Policy[_MessageT] = ...) -> None: ... + def parse(self, fp: _WrappedBuffer, headersonly: bool = False) -> _MessageT: ... def parsebytes(self, text: bytes | bytearray, headersonly: bool = False) -> _MessageT: ... diff --git a/mypy/typeshed/stdlib/email/policy.pyi b/mypy/typeshed/stdlib/email/policy.pyi index 35c999919eede..6b719f3c93fa0 100644 --- a/mypy/typeshed/stdlib/email/policy.pyi +++ b/mypy/typeshed/stdlib/email/policy.pyi @@ -12,6 +12,7 @@ class EmailPolicy(Policy[_MessageT]): refold_source: str header_factory: Callable[[str, Any], Any] content_manager: ContentManager + @overload def __init__( self: EmailPolicy[EmailMessage], @@ -46,6 +47,7 @@ class EmailPolicy(Policy[_MessageT]): header_factory: Callable[[str, str], str] = ..., content_manager: ContentManager = ..., ) -> None: ... + def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: ... def header_store_parse(self, name: str, value: Any) -> tuple[str, Any]: ... def header_fetch_parse(self, name: str, value: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/email/utils.pyi b/mypy/typeshed/stdlib/email/utils.pyi index cece2f2a11190..6b47950a2ef8f 100644 --- a/mypy/typeshed/stdlib/email/utils.pyi +++ b/mypy/typeshed/stdlib/email/utils.pyi @@ -4,8 +4,8 @@ from _typeshed import Unused from collections.abc import Iterable from email import _ParamType from email.charset import Charset -from typing import overload -from typing_extensions import TypeAlias, deprecated +from typing import TypeAlias, overload +from typing_extensions import deprecated __all__ = [ "collapse_rfc2231_value", @@ -36,14 +36,17 @@ def formataddr(pair: tuple[str | None, str], charset: str | Charset = "utf-8") - # `strict` parameter added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 def getaddresses(fieldvalues: Iterable[str], *, strict: bool = True) -> list[tuple[str, str]]: ... + @overload def parsedate(data: None) -> None: ... @overload def parsedate(data: str) -> tuple[int, int, int, int, int, int, int, int, int] | None: ... + @overload def parsedate_tz(data: None) -> None: ... @overload def parsedate_tz(data: str) -> _PDTZ | None: ... + def parsedate_to_datetime(data: str) -> datetime.datetime: ... def mktime_tz(data: _PDTZ) -> int: ... def formatdate(timeval: float | None = None, localtime: bool = False, usegmt: bool = False) -> str: ... diff --git a/mypy/typeshed/stdlib/enum.pyi b/mypy/typeshed/stdlib/enum.pyi index f9b53e1d45f16..1d216b90b6b7b 100644 --- a/mypy/typeshed/stdlib/enum.pyi +++ b/mypy/typeshed/stdlib/enum.pyi @@ -4,8 +4,8 @@ import types from _typeshed import SupportsKeysAndGetItem, Unused from builtins import property as _builtins_property from collections.abc import Callable, Iterable, Iterator, Mapping -from typing import Any, Final, Generic, Literal, SupportsIndex, TypeVar, overload -from typing_extensions import Self, TypeAlias, disjoint_base +from typing import Any, Final, Generic, Literal, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import Self, disjoint_base __all__ = ["EnumMeta", "Enum", "IntEnum", "Flag", "IntFlag", "auto", "unique"] @@ -37,6 +37,8 @@ if sys.version_info >= (3, 11): if sys.version_info >= (3, 13): __all__ += ["EnumDict"] +if sys.version_info >= (3, 15): + __all__ += ["show_flag_values", "bin"] _EnumMemberT = TypeVar("_EnumMemberT") _EnumerationT = TypeVar("_EnumerationT", bound=type[Enum]) @@ -81,6 +83,7 @@ class _EnumDict(dict[str, Any]): def update(self, members: SupportsKeysAndGetItem[str, Any], **more_members: Any) -> None: ... @overload def update(self, members: Iterable[tuple[str, Any]], **more_members: Any) -> None: ... + if sys.version_info >= (3, 13): @property def member_names(self) -> list[str]: ... @@ -114,10 +117,8 @@ class EnumMeta(type): def __contains__(self: type[Any], value: object) -> bool: ... elif sys.version_info >= (3, 11): def __contains__(self: type[Any], member: object) -> bool: ... - elif sys.version_info >= (3, 10): - def __contains__(self: type[Any], obj: object) -> bool: ... else: - def __contains__(self: type[Any], member: object) -> bool: ... + def __contains__(self: type[Any], obj: object) -> bool: ... def __getitem__(self: type[_EnumMemberT], name: str) -> _EnumMemberT: ... @_builtins_property diff --git a/mypy/typeshed/stdlib/faulthandler.pyi b/mypy/typeshed/stdlib/faulthandler.pyi index 17d4eef69af76..6999933c43b98 100644 --- a/mypy/typeshed/stdlib/faulthandler.pyi +++ b/mypy/typeshed/stdlib/faulthandler.pyi @@ -3,16 +3,39 @@ from _typeshed import FileDescriptorLike def cancel_dump_traceback_later() -> None: ... def disable() -> None: ... -def dump_traceback(file: FileDescriptorLike = sys.stderr, all_threads: bool = True) -> None: ... + +if sys.version_info >= (3, 15): + def dump_traceback( + file: FileDescriptorLike = sys.stderr, all_threads: bool = True, *, max_threads: int | None = None + ) -> None: ... + +else: + def dump_traceback(file: FileDescriptorLike = sys.stderr, all_threads: bool = True) -> None: ... if sys.version_info >= (3, 14): def dump_c_stack(file: FileDescriptorLike = sys.stderr) -> None: ... -def dump_traceback_later( - timeout: float, repeat: bool = False, file: FileDescriptorLike = sys.stderr, exit: bool = False -) -> None: ... +if sys.version_info >= (3, 15): + def dump_traceback_later( + timeout: float, + repeat: bool = False, + file: FileDescriptorLike = sys.stderr, + exit: bool = False, + *, + max_threads: int | None = None, + ) -> None: ... -if sys.version_info >= (3, 14): +else: + def dump_traceback_later( + timeout: float, repeat: bool = False, file: FileDescriptorLike = sys.stderr, exit: bool = False + ) -> None: ... + +if sys.version_info >= (3, 15): + def enable( + file: FileDescriptorLike = sys.stderr, all_threads: bool = True, c_stack: bool = True, *, max_threads: int | None = None + ) -> None: ... + +elif sys.version_info >= (3, 14): def enable(file: FileDescriptorLike = sys.stderr, all_threads: bool = True, c_stack: bool = True) -> None: ... else: @@ -21,5 +44,18 @@ else: def is_enabled() -> bool: ... if sys.platform != "win32": - def register(signum: int, file: FileDescriptorLike = sys.stderr, all_threads: bool = True, chain: bool = False) -> None: ... + if sys.version_info >= (3, 15): + def register( + signum: int, + file: FileDescriptorLike = sys.stderr, + all_threads: bool = True, + chain: bool = False, + *, + max_threads: int | None = None, + ) -> None: ... + else: + def register( + signum: int, file: FileDescriptorLike = sys.stderr, all_threads: bool = True, chain: bool = False + ) -> None: ... + def unregister(signum: int, /) -> None: ... diff --git a/mypy/typeshed/stdlib/fcntl.pyi b/mypy/typeshed/stdlib/fcntl.pyi index 5a3e89b0c6766..c17f31c4bebe8 100644 --- a/mypy/typeshed/stdlib/fcntl.pyi +++ b/mypy/typeshed/stdlib/fcntl.pyi @@ -45,11 +45,8 @@ if sys.platform != "win32": F_OFD_GETLK: Final[int] F_OFD_SETLK: Final[int] F_OFD_SETLKW: Final[int] - - if sys.version_info >= (3, 10): - F_GETPIPE_SZ: Final[int] - F_SETPIPE_SZ: Final[int] - + F_GETPIPE_SZ: Final[int] + F_SETPIPE_SZ: Final[int] DN_ACCESS: Final[int] DN_ATTRIB: Final[int] DN_CREATE: Final[int] @@ -140,6 +137,7 @@ if sys.platform != "win32": def fcntl(fd: FileDescriptorLike, cmd: int, arg: int = 0, /) -> int: ... @overload def fcntl(fd: FileDescriptorLike, cmd: int, arg: str | ReadOnlyBuffer, /) -> bytes: ... + # If arg is an int, return int @overload def ioctl(fd: FileDescriptorLike, request: int, arg: int = 0, mutate_flag: bool = True, /) -> int: ... @@ -154,5 +152,6 @@ if sys.platform != "win32": def ioctl(fd: FileDescriptorLike, request: int, arg: WriteableBuffer, mutate_flag: Literal[False], /) -> bytes: ... @overload def ioctl(fd: FileDescriptorLike, request: int, arg: Buffer, mutate_flag: bool = True, /) -> Any: ... + def flock(fd: FileDescriptorLike, operation: int, /) -> None: ... def lockf(fd: FileDescriptorLike, cmd: int, len: int = 0, start: int = 0, whence: int = 0, /) -> Any: ... diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index 95164de2f0107..db9c228f5f28e 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import AnyStr_co, StrOrBytesPath from collections.abc import Callable, Iterable, Iterator from types import GenericAlias, TracebackType -from typing import IO, Any, AnyStr, Literal, Protocol, overload, type_check_only -from typing_extensions import Self, TypeAlias, deprecated +from typing import IO, Any, AnyStr, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated __all__ = [ "input", @@ -30,10 +30,55 @@ class _HasReadlineAndFileno(Protocol[AnyStr_co]): def readline(self) -> AnyStr_co: ... def fileno(self) -> int: ... -if sys.version_info >= (3, 10): +# encoding and errors are added +@overload +def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: _TextMode = "r", + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None, + encoding: str | None = None, + errors: str | None = None, +) -> FileInput[str]: ... +@overload +def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: Literal["rb"], + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None, + encoding: None = None, + errors: None = None, +) -> FileInput[bytes]: ... +@overload +def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, + inplace: bool = False, + backup: str = "", + *, + mode: str, + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, + encoding: str | None = None, + errors: str | None = None, +) -> FileInput[Any]: ... + +def close() -> None: ... +def nextfile() -> None: ... +def filename() -> str: ... +def lineno() -> int: ... +def filelineno() -> int: ... +def fileno() -> int: ... +def isfirstline() -> bool: ... +def isstdin() -> bool: ... + +class FileInput(Iterator[AnyStr]): # encoding and errors are added @overload - def input( + def __init__( + self: FileInput[str], files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, inplace: bool = False, backup: str = "", @@ -42,9 +87,10 @@ if sys.version_info >= (3, 10): openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None, encoding: str | None = None, errors: str | None = None, - ) -> FileInput[str]: ... + ) -> None: ... @overload - def input( + def __init__( + self: FileInput[bytes], files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, inplace: bool = False, backup: str = "", @@ -53,9 +99,10 @@ if sys.version_info >= (3, 10): openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None, encoding: None = None, errors: None = None, - ) -> FileInput[bytes]: ... + ) -> None: ... @overload - def input( + def __init__( + self: FileInput[Any], files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, inplace: bool = False, backup: str = "", @@ -64,119 +111,7 @@ if sys.version_info >= (3, 10): openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, encoding: str | None = None, errors: str | None = None, - ) -> FileInput[Any]: ... - -else: - # bufsize is dropped and mode and openhook become keyword-only - @overload - def input( - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - *, - mode: _TextMode = "r", - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None, - ) -> FileInput[str]: ... - @overload - def input( - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - *, - mode: Literal["rb"], - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None, - ) -> FileInput[bytes]: ... - @overload - def input( - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - *, - mode: str, - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, - ) -> FileInput[Any]: ... - -def close() -> None: ... -def nextfile() -> None: ... -def filename() -> str: ... -def lineno() -> int: ... -def filelineno() -> int: ... -def fileno() -> int: ... -def isfirstline() -> bool: ... -def isstdin() -> bool: ... - -class FileInput(Iterator[AnyStr]): - if sys.version_info >= (3, 10): - # encoding and errors are added - @overload - def __init__( - self: FileInput[str], - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - *, - mode: _TextMode = "r", - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None, - encoding: str | None = None, - errors: str | None = None, - ) -> None: ... - @overload - def __init__( - self: FileInput[bytes], - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - *, - mode: Literal["rb"], - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None, - encoding: None = None, - errors: None = None, - ) -> None: ... - @overload - def __init__( - self: FileInput[Any], - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - *, - mode: str, - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, - encoding: str | None = None, - errors: str | None = None, - ) -> None: ... - - else: - # bufsize is dropped and mode and openhook become keyword-only - @overload - def __init__( - self: FileInput[str], - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - *, - mode: _TextMode = "r", - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None, - ) -> None: ... - @overload - def __init__( - self: FileInput[bytes], - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - *, - mode: Literal["rb"], - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None, - ) -> None: ... - @overload - def __init__( - self: FileInput[Any], - files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None, - inplace: bool = False, - backup: str = "", - *, - mode: str, - openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None, - ) -> None: ... + ) -> None: ... def __del__(self) -> None: ... def close(self) -> None: ... @@ -199,17 +134,8 @@ class FileInput(Iterator[AnyStr]): def isstdin(self) -> bool: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -if sys.version_info >= (3, 10): - def hook_compressed( - filename: StrOrBytesPath, mode: str, *, encoding: str | None = None, errors: str | None = None - ) -> IO[Any]: ... - -else: - def hook_compressed(filename: StrOrBytesPath, mode: str) -> IO[Any]: ... - -if sys.version_info >= (3, 10): - @deprecated("Deprecated since Python 3.10. Use `fileinput.input` or `fileinput.FileInput` instead.") - def hook_encoded(encoding: str, errors: str | None = None) -> Callable[[StrOrBytesPath, str], IO[Any]]: ... - -else: - def hook_encoded(encoding: str, errors: str | None = None) -> Callable[[StrOrBytesPath, str], IO[Any]]: ... +def hook_compressed( + filename: StrOrBytesPath, mode: str, *, encoding: str | None = None, errors: str | None = None +) -> IO[Any]: ... +@deprecated("Deprecated since Python 3.10. Use `fileinput.input` or `fileinput.FileInput` instead.") +def hook_encoded(encoding: str, errors: str | None = None) -> Callable[[StrOrBytesPath, str], IO[Any]]: ... diff --git a/mypy/typeshed/stdlib/formatter.pyi b/mypy/typeshed/stdlib/formatter.pyi deleted file mode 100644 index 05c3c8b3dd41c..0000000000000 --- a/mypy/typeshed/stdlib/formatter.pyi +++ /dev/null @@ -1,88 +0,0 @@ -from collections.abc import Iterable -from typing import IO, Any -from typing_extensions import TypeAlias - -AS_IS: None -_FontType: TypeAlias = tuple[str, bool, bool, bool] -_StylesType: TypeAlias = tuple[Any, ...] - -class NullFormatter: - writer: NullWriter | None - def __init__(self, writer: NullWriter | None = None) -> None: ... - def end_paragraph(self, blankline: int) -> None: ... - def add_line_break(self) -> None: ... - def add_hor_rule(self, *args: Any, **kw: Any) -> None: ... - def add_label_data(self, format: str, counter: int, blankline: int | None = None) -> None: ... - def add_flowing_data(self, data: str) -> None: ... - def add_literal_data(self, data: str) -> None: ... - def flush_softspace(self) -> None: ... - def push_alignment(self, align: str | None) -> None: ... - def pop_alignment(self) -> None: ... - def push_font(self, x: _FontType) -> None: ... - def pop_font(self) -> None: ... - def push_margin(self, margin: int) -> None: ... - def pop_margin(self) -> None: ... - def set_spacing(self, spacing: str | None) -> None: ... - def push_style(self, *styles: _StylesType) -> None: ... - def pop_style(self, n: int = 1) -> None: ... - def assert_line_data(self, flag: int = 1) -> None: ... - -class AbstractFormatter: - writer: NullWriter - align: str | None - align_stack: list[str | None] - font_stack: list[_FontType] - margin_stack: list[int] - spacing: str | None - style_stack: Any - nospace: int - softspace: int - para_end: int - parskip: int - hard_break: int - have_label: int - def __init__(self, writer: NullWriter) -> None: ... - def end_paragraph(self, blankline: int) -> None: ... - def add_line_break(self) -> None: ... - def add_hor_rule(self, *args: Any, **kw: Any) -> None: ... - def add_label_data(self, format: str, counter: int, blankline: int | None = None) -> None: ... - def format_counter(self, format: Iterable[str], counter: int) -> str: ... - def format_letter(self, case: str, counter: int) -> str: ... - def format_roman(self, case: str, counter: int) -> str: ... - def add_flowing_data(self, data: str) -> None: ... - def add_literal_data(self, data: str) -> None: ... - def flush_softspace(self) -> None: ... - def push_alignment(self, align: str | None) -> None: ... - def pop_alignment(self) -> None: ... - def push_font(self, font: _FontType) -> None: ... - def pop_font(self) -> None: ... - def push_margin(self, margin: int) -> None: ... - def pop_margin(self) -> None: ... - def set_spacing(self, spacing: str | None) -> None: ... - def push_style(self, *styles: _StylesType) -> None: ... - def pop_style(self, n: int = 1) -> None: ... - def assert_line_data(self, flag: int = 1) -> None: ... - -class NullWriter: - def flush(self) -> None: ... - def new_alignment(self, align: str | None) -> None: ... - def new_font(self, font: _FontType) -> None: ... - def new_margin(self, margin: int, level: int) -> None: ... - def new_spacing(self, spacing: str | None) -> None: ... - def new_styles(self, styles: tuple[Any, ...]) -> None: ... - def send_paragraph(self, blankline: int) -> None: ... - def send_line_break(self) -> None: ... - def send_hor_rule(self, *args: Any, **kw: Any) -> None: ... - def send_label_data(self, data: str) -> None: ... - def send_flowing_data(self, data: str) -> None: ... - def send_literal_data(self, data: str) -> None: ... - -class AbstractWriter(NullWriter): ... - -class DumbWriter(NullWriter): - file: IO[str] - maxcol: int - def __init__(self, file: IO[str] | None = None, maxcol: int = 72) -> None: ... - def reset(self) -> None: ... - -def test(file: str | None = None) -> None: ... diff --git a/mypy/typeshed/stdlib/fractions.pyi b/mypy/typeshed/stdlib/fractions.pyi index ef4066aa65b52..42947f2e2266a 100644 --- a/mypy/typeshed/stdlib/fractions.pyi +++ b/mypy/typeshed/stdlib/fractions.pyi @@ -2,8 +2,8 @@ import sys from collections.abc import Callable from decimal import Decimal from numbers import Rational, Real -from typing import Any, Literal, Protocol, SupportsIndex, overload, type_check_only -from typing_extensions import Self, TypeAlias +from typing import Any, Literal, Protocol, SupportsIndex, TypeAlias, overload, type_check_only +from typing_extensions import Self _ComparableNum: TypeAlias = int | float | Decimal | Real @@ -15,11 +15,11 @@ class _ConvertibleToIntegerRatio(Protocol): class Fraction(Rational): __slots__ = ("_numerator", "_denominator") + @overload def __new__(cls, numerator: int | Rational = 0, denominator: int | Rational | None = None) -> Self: ... @overload def __new__(cls, numerator: float | Decimal | str) -> Self: ... - if sys.version_info >= (3, 14): @overload def __new__(cls, numerator: _ConvertibleToIntegerRatio) -> Self: ... @@ -37,78 +37,93 @@ class Fraction(Rational): def numerator(a) -> int: ... @property def denominator(a) -> int: ... + @overload def __add__(a, b: int | Fraction) -> Fraction: ... @overload def __add__(a, b: float) -> float: ... @overload def __add__(a, b: complex) -> complex: ... + @overload def __radd__(b, a: int | Fraction) -> Fraction: ... @overload def __radd__(b, a: float) -> float: ... @overload def __radd__(b, a: complex) -> complex: ... + @overload def __sub__(a, b: int | Fraction) -> Fraction: ... @overload def __sub__(a, b: float) -> float: ... @overload def __sub__(a, b: complex) -> complex: ... + @overload def __rsub__(b, a: int | Fraction) -> Fraction: ... @overload def __rsub__(b, a: float) -> float: ... @overload def __rsub__(b, a: complex) -> complex: ... + @overload def __mul__(a, b: int | Fraction) -> Fraction: ... @overload def __mul__(a, b: float) -> float: ... @overload def __mul__(a, b: complex) -> complex: ... + @overload def __rmul__(b, a: int | Fraction) -> Fraction: ... @overload def __rmul__(b, a: float) -> float: ... @overload def __rmul__(b, a: complex) -> complex: ... + @overload def __truediv__(a, b: int | Fraction) -> Fraction: ... @overload def __truediv__(a, b: float) -> float: ... @overload def __truediv__(a, b: complex) -> complex: ... + @overload def __rtruediv__(b, a: int | Fraction) -> Fraction: ... @overload def __rtruediv__(b, a: float) -> float: ... @overload def __rtruediv__(b, a: complex) -> complex: ... + @overload def __floordiv__(a, b: int | Fraction) -> int: ... @overload def __floordiv__(a, b: float) -> float: ... + @overload def __rfloordiv__(b, a: int | Fraction) -> int: ... @overload def __rfloordiv__(b, a: float) -> float: ... + @overload def __mod__(a, b: int | Fraction) -> Fraction: ... @overload def __mod__(a, b: float) -> float: ... + @overload def __rmod__(b, a: int | Fraction) -> Fraction: ... @overload def __rmod__(b, a: float) -> float: ... + @overload def __divmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ... @overload def __divmod__(a, b: float) -> tuple[float, Fraction]: ... + @overload def __rdivmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ... @overload def __rdivmod__(a, b: float) -> tuple[float, Fraction]: ... + if sys.version_info >= (3, 14): @overload def __pow__(a, b: int, modulo: None = None) -> Fraction: ... @@ -123,6 +138,7 @@ class Fraction(Rational): def __pow__(a, b: float | Fraction) -> float: ... @overload def __pow__(a, b: complex) -> complex: ... + if sys.version_info >= (3, 14): @overload def __rpow__(b, a: float | Fraction, modulo: None = None) -> float: ... @@ -140,10 +156,12 @@ class Fraction(Rational): def __trunc__(a) -> int: ... def __floor__(a) -> int: ... def __ceil__(a) -> int: ... + @overload def __round__(self, ndigits: None = None) -> int: ... @overload def __round__(self, ndigits: int) -> Fraction: ... + def __hash__(self) -> int: ... # type: ignore[override] def __eq__(a, b: object) -> bool: ... def __lt__(a, b: _ComparableNum) -> bool: ... diff --git a/mypy/typeshed/stdlib/ftplib.pyi b/mypy/typeshed/stdlib/ftplib.pyi index 73eaa8a34e578..1b7222fc94f75 100644 --- a/mypy/typeshed/stdlib/ftplib.pyi +++ b/mypy/typeshed/stdlib/ftplib.pyi @@ -154,6 +154,7 @@ class FTP_TLS(FTP): *, encoding: str = "utf-8", ) -> None: ... + ssl_version: int keyfile: StrOrBytesPath | None certfile: StrOrBytesPath | None diff --git a/mypy/typeshed/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index 57bc3f179f7ac..5619a64f6ed20 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -3,8 +3,21 @@ import types from _typeshed import SupportsAllComparisons, SupportsItems from collections.abc import Callable, Hashable, Iterable, Sized from types import GenericAlias -from typing import Any, Final, Generic, Literal, NamedTuple, TypedDict, TypeVar, final, overload, type_check_only -from typing_extensions import ParamSpec, Self, TypeAlias, disjoint_base +from typing import ( + Any, + Final, + Generic, + Literal, + NamedTuple, + ParamSpec, + TypeAlias, + TypedDict, + TypeVar, + final, + overload, + type_check_only, +) +from typing_extensions import Self, disjoint_base __all__ = [ "update_wrapper", @@ -34,7 +47,6 @@ _RWrapper = TypeVar("_RWrapper") if sys.version_info >= (3, 14): @overload def reduce(function: Callable[[_T, _S], _T], iterable: Iterable[_S], /, initial: _T) -> _T: ... - else: @overload def reduce(function: Callable[[_T, _S], _T], iterable: Iterable[_S], initial: _T, /) -> _T: ... @@ -154,6 +166,7 @@ else: def total_ordering(cls: type[_T]) -> type[_T]: ... def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsAllComparisons]: ... + @disjoint_base class partial(Generic[_T]): @property @@ -198,6 +211,7 @@ else: class _SingleDispatchCallable(Generic[_T]): registry: types.MappingProxyType[Any, Callable[..., _T]] def dispatch(self, cls: Any) -> Callable[..., _T]: ... + # @fun.register(complex) # def _(arg, verbose=False): ... @overload @@ -209,6 +223,7 @@ class _SingleDispatchCallable(Generic[_T]): # fun.register(int, lambda x: x) @overload def register(self, cls: _RegType, func: Callable[..., _T]) -> Callable[..., _T]: ... + def _clear_cache(self) -> None: ... def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ... @@ -220,22 +235,26 @@ class singledispatchmethod(Generic[_T]): def __init__(self, func: Callable[..., _T]) -> None: ... @property def __isabstractmethod__(self) -> bool: ... + @overload def register(self, cls: _RegType, method: None = None) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... @overload def register(self, cls: Callable[..., _T], method: None = None) -> Callable[..., _T]: ... @overload def register(self, cls: _RegType, method: Callable[..., _T]) -> Callable[..., _T]: ... + def __get__(self, obj: _S, cls: type[_S] | None = None) -> Callable[..., _T]: ... class cached_property(Generic[_T_co]): func: Callable[[Any], _T_co] attrname: str | None def __init__(self, func: Callable[[Any], _T_co]) -> None: ... + @overload def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ... @overload def __get__(self, instance: object, owner: type[Any] | None = None) -> _T_co: ... + def __set_name__(self, owner: type[Any], name: str) -> None: ... # __set__ is not defined at runtime, but @cached_property is designed to be settable def __set__(self, instance: object, value: _T_co) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] diff --git a/mypy/typeshed/stdlib/gc.pyi b/mypy/typeshed/stdlib/gc.pyi index ec1ed2681c5c8..dc20a570cc89b 100644 --- a/mypy/typeshed/stdlib/gc.pyi +++ b/mypy/typeshed/stdlib/gc.pyi @@ -1,6 +1,5 @@ from collections.abc import Callable -from typing import Any, Final, Literal -from typing_extensions import TypeAlias +from typing import Any, Final, Literal, TypeAlias DEBUG_COLLECTABLE: Final = 2 DEBUG_LEAK: Final = 38 diff --git a/mypy/typeshed/stdlib/genericpath.pyi b/mypy/typeshed/stdlib/genericpath.pyi index 3caed77a661ac..07c58cc496b60 100644 --- a/mypy/typeshed/stdlib/genericpath.pyi +++ b/mypy/typeshed/stdlib/genericpath.pyi @@ -3,7 +3,7 @@ import sys from _typeshed import BytesPath, FileDescriptorOrPath, StrOrBytesPath, StrPath, SupportsRichComparisonT from collections.abc import Sequence from typing import Literal, NewType, overload -from typing_extensions import LiteralString +from typing_extensions import LiteralString, deprecated __all__ = [ "commonprefix", @@ -23,22 +23,41 @@ if sys.version_info >= (3, 12): __all__ += ["islink"] if sys.version_info >= (3, 13): __all__ += ["isjunction", "isdevdrive", "lexists"] +if sys.version_info >= (3, 15): + __all__ += ["ALL_BUT_LAST"] # All overloads can return empty string. Ideally, Literal[""] would be a valid # Iterable[T], so that list[T] | Literal[""] could be used as a return # type. But because this only works when T is str, we need Sequence[T] instead. -@overload -def commonprefix(m: Sequence[LiteralString]) -> LiteralString: ... -@overload -def commonprefix(m: Sequence[StrPath]) -> str: ... -@overload -def commonprefix(m: Sequence[BytesPath]) -> bytes | Literal[""]: ... -@overload -def commonprefix(m: Sequence[list[SupportsRichComparisonT]]) -> Sequence[SupportsRichComparisonT]: ... -@overload -def commonprefix(m: Sequence[tuple[SupportsRichComparisonT, ...]]) -> Sequence[SupportsRichComparisonT]: ... +if sys.version_info >= (3, 15): + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[LiteralString], /) -> LiteralString: ... + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[StrPath], /) -> str: ... + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[BytesPath], /) -> bytes | Literal[""]: ... + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[list[SupportsRichComparisonT]], /) -> Sequence[SupportsRichComparisonT]: ... + @overload + @deprecated("Deprecated since Python 3.15; use os.path.commonpath() for path prefixes.") + def commonprefix(m: Sequence[tuple[SupportsRichComparisonT, ...]], /) -> Sequence[SupportsRichComparisonT]: ... +else: + @overload + def commonprefix(m: Sequence[LiteralString]) -> LiteralString: ... + @overload + def commonprefix(m: Sequence[StrPath]) -> str: ... + @overload + def commonprefix(m: Sequence[BytesPath]) -> bytes | Literal[""]: ... + @overload + def commonprefix(m: Sequence[list[SupportsRichComparisonT]]) -> Sequence[SupportsRichComparisonT]: ... + @overload + def commonprefix(m: Sequence[tuple[SupportsRichComparisonT, ...]]) -> Sequence[SupportsRichComparisonT]: ... + def exists(path: FileDescriptorOrPath) -> bool: ... -def getsize(filename: FileDescriptorOrPath) -> int: ... def isfile(path: FileDescriptorOrPath) -> bool: ... def isdir(s: FileDescriptorOrPath) -> bool: ... @@ -47,12 +66,23 @@ if sys.version_info >= (3, 12): # These return float if os.stat_float_times() == True, # but int is a subclass of float. -def getatime(filename: FileDescriptorOrPath) -> float: ... -def getmtime(filename: FileDescriptorOrPath) -> float: ... -def getctime(filename: FileDescriptorOrPath) -> float: ... -def samefile(f1: FileDescriptorOrPath, f2: FileDescriptorOrPath) -> bool: ... def sameopenfile(fp1: int, fp2: int) -> bool: ... -def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... + +if sys.version_info >= (3, 15): + def getsize(filename: FileDescriptorOrPath, /) -> int: ... + def getatime(filename: FileDescriptorOrPath, /) -> float: ... + def getmtime(filename: FileDescriptorOrPath, /) -> float: ... + def getctime(filename: FileDescriptorOrPath, /) -> float: ... + def samefile(f1: FileDescriptorOrPath, f2: FileDescriptorOrPath, /) -> bool: ... + def samestat(s1: os.stat_result, s2: os.stat_result, /) -> bool: ... + +else: + def getsize(filename: FileDescriptorOrPath) -> int: ... + def getatime(filename: FileDescriptorOrPath) -> float: ... + def getmtime(filename: FileDescriptorOrPath) -> float: ... + def getctime(filename: FileDescriptorOrPath) -> float: ... + def samefile(f1: FileDescriptorOrPath, f2: FileDescriptorOrPath) -> bool: ... + def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... if sys.version_info >= (3, 13): def isjunction(path: StrOrBytesPath) -> bool: ... @@ -62,3 +92,7 @@ if sys.version_info >= (3, 13): # Added in Python 3.9.23, 3.10.18, 3.11.13, 3.12.11, 3.13.4 _AllowMissingType = NewType("_AllowMissingType", object) ALLOW_MISSING: _AllowMissingType + +if sys.version_info >= (3, 15): + _AllButLastType = NewType("_AllButLastType", object) + ALL_BUT_LAST: _AllButLastType diff --git a/mypy/typeshed/stdlib/gettext.pyi b/mypy/typeshed/stdlib/gettext.pyi index e9ffd7a4a4a42..aac2d3edf7d98 100644 --- a/mypy/typeshed/stdlib/gettext.pyi +++ b/mypy/typeshed/stdlib/gettext.pyi @@ -110,8 +110,8 @@ if sys.version_info >= (3, 11): class_: Callable[[io.BufferedReader], NullTranslations] | None = None, fallback: bool = False, ) -> NullTranslations: ... - def install(domain: str, localedir: StrPath | None = None, *, names: Container[str] | None = None) -> None: ... + def install(domain: str, localedir: StrPath | None = None, *, names: Container[str] | None = None) -> None: ... else: @overload def translation( @@ -150,6 +150,7 @@ else: fallback: bool = False, codeset: str | None = ..., ) -> NullTranslations: ... + @overload def install(domain: str, localedir: StrPath | None = None, names: Container[str] | None = None) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/glob.pyi b/mypy/typeshed/stdlib/glob.pyi index 942fd73961963..bdfb2cfbcfedd 100644 --- a/mypy/typeshed/stdlib/glob.pyi +++ b/mypy/typeshed/stdlib/glob.pyi @@ -9,7 +9,7 @@ __all__ = ["escape", "glob", "iglob"] if sys.version_info >= (3, 13): __all__ += ["translate"] -if sys.version_info >= (3, 10): +if sys.version_info < (3, 15): @deprecated( "Deprecated since Python 3.10; will be removed in Python 3.15. Use `glob.glob()` with the *root_dir* argument instead." ) @@ -19,10 +19,6 @@ if sys.version_info >= (3, 10): ) def glob1(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ... -else: - def glob0(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ... - def glob1(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ... - if sys.version_info >= (3, 11): def glob( pathname: AnyStr, @@ -41,7 +37,7 @@ if sys.version_info >= (3, 11): include_hidden: bool = False, ) -> Iterator[AnyStr]: ... -elif sys.version_info >= (3, 10): +else: def glob( pathname: AnyStr, *, root_dir: StrOrBytesPath | None = None, dir_fd: int | None = None, recursive: bool = False ) -> list[AnyStr]: ... @@ -49,10 +45,6 @@ elif sys.version_info >= (3, 10): pathname: AnyStr, *, root_dir: StrOrBytesPath | None = None, dir_fd: int | None = None, recursive: bool = False ) -> Iterator[AnyStr]: ... -else: - def glob(pathname: AnyStr, *, recursive: bool = False) -> list[AnyStr]: ... - def iglob(pathname: AnyStr, *, recursive: bool = False) -> Iterator[AnyStr]: ... - def escape(pathname: AnyStr) -> AnyStr: ... def has_magic(s: str | bytes) -> bool: ... # undocumented diff --git a/mypy/typeshed/stdlib/graphlib.pyi b/mypy/typeshed/stdlib/graphlib.pyi index 1ca8cbe12b085..f0ac72b6135e8 100644 --- a/mypy/typeshed/stdlib/graphlib.pyi +++ b/mypy/typeshed/stdlib/graphlib.pyi @@ -15,6 +15,7 @@ class TopologicalSorter(Generic[_T]): def __init__(self, graph: None = None) -> None: ... @overload def __init__(self, graph: SupportsItems[_T, Iterable[_T]]) -> None: ... + def add(self, node: _T, *predecessors: _T) -> None: ... def prepare(self) -> None: ... def is_active(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/grp.pyi b/mypy/typeshed/stdlib/grp.pyi index 965ecece2a56d..9f372b4d63dc8 100644 --- a/mypy/typeshed/stdlib/grp.pyi +++ b/mypy/typeshed/stdlib/grp.pyi @@ -5,8 +5,7 @@ from typing import Any, Final, final if sys.platform != "win32": @final class struct_group(structseq[Any], tuple[str, str | None, int, list[str]]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("gr_name", "gr_passwd", "gr_gid", "gr_mem") + __match_args__: Final = ("gr_name", "gr_passwd", "gr_gid", "gr_mem") @property def gr_name(self) -> str: ... diff --git a/mypy/typeshed/stdlib/gzip.pyi b/mypy/typeshed/stdlib/gzip.pyi index b18f76f06e3ee..4322e6c84c905 100644 --- a/mypy/typeshed/stdlib/gzip.pyi +++ b/mypy/typeshed/stdlib/gzip.pyi @@ -2,8 +2,8 @@ import sys import zlib from _typeshed import ReadableBuffer, SizedBuffer, StrOrBytesPath, WriteableBuffer from io import FileIO, TextIOWrapper -from typing import Final, Literal, Protocol, overload, type_check_only -from typing_extensions import TypeAlias, deprecated +from typing import Final, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import deprecated if sys.version_info >= (3, 14): from compression._common._streams import BaseStream, DecompressReader @@ -96,6 +96,7 @@ class GzipFile(BaseStream): name: str compress: zlib._Compress fileobj: _ReadableFileobj | _WritableFileobj + @overload def __init__( self, @@ -141,6 +142,7 @@ class GzipFile(BaseStream): fileobj: _ReadableFileobj | _WritableFileobj | None = None, mtime: float | None = None, ) -> None: ... + if sys.version_info < (3, 12): @property @deprecated("Deprecated since Python 2.6; removed in Python 3.12. Use `name` attribute instead.") @@ -167,7 +169,10 @@ class GzipFile(BaseStream): class _GzipReader(DecompressReader): def __init__(self, fp: _ReadableFileobj) -> None: ... -if sys.version_info >= (3, 14): +if sys.version_info >= (3, 15): + def compress(data: SizedBuffer, compresslevel: int = 6, *, mtime: float = 0) -> bytes: ... + +elif sys.version_info >= (3, 14): def compress(data: SizedBuffer, compresslevel: int = 9, *, mtime: float = 0) -> bytes: ... else: diff --git a/mypy/typeshed/stdlib/hashlib.pyi b/mypy/typeshed/stdlib/hashlib.pyi index 1763c23182736..50bc8e21f1d52 100644 --- a/mypy/typeshed/stdlib/hashlib.pyi +++ b/mypy/typeshed/stdlib/hashlib.pyi @@ -22,7 +22,7 @@ from _typeshed import ReadableBuffer from collections.abc import Callable, Set as AbstractSet from typing import Protocol, type_check_only -if sys.version_info >= (3, 11): +if sys.version_info >= (3, 15): __all__ = ( "md5", "sha1", @@ -41,8 +41,31 @@ if sys.version_info >= (3, 11): "new", "algorithms_guaranteed", "algorithms_available", + "file_digest", "pbkdf2_hmac", + "scrypt", + ) +elif sys.version_info >= (3, 11): + __all__ = ( + "md5", + "sha1", + "sha224", + "sha256", + "sha384", + "sha512", + "blake2b", + "blake2s", + "sha3_224", + "sha3_256", + "sha3_384", + "sha3_512", + "shake_128", + "shake_256", + "new", + "algorithms_guaranteed", + "algorithms_available", "file_digest", + "pbkdf2_hmac", ) else: __all__ = ( diff --git a/mypy/typeshed/stdlib/hmac.pyi b/mypy/typeshed/stdlib/hmac.pyi index 070c59b1c166d..9beabcc4dd92e 100644 --- a/mypy/typeshed/stdlib/hmac.pyi +++ b/mypy/typeshed/stdlib/hmac.pyi @@ -2,8 +2,7 @@ from _hashlib import _HashObject, compare_digest as compare_digest from _typeshed import ReadableBuffer, SizedBuffer from collections.abc import Callable from types import ModuleType -from typing import overload -from typing_extensions import TypeAlias +from typing import TypeAlias, overload _DigestMod: TypeAlias = str | Callable[[], _HashObject] | ModuleType diff --git a/mypy/typeshed/stdlib/html/__init__.pyi b/mypy/typeshed/stdlib/html/__init__.pyi index afba90832535d..8ad72f1265882 100644 --- a/mypy/typeshed/stdlib/html/__init__.pyi +++ b/mypy/typeshed/stdlib/html/__init__.pyi @@ -1,6 +1,4 @@ -from typing import AnyStr - __all__ = ["escape", "unescape"] -def escape(s: AnyStr, quote: bool = True) -> AnyStr: ... -def unescape(s: AnyStr) -> AnyStr: ... +def escape(s: str, quote: bool = True) -> str: ... +def unescape(s: str) -> str: ... diff --git a/mypy/typeshed/stdlib/http/client.pyi b/mypy/typeshed/stdlib/http/client.pyi index 699ef0e4c6d65..d22335b56c547 100644 --- a/mypy/typeshed/stdlib/http/client.pyi +++ b/mypy/typeshed/stdlib/http/client.pyi @@ -7,8 +7,8 @@ from _typeshed import MaybeNone, ReadableBuffer, StrOrBytesPath, SupportsRead, S from collections.abc import Callable, Iterable, Iterator, Mapping from email._policybase import _MessageT from socket import socket -from typing import BinaryIO, Final, TypeVar, overload -from typing_extensions import Self, TypeAlias, deprecated +from typing import BinaryIO, Final, TypeAlias, TypeVar, overload +from typing_extensions import Self, deprecated __all__ = [ "HTTPResponse", @@ -149,10 +149,12 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore[misc] # incomp def read1(self, n: int = -1) -> bytes: ... def readinto(self, b: WriteableBuffer) -> int: ... def readline(self, limit: int = -1) -> bytes: ... # type: ignore[override] + @overload def getheader(self, name: str) -> str | None: ... @overload def getheader(self, name: str, default: _T) -> str | _T: ... + def getheaders(self) -> list[tuple[str, str]]: ... def isclosed(self) -> bool: ... def __iter__(self) -> Iterator[bytes]: ... @@ -178,14 +180,27 @@ class HTTPConnection: host: str port: int sock: socket | MaybeNone # can be `None` if `.connect()` was not called - def __init__( - self, - host: str, - port: int | None = None, - timeout: float | None = ..., - source_address: tuple[str, int] | None = None, - blocksize: int = 8192, - ) -> None: ... + if sys.version_info >= (3, 15): + def __init__( + self, + host: str, + port: int | None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + *, + max_response_headers: int | None = None, + ) -> None: ... + else: + def __init__( + self, + host: str, + port: int | None = None, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + blocksize: int = 8192, + ) -> None: ... + def request( self, method: str, @@ -211,7 +226,19 @@ class HTTPConnection: class HTTPSConnection(HTTPConnection): # Can be `None` if `.connect()` was not called: sock: ssl.SSLSocket | MaybeNone - if sys.version_info >= (3, 12): + if sys.version_info >= (3, 15): + def __init__( + self, + host: str, + port: int | None = None, + *, + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + context: ssl.SSLContext | None = None, + blocksize: int = 8192, + max_response_headers: int | None = None, + ) -> None: ... + elif sys.version_info >= (3, 12): def __init__( self, host: str, @@ -255,6 +282,7 @@ class HTTPSConnection(HTTPConnection): check_hostname: bool | None = None, blocksize: int = 8192, ) -> None: ... + key_file: StrOrBytesPath | None cert_file: StrOrBytesPath | None diff --git a/mypy/typeshed/stdlib/http/cookiejar.pyi b/mypy/typeshed/stdlib/http/cookiejar.pyi index 31e1d3fc83785..2cbe432c55866 100644 --- a/mypy/typeshed/stdlib/http/cookiejar.pyi +++ b/mypy/typeshed/stdlib/http/cookiejar.pyi @@ -1,4 +1,3 @@ -import sys from _typeshed import StrPath from collections.abc import Iterator, Sequence from http.client import HTTPResponse @@ -49,9 +48,7 @@ class FileCookieJar(CookieJar): def load(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: ... def revert(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: ... -class MozillaCookieJar(FileCookieJar): - if sys.version_info < (3, 10): - header: ClassVar[str] # undocumented +class MozillaCookieJar(FileCookieJar): ... class LWPCookieJar(FileCookieJar): def as_lwp_str(self, ignore_discard: bool = True, ignore_expires: bool = True) -> str: ... # undocumented @@ -151,9 +148,11 @@ class Cookie: rfc2109: bool = False, ) -> None: ... def has_nonstandard_attr(self, name: str) -> bool: ... + @overload def get_nonstandard_attr(self, name: str) -> str | None: ... @overload def get_nonstandard_attr(self, name: str, default: _T) -> str | _T: ... + def set_nonstandard_attr(self, name: str, value: str) -> None: ... def is_expired(self, now: int | None = None) -> bool: ... diff --git a/mypy/typeshed/stdlib/http/cookies.pyi b/mypy/typeshed/stdlib/http/cookies.pyi index eadf054c3a5f4..bdec1068b5ea0 100644 --- a/mypy/typeshed/stdlib/http/cookies.pyi +++ b/mypy/typeshed/stdlib/http/cookies.pyi @@ -1,18 +1,17 @@ -from _typeshed import MaybeNone -from collections.abc import Iterable, Mapping +from _typeshed import MaybeNone, SupportsItems, SupportsKeysAndGetItem +from collections.abc import Container, Iterable from types import GenericAlias from typing import Any, Generic, TypeVar, overload -from typing_extensions import TypeAlias __all__ = ["CookieError", "BaseCookie", "SimpleCookie"] -_DataType: TypeAlias = str | Mapping[str, str | Morsel[Any]] _T = TypeVar("_T") @overload def _quote(str: None) -> None: ... @overload def _quote(str: str) -> str: ... + @overload def _unquote(str: None) -> None: ... @overload @@ -31,27 +30,24 @@ class Morsel(dict[str, Any], Generic[_T]): def set(self, key: str, val: str, coded_val: _T) -> None: ... def setdefault(self, key: str, val: str | None = None) -> str: ... # The dict update can also get a keywords argument so this is incompatible - @overload # type: ignore[override] - def update(self, values: Mapping[str, str]) -> None: ... - @overload - def update(self, values: Iterable[tuple[str, str]]) -> None: ... + def update(self, values: Iterable[tuple[str, str]] | SupportsKeysAndGetItem[str, str]) -> None: ... # type: ignore[override] def isReservedKey(self, K: str) -> bool: ... - def output(self, attrs: list[str] | None = None, header: str = "Set-Cookie:") -> str: ... + def output(self, attrs: Container[str] | None = None, header: str = "Set-Cookie:") -> str: ... __str__ = output - def js_output(self, attrs: list[str] | None = None) -> str: ... - def OutputString(self, attrs: list[str] | None = None) -> str: ... + def js_output(self, attrs: Container[str] | None = None) -> str: ... + def OutputString(self, attrs: Container[str] | None = None) -> str: ... def __eq__(self, morsel: object) -> bool: ... def __setitem__(self, K: str, V: Any) -> None: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class BaseCookie(dict[str, Morsel[_T]], Generic[_T]): - def __init__(self, input: _DataType | None = None) -> None: ... + def __init__(self, input: str | SupportsItems[str, str | Morsel[Any]] | None = None) -> None: ... def value_decode(self, val: str) -> tuple[_T, str]: ... def value_encode(self, val: _T) -> tuple[str, str]: ... - def output(self, attrs: list[str] | None = None, header: str = "Set-Cookie:", sep: str = "\r\n") -> str: ... + def output(self, attrs: Container[str] | None = None, header: str = "Set-Cookie:", sep: str = "\r\n") -> str: ... __str__ = output - def js_output(self, attrs: list[str] | None = None) -> str: ... - def load(self, rawdata: _DataType) -> None: ... + def js_output(self, attrs: Container[str] | None = None) -> str: ... + def load(self, rawdata: str | SupportsItems[str, str | Morsel[Any]]) -> None: ... def __setitem__(self, key: str, value: str | Morsel[_T]) -> None: ... class SimpleCookie(BaseCookie[str]): ... diff --git a/mypy/typeshed/stdlib/http/server.pyi b/mypy/typeshed/stdlib/http/server.pyi index 2c1a374331bcc..88cd2469cf115 100644 --- a/mypy/typeshed/stdlib/http/server.pyi +++ b/mypy/typeshed/stdlib/http/server.pyi @@ -10,18 +10,11 @@ from ssl import Purpose, SSLContext from typing import Any, AnyStr, BinaryIO, ClassVar, Protocol, type_check_only from typing_extensions import Self, deprecated +__all__ = ["HTTPServer", "ThreadingHTTPServer", "BaseHTTPRequestHandler", "SimpleHTTPRequestHandler"] +if sys.version_info < (3, 15): + __all__ += ["CGIHTTPRequestHandler"] if sys.version_info >= (3, 14): - __all__ = [ - "HTTPServer", - "ThreadingHTTPServer", - "HTTPSServer", - "ThreadingHTTPSServer", - "BaseHTTPRequestHandler", - "SimpleHTTPRequestHandler", - "CGIHTTPRequestHandler", - ] -else: - __all__ = ["HTTPServer", "ThreadingHTTPServer", "BaseHTTPRequestHandler", "SimpleHTTPRequestHandler", "CGIHTTPRequestHandler"] + __all__ = ["HTTPSServer", "ThreadingHTTPSServer"] class HTTPServer(socketserver.TCPServer): server_name: str @@ -77,6 +70,8 @@ class BaseHTTPRequestHandler(socketserver.StreamRequestHandler): protocol_version: str MessageClass: type responses: Mapping[int, tuple[str, str]] + if sys.version_info >= (3, 15): + default_content_type: str default_request_version: str # undocumented weekdayname: ClassVar[Sequence[str]] # undocumented monthname: ClassVar[Sequence[str | None]] # undocumented @@ -102,14 +97,26 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): if sys.version_info >= (3, 12): index_pages: ClassVar[tuple[str, ...]] directory: str - def __init__( - self, - request: socketserver._RequestType, - client_address: _socket._RetAddress, - server: socketserver.BaseServer, - *, - directory: StrPath | None = None, - ) -> None: ... + if sys.version_info >= (3, 15): + def __init__( + self, + request: socketserver._RequestType, + client_address: _socket._RetAddress, + server: socketserver.BaseServer, + *, + directory: StrPath | None = None, + extra_response_headers: Mapping[str, str] | None = None, + ) -> None: ... + else: + def __init__( + self, + request: socketserver._RequestType, + client_address: _socket._RetAddress, + server: socketserver.BaseServer, + *, + directory: StrPath | None = None, + ) -> None: ... + def do_GET(self) -> None: ... def do_HEAD(self) -> None: ... def send_head(self) -> io.BytesIO | BinaryIO | None: ... # undocumented @@ -120,7 +127,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def executable(path: StrPath) -> bool: ... # undocumented -if sys.version_info >= (3, 13): +if sys.version_info < (3, 15): @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): cgi_directories: list[str] @@ -130,13 +137,3 @@ if sys.version_info >= (3, 13): def is_executable(self, path: StrPath) -> bool: ... # undocumented def is_python(self, path: StrPath) -> bool: ... # undocumented def run_cgi(self) -> None: ... # undocumented - -else: - class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): - cgi_directories: list[str] - have_fork: bool # undocumented - def do_POST(self) -> None: ... - def is_cgi(self) -> bool: ... # undocumented - def is_executable(self, path: StrPath) -> bool: ... # undocumented - def is_python(self, path: StrPath) -> bool: ... # undocumented - def run_cgi(self) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/imaplib.pyi b/mypy/typeshed/stdlib/imaplib.pyi index 94b96f0a1283c..fd14e45ed725f 100644 --- a/mypy/typeshed/stdlib/imaplib.pyi +++ b/mypy/typeshed/stdlib/imaplib.pyi @@ -9,8 +9,8 @@ from re import Pattern from socket import socket as _socket from ssl import SSLContext, SSLSocket from types import TracebackType -from typing import IO, Any, Literal, SupportsAbs, SupportsInt, overload -from typing_extensions import Self, TypeAlias, deprecated +from typing import IO, Any, Literal, SupportsAbs, SupportsInt, TypeAlias, overload +from typing_extensions import Self, deprecated __all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple", "Int2AP", "ParseFlags", "Time2Internaldate", "IMAP4_SSL"] @@ -151,6 +151,7 @@ class IMAP4_SSL(IMAP4): ssl_context: None = None, timeout: float | None = None, ) -> None: ... + keyfile: StrOrBytesPath | None certfile: StrOrBytesPath | None sslobj: SSLSocket diff --git a/mypy/typeshed/stdlib/importlib/_abc.pyi b/mypy/typeshed/stdlib/importlib/_abc.pyi index 90ab340219172..e8c80c0447aed 100644 --- a/mypy/typeshed/stdlib/importlib/_abc.pyi +++ b/mypy/typeshed/stdlib/importlib/_abc.pyi @@ -4,17 +4,16 @@ from abc import ABCMeta from importlib.machinery import ModuleSpec from typing_extensions import deprecated -if sys.version_info >= (3, 10): - class Loader(metaclass=ABCMeta): - def load_module(self, fullname: str) -> types.ModuleType: ... - if sys.version_info < (3, 12): - @deprecated( - "Deprecated since Python 3.4; removed in Python 3.12. " - "The module spec is now used by the import machinery to generate a module repr." - ) - def module_repr(self, module: types.ModuleType) -> str: ... +class Loader(metaclass=ABCMeta): + def load_module(self, fullname: str) -> types.ModuleType: ... + if sys.version_info < (3, 12): + @deprecated( + "Deprecated since Python 3.4; removed in Python 3.12. " + "The module spec is now used by the import machinery to generate a module repr." + ) + def module_repr(self, module: types.ModuleType) -> str: ... - def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: ... - # Not defined on the actual class for backwards-compatibility reasons, - # but expected in new code. - def exec_module(self, module: types.ModuleType) -> None: ... + def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: ... + # Not defined on the actual class for backwards-compatibility reasons, + # but expected in new code. + def exec_module(self, module: types.ModuleType) -> None: ... diff --git a/mypy/typeshed/stdlib/importlib/abc.pyi b/mypy/typeshed/stdlib/importlib/abc.pyi index ef7761f7119b9..945b8d2080d1f 100644 --- a/mypy/typeshed/stdlib/importlib/abc.pyi +++ b/mypy/typeshed/stdlib/importlib/abc.pyi @@ -5,6 +5,7 @@ from _typeshed import ReadableBuffer, StrPath from abc import ABCMeta, abstractmethod from collections.abc import Iterator, Mapping, Sequence from importlib import _bootstrap_external +from importlib._abc import Loader as Loader from importlib.machinery import ModuleSpec from io import BufferedReader from typing import IO, Any, Literal, Protocol, overload, runtime_checkable @@ -25,17 +26,6 @@ if sys.version_info >= (3, 11): if sys.version_info < (3, 12): __all__ += ["Finder", "ResourceReader", "Traversable", "TraversableResources"] -if sys.version_info >= (3, 10): - from importlib._abc import Loader as Loader -else: - class Loader(metaclass=ABCMeta): - def load_module(self, fullname: str) -> types.ModuleType: ... - def module_repr(self, module: types.ModuleType) -> str: ... - def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: ... - # Not defined on the actual class for backwards-compatibility reasons, - # but expected in new code. - def exec_module(self, module: types.ModuleType) -> None: ... - if sys.version_info < (3, 12): @deprecated("Deprecated since Python 3.3; removed in Python 3.12. Use `MetaPathFinder` or `PathEntryFinder` instead.") class Finder(metaclass=ABCMeta): ... @@ -67,47 +57,28 @@ class SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLo def get_source(self, fullname: str) -> str | None: ... def path_stats(self, path: str) -> Mapping[str, Any]: ... -# The base classes differ starting in 3.10: -if sys.version_info >= (3, 10): - # Please keep in sync with _typeshed.importlib.MetaPathFinderProtocol - class MetaPathFinder(metaclass=ABCMeta): - if sys.version_info < (3, 12): - @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `MetaPathFinder.find_spec()` instead.") - def find_module(self, fullname: str, path: Sequence[str] | None) -> Loader | None: ... - - def invalidate_caches(self) -> None: ... - # Not defined on the actual class, but expected to exist. - def find_spec( - self, fullname: str, path: Sequence[str] | None, target: types.ModuleType | None = ..., / - ) -> ModuleSpec | None: ... - - class PathEntryFinder(metaclass=ABCMeta): - if sys.version_info < (3, 12): - @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `PathEntryFinder.find_spec()` instead.") - def find_module(self, fullname: str) -> Loader | None: ... - @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.") - def find_loader(self, fullname: str) -> tuple[Loader | None, Sequence[str]]: ... - - def invalidate_caches(self) -> None: ... - # Not defined on the actual class, but expected to exist. - def find_spec(self, fullname: str, target: types.ModuleType | None = ...) -> ModuleSpec | None: ... - -else: - # Please keep in sync with _typeshed.importlib.MetaPathFinderProtocol - class MetaPathFinder(Finder): +# Please keep in sync with _typeshed.importlib.MetaPathFinderProtocol +class MetaPathFinder(metaclass=ABCMeta): + if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `MetaPathFinder.find_spec()` instead.") def find_module(self, fullname: str, path: Sequence[str] | None) -> Loader | None: ... - def invalidate_caches(self) -> None: ... - # Not defined on the actual class, but expected to exist. - def find_spec( - self, fullname: str, path: Sequence[str] | None, target: types.ModuleType | None = ..., / - ) -> ModuleSpec | None: ... - class PathEntryFinder(Finder): + def invalidate_caches(self) -> None: ... + # Not defined on the actual class, but expected to exist. + def find_spec( + self, fullname: str, path: Sequence[str] | None, target: types.ModuleType | None = ..., / + ) -> ModuleSpec | None: ... + +class PathEntryFinder(metaclass=ABCMeta): + if sys.version_info < (3, 12): + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `PathEntryFinder.find_spec()` instead.") def find_module(self, fullname: str) -> Loader | None: ... + @deprecated("Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.") def find_loader(self, fullname: str) -> tuple[Loader | None, Sequence[str]]: ... - def invalidate_caches(self) -> None: ... - # Not defined on the actual class, but expected to exist. - def find_spec(self, fullname: str, target: types.ModuleType | None = ...) -> ModuleSpec | None: ... + + def invalidate_caches(self) -> None: ... + # Not defined on the actual class, but expected to exist. + def find_spec(self, fullname: str, target: types.ModuleType | None = ...) -> ModuleSpec | None: ... class FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader, metaclass=ABCMeta): name: str @@ -123,13 +94,8 @@ if sys.version_info < (3, 11): def open_resource(self, resource: str) -> IO[bytes]: ... @abstractmethod def resource_path(self, resource: str) -> str: ... - if sys.version_info >= (3, 10): - @abstractmethod - def is_resource(self, path: str) -> bool: ... - else: - @abstractmethod - def is_resource(self, name: str) -> bool: ... - + @abstractmethod + def is_resource(self, path: str) -> bool: ... @abstractmethod def contents(self) -> Iterator[str]: ... @@ -141,6 +107,7 @@ if sys.version_info < (3, 11): def is_file(self) -> bool: ... @abstractmethod def iterdir(self) -> Iterator[Traversable]: ... + if sys.version_info >= (3, 11): @abstractmethod def joinpath(self, *descendants: str) -> Traversable: ... @@ -157,15 +124,11 @@ if sys.version_info < (3, 11): @overload @abstractmethod def open(self, mode: Literal["rb"]) -> IO[bytes]: ... + @property @abstractmethod def name(self) -> str: ... - if sys.version_info >= (3, 10): - def __truediv__(self, child: str, /) -> Traversable: ... - else: - @abstractmethod - def __truediv__(self, child: str, /) -> Traversable: ... - + def __truediv__(self, child: str, /) -> Traversable: ... @abstractmethod def read_bytes(self) -> bytes: ... @abstractmethod diff --git a/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi index bb1b22f11a624..866fd969e2fe5 100644 --- a/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi @@ -5,13 +5,12 @@ import types from _collections_abc import dict_keys, dict_values from _typeshed import StrPath from collections.abc import Iterable, Iterator, Mapping -from email.message import Message from importlib.abc import MetaPathFinder +from importlib.metadata._meta import PackageMetadata as PackageMetadata, SimplePath from os import PathLike -from pathlib import Path from re import Pattern -from typing import Any, ClassVar, Generic, NamedTuple, TypeVar, overload, type_check_only -from typing_extensions import Self, TypeAlias, deprecated, disjoint_base +from typing import Any, ClassVar, Generic, NamedTuple, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, deprecated, disjoint_base _T = TypeVar("_T") _KT = TypeVar("_KT") @@ -20,32 +19,32 @@ _VT = TypeVar("_VT") __all__ = [ "Distribution", "DistributionFinder", + "PackageMetadata", "PackageNotFoundError", "distribution", "distributions", "entry_points", "files", "metadata", + "packages_distributions", "requires", "version", ] -if sys.version_info >= (3, 10): - __all__ += ["PackageMetadata", "packages_distributions"] +if sys.version_info >= (3, 15): + __all__ += ["PackagePath", "MetadataNotFound", "SimplePath"] -if sys.version_info >= (3, 10): - from importlib.metadata._meta import PackageMetadata as PackageMetadata, SimplePath - def packages_distributions() -> Mapping[str, list[str]]: ... +_SimplePath: TypeAlias = SimplePath - _SimplePath: TypeAlias = SimplePath - -else: - _SimplePath: TypeAlias = Path +def packages_distributions() -> Mapping[str, list[str]]: ... class PackageNotFoundError(ModuleNotFoundError): @property def name(self) -> str: ... # type: ignore[override] +if sys.version_info >= (3, 15): + class MetadataNotFound(FileNotFoundError): ... + if sys.version_info >= (3, 13): _EntryPointBase = object elif sys.version_info >= (3, 11): @@ -104,19 +103,17 @@ else: def module(self) -> str: ... @property def attr(self) -> str: ... - if sys.version_info >= (3, 10): - dist: ClassVar[Distribution | None] - def matches( - self, - *, - name: str = ..., - value: str = ..., - group: str = ..., - module: str = ..., - attr: str = ..., - extras: list[str] = ..., - ) -> bool: ... # undocumented - + dist: ClassVar[Distribution | None] + def matches( + self, + *, + name: str = ..., + value: str = ..., + group: str = ..., + module: str = ..., + attr: str = ..., + extras: list[str] = ..., + ) -> bool: ... # undocumented def __hash__(self) -> int: ... def __iter__(self) -> Iterator[Any]: ... # result of iter((str, Self)), really @@ -139,7 +136,7 @@ if sys.version_info >= (3, 12): @property def groups(self) -> set[str]: ... -elif sys.version_info >= (3, 10): +else: class DeprecatedList(list[_T]): __slots__ = () @@ -162,15 +159,17 @@ elif sys.version_info >= (3, 10): @property def groups(self) -> set[str]: ... -if sys.version_info >= (3, 10) and sys.version_info < (3, 12): +if sys.version_info < (3, 12): class Deprecated(Generic[_KT, _VT]): def __getitem__(self, name: _KT) -> _VT: ... + @overload def get(self, name: _KT, default: None = None) -> _VT | None: ... @overload def get(self, name: _KT, default: _VT) -> _VT: ... @overload def get(self, name: _KT, default: _T) -> _VT | _T: ... + def __iter__(self) -> Iterator[_KT]: ... def __contains__(self, *args: object) -> bool: ... def keys(self) -> dict_keys[_KT, _VT]: ... @@ -184,6 +183,7 @@ if sys.version_info >= (3, 10) and sys.version_info < (3, 12): def groups(self) -> set[str]: ... @property def names(self) -> set[str]: ... + @overload def select(self) -> Self: ... @overload @@ -212,7 +212,9 @@ class FileHash: value: str def __init__(self, spec: str) -> None: ... -if sys.version_info >= (3, 12): +if sys.version_info >= (3, 15): + _distribution_parent = abc.ABC +elif sys.version_info >= (3, 12): class DeprecatedNonAbstract: ... _distribution_parent = DeprecatedNonAbstract else: @@ -225,6 +227,7 @@ class Distribution(_distribution_parent): def locate_file(self, path: StrPath) -> _SimplePath: ... @classmethod def from_name(cls, name: str) -> Distribution: ... + @overload @classmethod def discover(cls, *, context: DistributionFinder.Context) -> Iterable[Distribution]: ... @@ -233,29 +236,21 @@ class Distribution(_distribution_parent): def discover( cls, *, context: None = None, name: str | None = ..., path: list[str] = ..., **kwargs: Any ) -> Iterable[Distribution]: ... + @staticmethod def at(path: StrPath) -> PathDistribution: ... - - if sys.version_info >= (3, 10): - @property - def metadata(self) -> PackageMetadata: ... - @property - def entry_points(self) -> EntryPoints: ... - else: - @property - def metadata(self) -> Message: ... - @property - def entry_points(self) -> list[EntryPoint]: ... - + @property + def metadata(self) -> PackageMetadata: ... + @property + def entry_points(self) -> EntryPoints: ... @property def version(self) -> str: ... @property def files(self) -> list[PackagePath] | None: ... @property def requires(self) -> list[str] | None: ... - if sys.version_info >= (3, 10): - @property - def name(self) -> str: ... + @property + def name(self) -> str: ... if sys.version_info >= (3, 13): @property def origin(self) -> types.SimpleNamespace | None: ... @@ -276,7 +271,7 @@ class MetadataPathFinder(DistributionFinder): if sys.version_info >= (3, 11): @classmethod def invalidate_caches(cls) -> None: ... - elif sys.version_info >= (3, 10): + else: # Yes, this is an instance method that has a parameter named "cls" def invalidate_caches(cls) -> None: ... @@ -287,6 +282,7 @@ class PathDistribution(Distribution): def locate_file(self, path: StrPath) -> _SimplePath: ... def distribution(distribution_name: str) -> Distribution: ... + @overload def distributions(*, context: DistributionFinder.Context) -> Iterable[Distribution]: ... @overload @@ -294,18 +290,14 @@ def distributions( *, context: None = None, name: str | None = ..., path: list[str] = ..., **kwargs: Any ) -> Iterable[Distribution]: ... -if sys.version_info >= (3, 10): - def metadata(distribution_name: str) -> PackageMetadata: ... - -else: - def metadata(distribution_name: str) -> Message: ... +def metadata(distribution_name: str) -> PackageMetadata: ... if sys.version_info >= (3, 12): def entry_points( *, name: str = ..., value: str = ..., group: str = ..., module: str = ..., attr: str = ..., extras: list[str] = ... ) -> EntryPoints: ... -elif sys.version_info >= (3, 10): +else: @overload def entry_points() -> SelectableGroups: ... @overload @@ -313,9 +305,6 @@ elif sys.version_info >= (3, 10): *, name: str = ..., value: str = ..., group: str = ..., module: str = ..., attr: str = ..., extras: list[str] = ... ) -> EntryPoints: ... -else: - def entry_points() -> dict[str, list[EntryPoint]]: ... - def version(distribution_name: str) -> str: ... def files(distribution_name: str) -> list[PackagePath] | None: ... def requires(distribution_name: str) -> list[str] | None: ... diff --git a/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi b/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi index 9f791dab254fd..b9bad7b8a6b0e 100644 --- a/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi @@ -15,10 +15,12 @@ class PackageMetadata(Protocol): def __iter__(self) -> Iterator[str]: ... @property def json(self) -> dict[str, str | list[str]]: ... + @overload def get_all(self, name: str, failobj: None = None) -> list[Any] | None: ... @overload def get_all(self, name: str, failobj: _T) -> list[Any] | _T: ... + if sys.version_info >= (3, 12): @overload def get(self, name: str, failobj: None = None) -> str | None: ... diff --git a/mypy/typeshed/stdlib/importlib/readers.pyi b/mypy/typeshed/stdlib/importlib/readers.pyi index 0e7f7ce165c3d..50f06ea5434d5 100644 --- a/mypy/typeshed/stdlib/importlib/readers.pyi +++ b/mypy/typeshed/stdlib/importlib/readers.pyi @@ -7,66 +7,63 @@ import sys import zipfile from _typeshed import StrPath from collections.abc import Iterable, Iterator +from importlib._bootstrap_external import FileLoader from io import BufferedReader from typing import Literal, NoReturn, TypeVar from typing_extensions import Never - -if sys.version_info >= (3, 10): - from importlib._bootstrap_external import FileLoader - from zipimport import zipimporter +from zipimport import zipimporter if sys.version_info >= (3, 11): from importlib.resources import abc else: from importlib import abc -if sys.version_info >= (3, 10): - if sys.version_info >= (3, 11): - __all__ = ["FileReader", "ZipReader", "MultiplexedPath", "NamespaceReader"] +if sys.version_info >= (3, 11): + __all__ = ["FileReader", "ZipReader", "MultiplexedPath", "NamespaceReader"] - if sys.version_info < (3, 11): - _T = TypeVar("_T") +if sys.version_info < (3, 11): + _T = TypeVar("_T") - def remove_duplicates(items: Iterable[_T]) -> Iterator[_T]: ... + def remove_duplicates(items: Iterable[_T]) -> Iterator[_T]: ... - class FileReader(abc.TraversableResources): - path: pathlib.Path - def __init__(self, loader: FileLoader) -> None: ... - def resource_path(self, resource: StrPath) -> str: ... - def files(self) -> pathlib.Path: ... +class FileReader(abc.TraversableResources): + path: pathlib.Path + def __init__(self, loader: FileLoader) -> None: ... + def resource_path(self, resource: StrPath) -> str: ... + def files(self) -> pathlib.Path: ... - class ZipReader(abc.TraversableResources): - prefix: str - archive: str - def __init__(self, loader: zipimporter, module: str) -> None: ... - def open_resource(self, resource: str) -> BufferedReader: ... - def is_resource(self, path: StrPath) -> bool: ... - def files(self) -> zipfile.Path: ... +class ZipReader(abc.TraversableResources): + prefix: str + archive: str + def __init__(self, loader: zipimporter, module: str) -> None: ... + def open_resource(self, resource: str) -> BufferedReader: ... + def is_resource(self, path: StrPath) -> bool: ... + def files(self) -> zipfile.Path: ... - class MultiplexedPath(abc.Traversable): - def __init__(self, *paths: abc.Traversable) -> None: ... - def iterdir(self) -> Iterator[abc.Traversable]: ... - def read_bytes(self) -> NoReturn: ... - def read_text(self, *args: Never, **kwargs: Never) -> NoReturn: ... # type: ignore[override] - def is_dir(self) -> Literal[True]: ... - def is_file(self) -> Literal[False]: ... +class MultiplexedPath(abc.Traversable): + def __init__(self, *paths: abc.Traversable) -> None: ... + def iterdir(self) -> Iterator[abc.Traversable]: ... + def read_bytes(self) -> NoReturn: ... + def read_text(self, *args: Never, **kwargs: Never) -> NoReturn: ... # type: ignore[override] + def is_dir(self) -> Literal[True]: ... + def is_file(self) -> Literal[False]: ... - if sys.version_info >= (3, 12): - def joinpath(self, *descendants: StrPath) -> abc.Traversable: ... - elif sys.version_info >= (3, 11): - def joinpath(self, child: StrPath) -> abc.Traversable: ... # type: ignore[override] - else: - def joinpath(self, child: str) -> abc.Traversable: ... + if sys.version_info >= (3, 12): + def joinpath(self, *descendants: StrPath) -> abc.Traversable: ... + elif sys.version_info >= (3, 11): + def joinpath(self, child: StrPath) -> abc.Traversable: ... # type: ignore[override] + else: + def joinpath(self, child: str) -> abc.Traversable: ... - if sys.version_info < (3, 12): - __truediv__ = joinpath + if sys.version_info < (3, 12): + __truediv__ = joinpath - def open(self, *args: Never, **kwargs: Never) -> NoReturn: ... # type: ignore[override] - @property - def name(self) -> str: ... + def open(self, *args: Never, **kwargs: Never) -> NoReturn: ... # type: ignore[override] + @property + def name(self) -> str: ... - class NamespaceReader(abc.TraversableResources): - path: MultiplexedPath - def __init__(self, namespace_path: Iterable[str]) -> None: ... - def resource_path(self, resource: str) -> str: ... - def files(self) -> MultiplexedPath: ... +class NamespaceReader(abc.TraversableResources): + path: MultiplexedPath + def __init__(self, namespace_path: Iterable[str]) -> None: ... + def resource_path(self, resource: str) -> str: ... + def files(self) -> MultiplexedPath: ... diff --git a/mypy/typeshed/stdlib/importlib/resources/__init__.pyi b/mypy/typeshed/stdlib/importlib/resources/__init__.pyi index 28adc37da4a42..5e58ddf310c93 100644 --- a/mypy/typeshed/stdlib/importlib/resources/__init__.pyi +++ b/mypy/typeshed/stdlib/importlib/resources/__init__.pyi @@ -4,8 +4,8 @@ from collections.abc import Iterator from contextlib import AbstractContextManager from pathlib import Path from types import ModuleType -from typing import Any, BinaryIO, Literal, TextIO -from typing_extensions import TypeAlias, deprecated +from typing import Any, BinaryIO, Literal, TextIO, TypeAlias +from typing_extensions import deprecated if sys.version_info >= (3, 11): from importlib.resources.abc import Traversable @@ -19,6 +19,7 @@ else: __all__ = [ "Package", + "ResourceReader", "as_file", "contents", "files", @@ -30,9 +31,6 @@ __all__ = [ "read_text", ] -if sys.version_info >= (3, 10): - __all__ += ["ResourceReader"] - if sys.version_info < (3, 13): __all__ += ["Resource"] @@ -64,11 +62,8 @@ else: def read_text(package: Package, resource: Resource, encoding: str = "utf-8", errors: str = "strict") -> str: ... def path(package: Package, resource: Resource) -> AbstractContextManager[Path, Literal[False]]: ... def is_resource(package: Package, name: str) -> bool: ... - if sys.version_info >= (3, 11): - @deprecated("Deprecated since Python 3.11. Use `files(anchor).iterdir()`.") - def contents(package: Package) -> Iterator[str]: ... - else: - def contents(package: Package) -> Iterator[str]: ... + @deprecated("Deprecated since Python 3.11. Use `files(anchor).iterdir()`.") + def contents(package: Package) -> Iterator[str]: ... if sys.version_info >= (3, 11): from importlib.resources._common import as_file as as_file @@ -82,5 +77,5 @@ else: if sys.version_info >= (3, 11): from importlib.resources.abc import ResourceReader as ResourceReader -elif sys.version_info >= (3, 10): +else: from importlib.abc import ResourceReader as ResourceReader diff --git a/mypy/typeshed/stdlib/importlib/resources/_common.pyi b/mypy/typeshed/stdlib/importlib/resources/_common.pyi index 11a93ca82d8df..447cc1ea33b89 100644 --- a/mypy/typeshed/stdlib/importlib/resources/_common.pyi +++ b/mypy/typeshed/stdlib/importlib/resources/_common.pyi @@ -7,8 +7,8 @@ if sys.version_info >= (3, 11): from contextlib import AbstractContextManager from importlib.resources.abc import ResourceReader, Traversable from pathlib import Path - from typing import Literal, overload - from typing_extensions import TypeAlias, deprecated + from typing import Literal, TypeAlias, overload + from typing_extensions import deprecated Package: TypeAlias = str | types.ModuleType @@ -18,6 +18,7 @@ if sys.version_info >= (3, 11): def package_to_anchor( func: Callable[[Anchor | None], Traversable], ) -> Callable[[Anchor | None, Anchor | None], Traversable]: ... + @overload def files(anchor: Anchor | None = None) -> Traversable: ... @overload diff --git a/mypy/typeshed/stdlib/importlib/resources/_functional.pyi b/mypy/typeshed/stdlib/importlib/resources/_functional.pyi index 71e01bcd3d5ec..cfd15dc87ce85 100644 --- a/mypy/typeshed/stdlib/importlib/resources/_functional.pyi +++ b/mypy/typeshed/stdlib/importlib/resources/_functional.pyi @@ -12,19 +12,23 @@ if sys.version_info >= (3, 13): from typing_extensions import Unpack, deprecated def open_binary(anchor: Anchor, *path_names: StrPath) -> BinaryIO: ... + @overload def open_text( anchor: Anchor, *path_names: Unpack[tuple[StrPath]], encoding: str | None = "utf-8", errors: str | None = "strict" ) -> TextIOWrapper: ... @overload def open_text(anchor: Anchor, *path_names: StrPath, encoding: str | None, errors: str | None = "strict") -> TextIOWrapper: ... + def read_binary(anchor: Anchor, *path_names: StrPath) -> bytes: ... + @overload def read_text( anchor: Anchor, *path_names: Unpack[tuple[StrPath]], encoding: str | None = "utf-8", errors: str | None = "strict" ) -> str: ... @overload def read_text(anchor: Anchor, *path_names: StrPath, encoding: str | None, errors: str | None = "strict") -> str: ... + def path(anchor: Anchor, *path_names: StrPath) -> AbstractContextManager[Path, Literal[False]]: ... def is_resource(anchor: Anchor, *path_names: StrPath) -> bool: ... @deprecated("Deprecated since Python 3.11. Use `files(anchor).iterdir()`.") diff --git a/mypy/typeshed/stdlib/importlib/resources/abc.pyi b/mypy/typeshed/stdlib/importlib/resources/abc.pyi index 477339ea74291..20a4b1fc5dfef 100644 --- a/mypy/typeshed/stdlib/importlib/resources/abc.pyi +++ b/mypy/typeshed/stdlib/importlib/resources/abc.pyi @@ -38,14 +38,20 @@ if sys.version_info >= (3, 11): @overload @abstractmethod def open(self, mode: Literal["rb"]) -> IO[bytes]: ... + @property @abstractmethod def name(self) -> str: ... def __truediv__(self, child: StrPath, /) -> Traversable: ... @abstractmethod def read_bytes(self) -> bytes: ... - @abstractmethod - def read_text(self, encoding: str | None = None) -> str: ... + + if sys.version_info >= (3, 15): + @abstractmethod + def read_text(self, encoding: str | None = None, errors: str | None = None) -> str: ... + else: + @abstractmethod + def read_text(self, encoding: str | None = None) -> str: ... class TraversableResources(ResourceReader): @abstractmethod diff --git a/mypy/typeshed/stdlib/importlib/resources/simple.pyi b/mypy/typeshed/stdlib/importlib/resources/simple.pyi index 946987c7312f9..ef9882056a9c2 100644 --- a/mypy/typeshed/stdlib/importlib/resources/simple.pyi +++ b/mypy/typeshed/stdlib/importlib/resources/simple.pyi @@ -27,6 +27,7 @@ if sys.version_info >= (3, 11): def __init__(self, parent: ResourceContainer, name: str) -> None: ... def is_file(self) -> Literal[True]: ... def is_dir(self) -> Literal[False]: ... + @overload def open( self, @@ -41,6 +42,7 @@ if sys.version_info >= (3, 11): def open(self, mode: Literal["rb"]) -> BinaryIO: ... @overload def open(self, mode: str) -> IO[Any]: ... + def joinpath(self, name: Never) -> NoReturn: ... # type: ignore[override] class ResourceContainer(Traversable, metaclass=abc.ABCMeta): diff --git a/mypy/typeshed/stdlib/importlib/util.pyi b/mypy/typeshed/stdlib/importlib/util.pyi index 577d3a667eca8..785ba6b9a08f0 100644 --- a/mypy/typeshed/stdlib/importlib/util.pyi +++ b/mypy/typeshed/stdlib/importlib/util.pyi @@ -13,8 +13,8 @@ from importlib._bootstrap_external import ( ) from importlib.abc import Loader from types import TracebackType -from typing import Literal -from typing_extensions import ParamSpec, Self, deprecated +from typing import Literal, ParamSpec +from typing_extensions import Self, deprecated _P = ParamSpec("_P") diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index c48d63bc4f322..0ca4cff75d7fd 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -25,8 +25,21 @@ from types import ( TracebackType, WrapperDescriptorType, ) -from typing import Any, ClassVar, Final, Literal, NamedTuple, Protocol, TypeVar, overload, type_check_only -from typing_extensions import ParamSpec, Self, TypeAlias, TypeGuard, TypeIs, deprecated, disjoint_base +from typing import ( + Any, + ClassVar, + Final, + Literal, + NamedTuple, + ParamSpec, + Protocol, + TypeAlias, + TypeGuard, + TypeVar, + overload, + type_check_only, +) +from typing_extensions import Self, TypeIs, deprecated, disjoint_base if sys.version_info >= (3, 14): from annotationlib import Format @@ -183,8 +196,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]] @@ -223,6 +236,7 @@ def isgeneratorfunction(obj: Callable[..., Generator[Any, Any, Any]]) -> bool: . def isgeneratorfunction(obj: Callable[_P, Any]) -> TypeGuard[Callable[_P, GeneratorType[Any, Any, Any]]]: ... @overload def isgeneratorfunction(obj: object) -> TypeGuard[Callable[..., GeneratorType[Any, Any, Any]]]: ... + @overload def iscoroutinefunction(obj: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ... @overload @@ -231,15 +245,18 @@ def iscoroutinefunction(obj: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[ def iscoroutinefunction(obj: Callable[_P, object]) -> TypeGuard[Callable[_P, CoroutineType[Any, Any, Any]]]: ... @overload def iscoroutinefunction(obj: object) -> TypeGuard[Callable[..., CoroutineType[Any, Any, Any]]]: ... + def isgenerator(object: object) -> TypeIs[GeneratorType[Any, Any, Any]]: ... def iscoroutine(object: object) -> TypeIs[CoroutineType[Any, Any, Any]]: ... def isawaitable(object: object) -> TypeIs[Awaitable[Any]]: ... + @overload def isasyncgenfunction(obj: Callable[..., AsyncGenerator[Any, Any]]) -> bool: ... @overload def isasyncgenfunction(obj: Callable[_P, Any]) -> TypeGuard[Callable[_P, AsyncGeneratorType[Any, Any]]]: ... @overload def isasyncgenfunction(obj: object) -> TypeGuard[Callable[..., AsyncGeneratorType[Any, Any]]]: ... + @type_check_only class _SupportsSet(Protocol[_T_contra, _V_contra]): def __set__(self, instance: _T_contra, value: _V_contra, /) -> None: ... @@ -293,7 +310,13 @@ def getblock(lines: list[str]) -> list[str]: ... def getblock(lines: tuple[str, ...]) -> tuple[str, ...]: ... @overload def getblock(lines: Sequence[str]) -> Sequence[str]: ... -def getdoc(object: object) -> str | None: ... + +if sys.version_info >= (3, 15): + def getdoc(object: object, *, inherit_class_doc: bool = True, fallback_to_class_doc: bool = True) -> str | None: ... + +else: + def getdoc(object: object) -> str | None: ... + def getcomments(object: object) -> str | None: ... def getfile(object: _SourceObjectType) -> str: ... def getmodule(object: object, _filename: str | None = None) -> ModuleType | None: ... @@ -319,7 +342,7 @@ if sys.version_info >= (3, 14): annotation_format: Format = Format.VALUE, # noqa: Y011 ) -> Signature: ... -elif sys.version_info >= (3, 10): +else: def signature( obj: _IntrospectableCallable, *, @@ -329,9 +352,6 @@ elif sys.version_info >= (3, 10): eval_str: bool = False, ) -> Signature: ... -else: - def signature(obj: _IntrospectableCallable, *, follow_wrapped: bool = True) -> Signature: ... - class _void: ... class _empty: ... @@ -361,7 +381,7 @@ class Signature: eval_str: bool = False, annotation_format: Format = Format.VALUE, # noqa: Y011 ) -> Self: ... - elif sys.version_info >= (3, 10): + else: @classmethod def from_callable( cls, @@ -372,9 +392,7 @@ class Signature: locals: Mapping[str, Any] | None = None, eval_str: bool = False, ) -> Self: ... - else: - @classmethod - def from_callable(cls, obj: _IntrospectableCallable, *, follow_wrapped: bool = True) -> Self: ... + if sys.version_info >= (3, 14): def format(self, *, max_width: int | None = None, quote_annotation_strings: bool = True) -> str: ... elif sys.version_info >= (3, 13): @@ -385,7 +403,7 @@ class Signature: if sys.version_info >= (3, 14): from annotationlib import get_annotations as get_annotations -elif sys.version_info >= (3, 10): +else: def get_annotations( obj: Callable[..., object] | type[object] | ModuleType, # any callable, class, or module *, @@ -498,7 +516,11 @@ class FullArgSpec(NamedTuple): kwonlydefaults: dict[str, Any] | None annotations: dict[str, Any] -def getfullargspec(func: object) -> FullArgSpec: ... +if sys.version_info >= (3, 15): + def getfullargspec(func: object, *, annotation_format: Format = Format.VALUE) -> FullArgSpec: ... # noqa: Y011 + +else: + def getfullargspec(func: object) -> FullArgSpec: ... class ArgInfo(NamedTuple): args: list[str] diff --git a/mypy/typeshed/stdlib/ipaddress.pyi b/mypy/typeshed/stdlib/ipaddress.pyi index d09804cb93423..c514abfa569f9 100644 --- a/mypy/typeshed/stdlib/ipaddress.pyi +++ b/mypy/typeshed/stdlib/ipaddress.pyi @@ -1,7 +1,7 @@ import sys from collections.abc import Iterable, Iterator -from typing import Any, Final, Generic, Literal, TypeVar, overload -from typing_extensions import Self, TypeAlias +from typing import Any, Final, Generic, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self # Undocumented length constants IPV4LENGTH: Final = 32 @@ -235,7 +235,9 @@ def summarize_address_range(first: IPv6Address, last: IPv6Address) -> Iterator[I def summarize_address_range( first: IPv4Address | IPv6Address, last: IPv4Address | IPv6Address ) -> Iterator[IPv4Network] | Iterator[IPv6Network]: ... + def collapse_addresses(addresses: Iterable[_N]) -> Iterator[_N]: ... + @overload def get_mixed_type_key(obj: _A) -> tuple[int, _A]: ... @overload diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index 4713d62cc346f..fd7daf11e8086 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import MaybeNone from collections.abc import Callable, Iterable, Iterator from types import GenericAlias -from typing import Any, Generic, Literal, SupportsComplex, SupportsFloat, SupportsIndex, SupportsInt, TypeVar, overload -from typing_extensions import Self, TypeAlias, disjoint_base +from typing import Any, Generic, Literal, SupportsComplex, SupportsFloat, SupportsIndex, SupportsInt, TypeAlias, TypeVar, overload +from typing_extensions import Self, disjoint_base _T = TypeVar("_T") _S = TypeVar("_S") @@ -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 @@ -35,6 +35,7 @@ class count(Iterator[_N]): def __new__(cls, start: _N, step: _Step = 1) -> count[_N]: ... @overload def __new__(cls, *, step: _N) -> count[_N]: ... + def __next__(self) -> _N: ... def __iter__(self) -> Self: ... @@ -50,6 +51,7 @@ class repeat(Iterator[_T]): def __new__(cls, object: _T) -> Self: ... @overload def __new__(cls, object: _T, times: int) -> Self: ... + def __next__(self) -> _T: ... def __iter__(self) -> Self: ... def __length_hint__(self) -> int: ... @@ -60,6 +62,7 @@ class accumulate(Iterator[_T]): def __new__(cls, iterable: Iterable[_T], func: None = None, *, initial: _T | None = None) -> Self: ... @overload def __new__(cls, iterable: Iterable[_S], func: Callable[[_T, _S], _T], *, initial: _T | None = None) -> Self: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T: ... @@ -97,6 +100,7 @@ class groupby(Iterator[tuple[_T_co, Iterator[_S_co]]], Generic[_T_co, _S_co]): def __new__(cls, iterable: Iterable[_T1], key: None = None) -> groupby[_T1, _T1]: ... @overload def __new__(cls, iterable: Iterable[_T1], key: Callable[[_T1], _T2]) -> groupby[_T2, _T1]: ... + def __iter__(self) -> Self: ... def __next__(self) -> tuple[_T_co, Iterator[_S_co]]: ... @@ -106,6 +110,7 @@ class islice(Iterator[_T]): def __new__(cls, iterable: Iterable[_T], stop: int | None, /) -> Self: ... @overload def __new__(cls, iterable: Iterable[_T], start: int | None, stop: int | None, step: int | None = 1, /) -> Self: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T: ... @@ -122,6 +127,7 @@ class takewhile(Iterator[_T]): def __next__(self) -> _T: ... def tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]: ... + @disjoint_base class zip_longest(Iterator[_T_co]): # one iterable (fillvalue doesn't matter) @@ -198,6 +204,7 @@ class zip_longest(Iterator[_T_co]): *iterables: Iterable[_T], fillvalue: _T, ) -> zip_longest[tuple[_T, ...]]: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... @@ -284,6 +291,7 @@ class product(Iterator[_T_co]): ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9, _T10]]: ... @overload def __new__(cls, *iterables: Iterable[_T1], repeat: int = 1) -> product[tuple[_T1, ...]]: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... @@ -299,6 +307,7 @@ class permutations(Iterator[_T_co]): def __new__(cls, iterable: Iterable[_T], r: Literal[5]) -> permutations[tuple[_T, _T, _T, _T, _T]]: ... @overload def __new__(cls, iterable: Iterable[_T], r: int | None = None) -> permutations[tuple[_T, ...]]: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... @@ -314,6 +323,7 @@ class combinations(Iterator[_T_co]): def __new__(cls, iterable: Iterable[_T], r: Literal[5]) -> combinations[tuple[_T, _T, _T, _T, _T]]: ... @overload def __new__(cls, iterable: Iterable[_T], r: int) -> combinations[tuple[_T, ...]]: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... @@ -329,15 +339,15 @@ class combinations_with_replacement(Iterator[_T_co]): def __new__(cls, iterable: Iterable[_T], r: Literal[5]) -> combinations_with_replacement[tuple[_T, _T, _T, _T, _T]]: ... @overload def __new__(cls, iterable: Iterable[_T], r: int) -> combinations_with_replacement[tuple[_T, ...]]: ... + def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... -if sys.version_info >= (3, 10): - @disjoint_base - class pairwise(Iterator[_T_co]): - def __new__(cls, iterable: Iterable[_T], /) -> pairwise[tuple[_T, _T]]: ... - def __iter__(self) -> Self: ... - def __next__(self) -> _T_co: ... +@disjoint_base +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 diff --git a/mypy/typeshed/stdlib/json/__init__.pyi b/mypy/typeshed/stdlib/json/__init__.pyi index 454a235ecf703..2342b29cb0c82 100644 --- a/mypy/typeshed/stdlib/json/__init__.pyi +++ b/mypy/typeshed/stdlib/json/__init__.pyi @@ -1,3 +1,4 @@ +import sys from _typeshed import SupportsRead, SupportsWrite from collections.abc import Callable from typing import Any, Literal @@ -36,28 +37,57 @@ def dump( sort_keys: bool = False, **kwds: Any, ) -> None: ... -def loads( - s: str | bytes | bytearray, - *, - cls: type[JSONDecoder] | None = None, - object_hook: Callable[[dict[Any, Any]], Any] | None = None, - parse_float: Callable[[str], Any] | None = None, - parse_int: Callable[[str], Any] | None = None, - parse_constant: Callable[[str], Any] | None = None, - object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, - **kwds: Any, -) -> Any: ... -def load( - fp: SupportsRead[str | bytes], - *, - cls: type[JSONDecoder] | None = None, - object_hook: Callable[[dict[Any, Any]], Any] | None = None, - parse_float: Callable[[str], Any] | None = None, - parse_int: Callable[[str], Any] | None = None, - parse_constant: Callable[[str], Any] | None = None, - object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, - **kwds: Any, -) -> Any: ... + +if sys.version_info >= (3, 15): + def loads( + s: str | bytes | bytearray, + *, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + array_hook: Callable[[list[Any]], Any] | None = None, + **kwds: Any, + ) -> Any: ... + def load( + fp: SupportsRead[str | bytes], + *, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + array_hook: Callable[[list[Any]], Any] | None = None, + **kwds: Any, + ) -> Any: ... + +else: + def loads( + s: str | bytes | bytearray, + *, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + **kwds: Any, + ) -> Any: ... + def load( + fp: SupportsRead[str | bytes], + *, + cls: type[JSONDecoder] | None = None, + object_hook: Callable[[dict[Any, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, + **kwds: Any, + ) -> Any: ... + def detect_encoding( b: bytes | bytearray, ) -> Literal["utf-8", "utf-8-sig", "utf-16", "utf-16-be", "utf-16-le", "utf-32", "utf-32-be", "utf-32-le"]: ... # undocumented diff --git a/mypy/typeshed/stdlib/json/decoder.pyi b/mypy/typeshed/stdlib/json/decoder.pyi index 8debfe6cd65a9..1b09579fb0c41 100644 --- a/mypy/typeshed/stdlib/json/decoder.pyi +++ b/mypy/typeshed/stdlib/json/decoder.pyi @@ -1,3 +1,4 @@ +import sys from collections.abc import Callable from typing import Any @@ -12,21 +13,38 @@ class JSONDecodeError(ValueError): def __init__(self, msg: str, doc: str, pos: int) -> None: ... class JSONDecoder: + if sys.version_info >= (3, 15): + array_hook: Callable[[list[Any]], Any] | None object_hook: Callable[[dict[str, Any]], Any] parse_float: Callable[[str], Any] parse_int: Callable[[str], Any] parse_constant: Callable[[str], Any] strict: bool object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] - def __init__( - self, - *, - object_hook: Callable[[dict[str, Any]], Any] | None = None, - parse_float: Callable[[str], Any] | None = None, - parse_int: Callable[[str], Any] | None = None, - parse_constant: Callable[[str], Any] | None = None, - strict: bool = True, - object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None, - ) -> None: ... + if sys.version_info >= (3, 15): + def __init__( + self, + *, + object_hook: Callable[[dict[str, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + strict: bool = True, + object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None, + array_hook: Callable[[list[Any]], Any] | None = None, + ) -> None: ... + + else: + def __init__( + self, + *, + object_hook: Callable[[dict[str, Any]], Any] | None = None, + parse_float: Callable[[str], Any] | None = None, + parse_int: Callable[[str], Any] | None = None, + parse_constant: Callable[[str], Any] | None = None, + strict: bool = True, + object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None, + ) -> None: ... + def decode(self, s: str, _w: Callable[..., Any] = ...) -> Any: ... # _w is undocumented def raw_decode(self, s: str, idx: int = 0) -> tuple[Any, int]: ... diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi index de8a874f434d0..3b1cbef7727d2 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi @@ -1,6 +1,5 @@ from collections.abc import Callable -from typing import Any -from typing_extensions import TypeAlias +from typing import Any, TypeAlias from ..pytree import _RawNode from .grammar import Grammar diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi index bef0a7922683b..5093422ae2364 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi @@ -1,5 +1,6 @@ from _typeshed import StrPath -from typing_extensions import Self, TypeAlias +from typing import TypeAlias +from typing_extensions import Self _Label: TypeAlias = tuple[int, str | None] _DFA: TypeAlias = list[list[tuple[int, int]]] diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi index 320c5f018d43f..9befe9bf879d3 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi @@ -1,6 +1,6 @@ from _typeshed import Incomplete from collections.abc import Sequence -from typing_extensions import TypeAlias +from typing import TypeAlias from ..pytree import _NL, _RawNode from . import _Convert diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi index 5776d100d1da0..4b951e1489e15 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi @@ -29,6 +29,7 @@ class ParserGenerator: def parse_atom(self) -> tuple[NFAState, NFAState]: ... def expect(self, type: int, value: str | None = None) -> str: ... def gettoken(self) -> None: ... + @overload def raise_error(self, msg: object) -> NoReturn: ... @overload diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi index af54de1b51d33..76ff733163afe 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi @@ -1,5 +1,5 @@ from collections.abc import Callable, Iterable, Iterator -from typing_extensions import TypeAlias +from typing import TypeAlias from .token import * diff --git a/mypy/typeshed/stdlib/lib2to3/pytree.pyi b/mypy/typeshed/stdlib/lib2to3/pytree.pyi index 51bdbc75e1421..045f7882721a1 100644 --- a/mypy/typeshed/stdlib/lib2to3/pytree.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pytree.pyi @@ -1,8 +1,8 @@ from _typeshed import Incomplete, SupportsGetItem, SupportsLenAndGetItem, Unused from abc import abstractmethod from collections.abc import Iterable, Iterator, MutableSequence -from typing import ClassVar, Final -from typing_extensions import Self, TypeAlias +from typing import ClassVar, Final, TypeAlias +from typing_extensions import Self from .fixer_base import BaseFix from .pgen2.grammar import Grammar diff --git a/mypy/typeshed/stdlib/lib2to3/refactor.pyi b/mypy/typeshed/stdlib/lib2to3/refactor.pyi index c33347ede38fd..dfec28b758b5d 100644 --- a/mypy/typeshed/stdlib/lib2to3/refactor.pyi +++ b/mypy/typeshed/stdlib/lib2to3/refactor.pyi @@ -40,14 +40,17 @@ class RefactoringTool: ) -> None: ... def get_fixers(self) -> tuple[list[BaseFix], list[BaseFix]]: ... def log_error(self, msg: str, *args: Iterable[str], **kwargs: _ExcInfoType) -> NoReturn: ... + @overload def log_message(self, msg: object) -> None: ... @overload def log_message(self, msg: str, *args: object) -> None: ... + @overload def log_debug(self, msg: object) -> None: ... @overload def log_debug(self, msg: str, *args: object) -> None: ... + def print_output(self, old_text: str, new_text: str, filename: StrPath, equal: bool) -> None: ... def refactor(self, items: Iterable[str], write: bool = False, doctests_only: bool = False) -> None: ... def refactor_dir(self, dir_name: str, write: bool = False, doctests_only: bool = False) -> None: ... diff --git a/mypy/typeshed/stdlib/linecache.pyi b/mypy/typeshed/stdlib/linecache.pyi index 5379a21e7d123..f527e7084ced8 100644 --- a/mypy/typeshed/stdlib/linecache.pyi +++ b/mypy/typeshed/stdlib/linecache.pyi @@ -1,6 +1,5 @@ from collections.abc import Callable -from typing import Any -from typing_extensions import TypeAlias +from typing import Any, TypeAlias __all__ = ["getline", "clearcache", "checkcache", "lazycache"] diff --git a/mypy/typeshed/stdlib/locale.pyi b/mypy/typeshed/stdlib/locale.pyi index 80c39a532dc86..1be68ec516344 100644 --- a/mypy/typeshed/stdlib/locale.pyi +++ b/mypy/typeshed/stdlib/locale.pyi @@ -138,11 +138,8 @@ def getpreferredencoding(do_setlocale: bool = True) -> _str: ... def normalize(localename: _str) -> _str: ... if sys.version_info < (3, 13): - if sys.version_info >= (3, 11): - @deprecated("Deprecated since Python 3.11; removed in Python 3.13. Use `locale.setlocale(locale.LC_ALL, '')` instead.") - def resetlocale(category: int = ...) -> None: ... - else: - def resetlocale(category: int = ...) -> None: ... + @deprecated("Deprecated since Python 3.11; removed in Python 3.13. Use `locale.setlocale(locale.LC_ALL, '')` instead.") + def resetlocale(category: int = ...) -> None: ... if sys.version_info < (3, 12): @deprecated("Deprecated since Python 3.7; removed in Python 3.12. Use `locale.format_string()` instead.") @@ -153,10 +150,7 @@ if sys.version_info < (3, 12): def format_string(f: _str, val: Any, grouping: bool = False, monetary: bool = False) -> _str: ... def currency(val: float | Decimal, symbol: bool = True, grouping: bool = False, international: bool = False) -> _str: ... def delocalize(string: _str) -> _str: ... - -if sys.version_info >= (3, 10): - def localize(string: _str, grouping: bool = False, monetary: bool = False) -> _str: ... - +def localize(string: _str, grouping: bool = False, monetary: bool = False) -> _str: ... def atof(string: _str, func: Callable[[_str], float] = ...) -> float: ... def atoi(string: _str) -> int: ... def str(val: float) -> _str: ... diff --git a/mypy/typeshed/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index 89c94816a906c..8e90a68d9453c 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -7,8 +7,8 @@ from re import Pattern from string import Template from time import struct_time from types import FrameType, GenericAlias, TracebackType -from typing import Any, ClassVar, Final, Generic, Literal, Protocol, TextIO, TypeVar, overload, type_check_only -from typing_extensions import Self, TypeAlias, deprecated +from typing import Any, ClassVar, Final, Generic, Literal, Protocol, TextIO, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, deprecated __all__ = [ "BASIC_FORMAT", @@ -274,21 +274,15 @@ class Formatter: default_time_format: str default_msec_format: str | None - if sys.version_info >= (3, 10): - def __init__( - self, - fmt: str | None = None, - datefmt: str | None = None, - style: _FormatStyle = "%", - validate: bool = True, - *, - defaults: Mapping[str, Any] | None = None, - ) -> None: ... - else: - def __init__( - self, fmt: str | None = None, datefmt: str | None = None, style: _FormatStyle = "%", validate: bool = True - ) -> None: ... - + def __init__( + self, + fmt: str | None = None, + datefmt: str | None = None, + style: _FormatStyle = "%", + validate: bool = True, + *, + defaults: Mapping[str, Any] | None = None, + ) -> None: ... def format(self, record: LogRecord) -> str: ... def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str: ... def formatException(self, ei: _SysExcInfoType) -> str: ... @@ -362,18 +356,12 @@ _L = TypeVar("_L", bound=Logger | LoggerAdapter[Any]) class LoggerAdapter(Generic[_L]): logger: _L manager: Manager # undocumented + extra: Mapping[str, object] | None if sys.version_info >= (3, 13): def __init__(self, logger: _L, extra: Mapping[str, object] | None = None, merge_extra: bool = False) -> None: ... - elif sys.version_info >= (3, 10): - def __init__(self, logger: _L, extra: Mapping[str, object] | None = None) -> None: ... else: - def __init__(self, logger: _L, extra: Mapping[str, object]) -> None: ... - - if sys.version_info >= (3, 10): - extra: Mapping[str, object] | None - else: - extra: Mapping[str, object] + def __init__(self, logger: _L, extra: Mapping[str, object] | None = None) -> None: ... if sys.version_info >= (3, 13): merge_extra: bool @@ -566,6 +554,7 @@ fatal = critical def disable(level: int = 50) -> None: ... def addLevelName(level: int, levelName: str) -> None: ... + @overload def getLevelName(level: int) -> str: ... @overload @@ -576,6 +565,7 @@ if sys.version_info >= (3, 11): def getLevelNamesMapping() -> dict[str, int]: ... def makeLogRecord(dict: Mapping[str, object]) -> LogRecord: ... + @overload # handlers is non-None def basicConfig( *, @@ -611,6 +601,7 @@ def basicConfig( handlers: None = None, force: bool | None = False, ) -> None: ... + def shutdown(handlerList: Sequence[Any] = ...) -> None: ... # handlerList is undocumented def setLoggerClass(klass: type[Logger]) -> None: ... def captureWarnings(capture: bool) -> None: ... @@ -623,10 +614,12 @@ _StreamT = TypeVar("_StreamT", bound=SupportsWrite[str]) class StreamHandler(Handler, Generic[_StreamT]): stream: _StreamT # undocumented terminator: str + @overload def __init__(self: StreamHandler[TextIO], stream: None = None) -> None: ... @overload def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None: ... # pyright: ignore[reportInvalidTypeVarUse] #11780 + def setStream(self, stream: _StreamT) -> _StreamT | None: ... if sys.version_info >= (3, 11): def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @@ -663,11 +656,8 @@ class PercentStyle: # undocumented asctime_search: str validation_pattern: Pattern[str] _fmt: str - if sys.version_info >= (3, 10): - def __init__(self, fmt: str, *, defaults: Mapping[str, Any] | None = None) -> None: ... - else: - def __init__(self, fmt: str) -> None: ... + def __init__(self, fmt: str, *, defaults: Mapping[str, Any] | None = None) -> None: ... def usesTime(self) -> bool: ... def validate(self) -> None: ... def format(self, record: Any) -> str: ... diff --git a/mypy/typeshed/stdlib/logging/config.pyi b/mypy/typeshed/stdlib/logging/config.pyi index e362145516001..1c870edc80f8b 100644 --- a/mypy/typeshed/stdlib/logging/config.pyi +++ b/mypy/typeshed/stdlib/logging/config.pyi @@ -4,8 +4,8 @@ from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence from configparser import RawConfigParser from re import Pattern from threading import Thread -from typing import IO, Any, Final, Literal, SupportsIndex, TypedDict, overload, type_check_only -from typing_extensions import Required, TypeAlias, disjoint_base +from typing import IO, Any, Final, Literal, SupportsIndex, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Required, disjoint_base from . import Filter, Filterer, Formatter, Handler, Logger, _FilterType, _FormatStyle, _Level @@ -64,22 +64,12 @@ class _DictConfigArgs(TypedDict, total=False): # Also accept a TypedDict type, to allow callers to use TypedDict # types, and for somewhat stricter type checking of dict literals. def dictConfig(config: _DictConfigArgs | dict[str, Any]) -> None: ... - -if sys.version_info >= (3, 10): - def fileConfig( - fname: StrOrBytesPath | IO[str] | RawConfigParser, - defaults: Mapping[str, str] | None = None, - disable_existing_loggers: bool = True, - encoding: str | None = None, - ) -> None: ... - -else: - def fileConfig( - fname: StrOrBytesPath | IO[str] | RawConfigParser, - defaults: Mapping[str, str] | None = None, - disable_existing_loggers: bool = True, - ) -> None: ... - +def fileConfig( + fname: StrOrBytesPath | IO[str] | RawConfigParser, + defaults: Mapping[str, str] | None = None, + disable_existing_loggers: bool = True, + encoding: str | None = None, +) -> None: ... def valid_ident(s: str) -> Literal[True]: ... # undocumented def listen(port: int = 9030, verify: Callable[[bytes], bytes | None] | None = None) -> Thread: ... def stopListening() -> None: ... @@ -98,6 +88,7 @@ class ConvertingList(list[Any], ConvertingMixin): # undocumented def __getitem__(self, key: SupportsIndex) -> Any: ... @overload def __getitem__(self, key: slice[SupportsIndex | None]) -> Any: ... + def pop(self, idx: SupportsIndex = -1) -> Any: ... if sys.version_info >= (3, 12): diff --git a/mypy/typeshed/stdlib/lzma.pyi b/mypy/typeshed/stdlib/lzma.pyi index b7ef607b75cbf..656ecb168c956 100644 --- a/mypy/typeshed/stdlib/lzma.pyi +++ b/mypy/typeshed/stdlib/lzma.pyi @@ -36,8 +36,8 @@ from _lzma import ( ) from _typeshed import ReadableBuffer, StrOrBytesPath from io import TextIOWrapper -from typing import IO, Literal, overload -from typing_extensions import Self, TypeAlias +from typing import IO, Literal, TypeAlias, overload +from typing_extensions import Self if sys.version_info >= (3, 14): from compression._common._streams import BaseStream @@ -172,6 +172,7 @@ def open( errors: str | None = None, newline: str | None = None, ) -> LZMAFile | TextIOWrapper: ... + def compress( data: ReadableBuffer, format: int = 1, check: int = -1, preset: int | None = None, filters: _FilterChain | None = None ) -> bytes: ... diff --git a/mypy/typeshed/stdlib/mailbox.pyi b/mypy/typeshed/stdlib/mailbox.pyi index 89bd998b4dfeb..961c0f5e81f7a 100644 --- a/mypy/typeshed/stdlib/mailbox.pyi +++ b/mypy/typeshed/stdlib/mailbox.pyi @@ -1,13 +1,12 @@ import email.message import io import sys -from _typeshed import StrPath, SupportsNoArgReadline, SupportsRead +from _typeshed import StrPath, SupportsItems, SupportsNoArgReadline, SupportsRead, SupportsWrite, Unused from abc import ABCMeta, abstractmethod from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence -from email._policybase import _MessageT from types import GenericAlias, TracebackType -from typing import IO, Any, AnyStr, Generic, Literal, Protocol, TypeVar, overload, type_check_only -from typing_extensions import Self, TypeAlias +from typing import Any, Generic, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self __all__ = [ "Mailbox", @@ -34,25 +33,49 @@ _T = TypeVar("_T") @type_check_only class _SupportsReadAndReadline(SupportsRead[bytes], SupportsNoArgReadline[bytes], Protocol): ... +# As opposed to _MessageT_co in email._policybase, this type is bound to +# mailbox.Message instead of email.message.Message. +_MessageT_co = TypeVar("_MessageT_co", bound=Message, default=Message, covariant=True) + _MessageData: TypeAlias = email.message.Message | bytes | str | io.StringIO | _SupportsReadAndReadline @type_check_only class _HasIteritems(Protocol): def iteritems(self) -> Iterator[tuple[str, _MessageData]]: ... -@type_check_only -class _HasItems(Protocol): - def items(self) -> Iterator[tuple[str, _MessageData]]: ... - linesep: bytes -class Mailbox(Generic[_MessageT]): +# Common interface for get_file() return types. +@type_check_only +class _GetFileReturn(Protocol): + def __iter__(self) -> Iterator[bytes]: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, / + ) -> bool | None: ... + def read(self, size: int | None = None, /) -> bytes: ... + def read1(self, size: int | None = None, /) -> bytes: ... + def readline(self, size: int | None = None, /) -> bytes: ... + def readlines(self, sizehint: int | None = None, /) -> list[bytes]: ... + def tell(self) -> int: ... + def seek(self, offset: int, whence: int = 0, /) -> object: ... + def close(self) -> object: ... + def readable(self) -> bool: ... + def writable(self) -> bool: ... + def seekable(self) -> bool: ... + def flush(self) -> object: ... + @property + def closed(self) -> bool: ... + +class Mailbox(Generic[_MessageT_co]): _path: str # undocumented - _factory: Callable[[IO[Any]], _MessageT] | None # undocumented + _factory: Callable[[_GetFileReturn], _MessageT_co] | None # undocumented + @overload - def __init__(self, path: StrPath, factory: Callable[[IO[Any]], _MessageT], create: bool = True) -> None: ... + def __init__(self, path: StrPath, factory: Callable[[_GetFileReturn], _MessageT_co], create: bool = True) -> None: ... @overload def __init__(self, path: StrPath, factory: None = None, create: bool = True) -> None: ... + @abstractmethod def add(self, message: _MessageData) -> str: ... @abstractmethod @@ -61,38 +84,43 @@ class Mailbox(Generic[_MessageT]): def discard(self, key: str) -> None: ... @abstractmethod def __setitem__(self, key: str, message: _MessageData) -> None: ... + @overload - def get(self, key: str, default: None = None) -> _MessageT | None: ... + def get(self, key: str, default: None = None) -> _MessageT_co | None: ... @overload - def get(self, key: str, default: _T) -> _MessageT | _T: ... - def __getitem__(self, key: str) -> _MessageT: ... + def get(self, key: str, default: _T) -> _MessageT_co | _T: ... + + def __getitem__(self, key: str) -> _MessageT_co: ... @abstractmethod - def get_message(self, key: str) -> _MessageT: ... + def get_message(self, key: str) -> _MessageT_co: ... def get_string(self, key: str) -> str: ... @abstractmethod def get_bytes(self, key: str) -> bytes: ... - # As '_ProxyFile' doesn't implement the full IO spec, and BytesIO is incompatible with it, get_file return is Any here @abstractmethod - def get_file(self, key: str) -> Any: ... + def get_file(self, key: str) -> _GetFileReturn: ... @abstractmethod def iterkeys(self) -> Iterator[str]: ... def keys(self) -> list[str]: ... - def itervalues(self) -> Iterator[_MessageT]: ... - def __iter__(self) -> Iterator[_MessageT]: ... - def values(self) -> list[_MessageT]: ... - def iteritems(self) -> Iterator[tuple[str, _MessageT]]: ... - def items(self) -> list[tuple[str, _MessageT]]: ... + def itervalues(self) -> Iterator[_MessageT_co]: ... + def __iter__(self) -> Iterator[_MessageT_co]: ... + def values(self) -> list[_MessageT_co]: ... + def iteritems(self) -> Iterator[tuple[str, _MessageT_co]]: ... + def items(self) -> list[tuple[str, _MessageT_co]]: ... @abstractmethod def __contains__(self, key: str) -> bool: ... @abstractmethod def __len__(self) -> int: ... def clear(self) -> None: ... + @overload - def pop(self, key: str, default: None = None) -> _MessageT | None: ... + def pop(self, key: str, default: None = None) -> _MessageT_co | None: ... @overload - def pop(self, key: str, default: _T) -> _MessageT | _T: ... - def popitem(self) -> tuple[str, _MessageT]: ... - def update(self, arg: _HasIteritems | _HasItems | Iterable[tuple[str, _MessageData]] | None = None) -> None: ... + def pop(self, key: str, default: _T) -> _MessageT_co | _T: ... + + def popitem(self) -> tuple[str, _MessageT_co]: ... + def update( + self, arg: _HasIteritems | SupportsItems[str, _MessageData] | Iterable[tuple[str, _MessageData]] | None = None + ) -> None: ... @abstractmethod def flush(self) -> None: ... @abstractmethod @@ -101,19 +129,21 @@ class Mailbox(Generic[_MessageT]): def unlock(self) -> None: ... @abstractmethod def close(self) -> None: ... + # Undocumented, called by subclasses to parse added messages. + def _dump_message(self, message: _MessageData, target: SupportsWrite[bytes], mangle_from_: bool = False) -> None: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class Maildir(Mailbox[MaildirMessage]): colon: str def __init__( - self, dirname: StrPath, factory: Callable[[IO[Any]], MaildirMessage] | None = None, create: bool = True + self, dirname: StrPath, factory: Callable[[_GetFileReturn], MaildirMessage] | None = None, create: bool = True ) -> None: ... - def add(self, message: _MessageData) -> str: ... + def add(self, message: _MessageData | MaildirMessage) -> str: ... def remove(self, key: str) -> None: ... - def __setitem__(self, key: str, message: _MessageData) -> None: ... + def __setitem__(self, key: str, message: _MessageData | MaildirMessage) -> None: ... def get_message(self, key: str) -> MaildirMessage: ... def get_bytes(self, key: str) -> bytes: ... - def get_file(self, key: str) -> _ProxyFile[bytes]: ... + def get_file(self, key: str) -> _ProxyFile: ... if sys.version_info >= (3, 13): def get_info(self, key: str) -> str: ... def set_info(self, key: str, info: str) -> None: ... @@ -136,7 +166,7 @@ class Maildir(Mailbox[MaildirMessage]): def clean(self) -> None: ... def next(self) -> str | None: ... -class _singlefileMailbox(Mailbox[_MessageT], metaclass=ABCMeta): +class _singlefileMailbox(Mailbox[_MessageT_co], metaclass=ABCMeta): def add(self, message: _MessageData) -> str: ... def remove(self, key: str) -> None: ... def __setitem__(self, key: str, message: _MessageData) -> None: ... @@ -148,26 +178,32 @@ class _singlefileMailbox(Mailbox[_MessageT], metaclass=ABCMeta): def flush(self) -> None: ... def close(self) -> None: ... -class _mboxMMDF(_singlefileMailbox[_MessageT]): - def get_message(self, key: str) -> _MessageT: ... - def get_file(self, key: str, from_: bool = False) -> _PartialFile[bytes]: ... +class _mboxMMDF(_singlefileMailbox[_MessageT_co]): + def get_message(self, key: str) -> _MessageT_co: ... + def get_file(self, key: str, from_: bool = False) -> _PartialFile: ... def get_bytes(self, key: str, from_: bool = False) -> bytes: ... def get_string(self, key: str, from_: bool = False) -> str: ... class mbox(_mboxMMDF[mboxMessage]): - def __init__(self, path: StrPath, factory: Callable[[IO[Any]], mboxMessage] | None = None, create: bool = True) -> None: ... + def __init__( + self, path: StrPath, factory: Callable[[_GetFileReturn], mboxMessage] | None = None, create: bool = True + ) -> None: ... class MMDF(_mboxMMDF[MMDFMessage]): - def __init__(self, path: StrPath, factory: Callable[[IO[Any]], MMDFMessage] | None = None, create: bool = True) -> None: ... + def __init__( + self, path: StrPath, factory: Callable[[_GetFileReturn], MMDFMessage] | None = None, create: bool = True + ) -> None: ... class MH(Mailbox[MHMessage]): - def __init__(self, path: StrPath, factory: Callable[[IO[Any]], MHMessage] | None = None, create: bool = True) -> None: ... + def __init__( + self, path: StrPath, factory: Callable[[_GetFileReturn], MHMessage] | None = None, create: bool = True + ) -> None: ... def add(self, message: _MessageData) -> str: ... def remove(self, key: str) -> None: ... def __setitem__(self, key: str, message: _MessageData) -> None: ... def get_message(self, key: str) -> MHMessage: ... def get_bytes(self, key: str) -> bytes: ... - def get_file(self, key: str) -> _ProxyFile[bytes]: ... + def get_file(self, key: str) -> _ProxyFile: ... def iterkeys(self) -> Iterator[str]: ... def __contains__(self, key: str) -> bool: ... def __len__(self) -> int: ... @@ -184,13 +220,15 @@ class MH(Mailbox[MHMessage]): def pack(self) -> None: ... class Babyl(_singlefileMailbox[BabylMessage]): - def __init__(self, path: StrPath, factory: Callable[[IO[Any]], BabylMessage] | None = None, create: bool = True) -> None: ... + def __init__( + self, path: StrPath, factory: Callable[[_GetFileReturn], BabylMessage] | None = None, create: bool = True + ) -> None: ... def get_message(self, key: str) -> BabylMessage: ... def get_bytes(self, key: str) -> bytes: ... - def get_file(self, key: str) -> IO[bytes]: ... + def get_file(self, key: str) -> io.BytesIO: ... def get_labels(self) -> list[str]: ... -class Message(email.message.Message): +class Message(email.message.Message[str, str]): def __init__(self, message: _MessageData | None = None) -> None: ... class MaildirMessage(Message): @@ -232,18 +270,19 @@ class BabylMessage(Message): class MMDFMessage(_mboxMMDFMessage): ... -class _ProxyFile(Generic[AnyStr]): - def __init__(self, f: IO[AnyStr], pos: int | None = None) -> None: ... - def read(self, size: int | None = None) -> AnyStr: ... - def read1(self, size: int | None = None) -> AnyStr: ... - def readline(self, size: int | None = None) -> AnyStr: ... - def readlines(self, sizehint: int | None = None) -> list[AnyStr]: ... - def __iter__(self) -> Iterator[AnyStr]: ... +# Until Python 3.14, this class was technically - but unnecessarily - generic at runtime. +class _ProxyFile: + def __init__(self, f: _GetFileReturn, pos: int | None = None) -> None: ... + def read(self, size: int | None = None) -> bytes: ... + def read1(self, size: int | None = None) -> bytes: ... + def readline(self, size: int | None = None) -> bytes: ... + def readlines(self, sizehint: int | None = None) -> list[bytes]: ... + def __iter__(self) -> Iterator[bytes]: ... def tell(self) -> int: ... def seek(self, offset: int, whence: int = 0) -> None: ... def close(self) -> None: ... def __enter__(self) -> Self: ... - def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... + def __exit__(self, *exc: Unused) -> None: ... def readable(self) -> bool: ... def writable(self) -> bool: ... def seekable(self) -> bool: ... @@ -252,8 +291,8 @@ class _ProxyFile(Generic[AnyStr]): def closed(self) -> bool: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -class _PartialFile(_ProxyFile[AnyStr]): - def __init__(self, f: IO[AnyStr], start: int | None = None, stop: int | None = None) -> None: ... +class _PartialFile(_ProxyFile): + def __init__(self, f: _GetFileReturn, start: int | None = None, stop: int | None = None) -> None: ... class Error(Exception): ... class NoSuchMailboxError(Error): ... diff --git a/mypy/typeshed/stdlib/mailcap.pyi b/mypy/typeshed/stdlib/mailcap.pyi index ce549e01f528c..74c32694a7f9d 100644 --- a/mypy/typeshed/stdlib/mailcap.pyi +++ b/mypy/typeshed/stdlib/mailcap.pyi @@ -1,5 +1,5 @@ from collections.abc import Mapping, Sequence -from typing_extensions import TypeAlias +from typing import TypeAlias _Cap: TypeAlias = dict[str, str | int] diff --git a/mypy/typeshed/stdlib/marshal.pyi b/mypy/typeshed/stdlib/marshal.pyi index 46c421e4ce307..d72abe7758b76 100644 --- a/mypy/typeshed/stdlib/marshal.pyi +++ b/mypy/typeshed/stdlib/marshal.pyi @@ -2,8 +2,7 @@ import builtins import sys import types from _typeshed import ReadableBuffer, SupportsRead, SupportsWrite -from typing import Any, Final -from typing_extensions import TypeAlias +from typing import Any, Final, TypeAlias version: Final[int] @@ -28,7 +27,11 @@ _Marshallable: TypeAlias = ( | ReadableBuffer ) -if sys.version_info >= (3, 14): +if sys.version_info >= (3, 15): + def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 6, /, *, allow_code: bool = True) -> None: ... + def dumps(value: _Marshallable, version: int = 6, /, *, allow_code: bool = True) -> bytes: ... + +elif sys.version_info >= (3, 14): def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 5, /, *, allow_code: bool = True) -> None: ... def dumps(value: _Marshallable, version: int = 5, /, *, allow_code: bool = True) -> bytes: ... diff --git a/mypy/typeshed/stdlib/math.pyi b/mypy/typeshed/stdlib/math/__init__.pyi similarity index 92% rename from mypy/typeshed/stdlib/math.pyi rename to mypy/typeshed/stdlib/math/__init__.pyi index 1903d488f7bb3..4839bf7e90df1 100644 --- a/mypy/typeshed/stdlib/math.pyi +++ b/mypy/typeshed/stdlib/math/__init__.pyi @@ -1,8 +1,7 @@ import sys from _typeshed import SupportsMul, SupportsRMul from collections.abc import Iterable -from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, TypeVar, overload, type_check_only -from typing_extensions import TypeAlias +from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, TypeAlias, TypeVar, overload, type_check_only _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) @@ -34,6 +33,7 @@ class _SupportsCeil(Protocol[_T_co]): def ceil(x: _SupportsCeil[_T], /) -> _T: ... @overload def ceil(x: _SupportsFloatOrIndex, /) -> int: ... + def comb(n: SupportsIndex, k: SupportsIndex, /) -> int: ... def copysign(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... def cos(x: _SupportsFloatOrIndex, /) -> float: ... @@ -50,6 +50,7 @@ if sys.version_info >= (3, 11): def expm1(x: _SupportsFloatOrIndex, /) -> float: ... def fabs(x: _SupportsFloatOrIndex, /) -> float: ... def factorial(x: SupportsIndex, /) -> int: ... + @type_check_only class _SupportsFloor(Protocol[_T_co]): def __floor__(self) -> _T_co: ... @@ -58,7 +59,13 @@ class _SupportsFloor(Protocol[_T_co]): def floor(x: _SupportsFloor[_T], /) -> _T: ... @overload def floor(x: _SupportsFloatOrIndex, /) -> int: ... + def fmod(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... + +if sys.version_info >= (3, 15): + def fmax(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... + def fmin(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... + def frexp(x: _SupportsFloatOrIndex, /) -> tuple[float, int]: ... def fsum(seq: Iterable[_SupportsFloatOrIndex], /) -> float: ... def gamma(x: _SupportsFloatOrIndex, /) -> float: ... @@ -74,6 +81,11 @@ def isclose( def isinf(x: _SupportsFloatOrIndex, /) -> bool: ... def isfinite(x: _SupportsFloatOrIndex, /) -> bool: ... def isnan(x: _SupportsFloatOrIndex, /) -> bool: ... + +if sys.version_info >= (3, 15): + def isnormal(x: _SupportsFloatOrIndex, /) -> bool: ... + def issubnormal(x: _SupportsFloatOrIndex, /) -> bool: ... + def isqrt(n: SupportsIndex, /) -> int: ... def lcm(*integers: SupportsIndex) -> int: ... def ldexp(x: _SupportsFloatOrIndex, i: int, /) -> float: ... @@ -116,9 +128,14 @@ def prod(iterable: Iterable[bool | _LiteralInteger], /, *, start: int = 1) -> in def prod(iterable: Iterable[_SupportsProdNoDefaultT], /) -> _SupportsProdNoDefaultT | Literal[1]: ... @overload def prod(iterable: Iterable[_MultiplicableT1], /, *, start: _MultiplicableT2) -> _MultiplicableT1 | _MultiplicableT2: ... + def radians(x: _SupportsFloatOrIndex, /) -> float: ... def remainder(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... def sin(x: _SupportsFloatOrIndex, /) -> float: ... + +if sys.version_info >= (3, 15): + def signbit(x: _SupportsFloatOrIndex, /) -> bool: ... + def sinh(x: _SupportsFloatOrIndex, /) -> float: ... if sys.version_info >= (3, 12): diff --git a/mypy/typeshed/stdlib/math/integer.pyi b/mypy/typeshed/stdlib/math/integer.pyi new file mode 100644 index 0000000000000..6d6d6b3e82dce --- /dev/null +++ b/mypy/typeshed/stdlib/math/integer.pyi @@ -0,0 +1,8 @@ +from typing import SupportsIndex + +def comb(n: SupportsIndex, k: SupportsIndex, /) -> int: ... +def factorial(n: SupportsIndex, /) -> int: ... +def gcd(*integers: SupportsIndex) -> int: ... +def isqrt(n: SupportsIndex, /) -> int: ... +def lcm(*integers: SupportsIndex) -> int: ... +def perm(n: SupportsIndex, k: SupportsIndex | None = None, /) -> int: ... diff --git a/mypy/typeshed/stdlib/mmap.pyi b/mypy/typeshed/stdlib/mmap.pyi index 12425f703aa1a..587b91d86c084 100644 --- a/mypy/typeshed/stdlib/mmap.pyi +++ b/mypy/typeshed/stdlib/mmap.pyi @@ -15,8 +15,7 @@ ALLOCATIONGRANULARITY: Final[int] if sys.platform == "linux": MAP_DENYWRITE: Final[int] MAP_EXECUTABLE: Final[int] - if sys.version_info >= (3, 10): - MAP_POPULATE: Final[int] + MAP_POPULATE: Final[int] if sys.version_info >= (3, 11) and sys.platform != "win32" and sys.platform != "darwin": MAP_STACK: Final[int] @@ -28,13 +27,29 @@ if sys.platform != "win32": PROT_EXEC: Final[int] PROT_READ: Final[int] PROT_WRITE: Final[int] + if sys.version_info >= (3, 15): + MS_ASYNC: Final[int] + MS_INVALIDATE: Final[int] + MS_SYNC: Final[int] PAGESIZE: Final[int] @disjoint_base class mmap: if sys.platform == "win32": - def __new__(cls, fileno: int, length: int, tagname: str | None = None, access: int = 0, offset: int = 0) -> Self: ... + if sys.version_info >= (3, 15): + def __new__( + cls, + fileno: int, + length: int, + tagname: str | None = None, + access: int = 0, + offset: int = 0, + *, + trackfd: bool = True, + ) -> Self: ... + else: + def __new__(cls, fileno: int, length: int, tagname: str | None = None, access: int = 0, offset: int = 0) -> Self: ... else: if sys.version_info >= (3, 13): def __new__( @@ -54,11 +69,16 @@ class mmap: ) -> Self: ... def close(self) -> None: ... - def flush(self, offset: int = 0, size: int = ..., /) -> None: ... + if sys.version_info >= (3, 15): + def flush(self, offset: int = 0, size: int = ..., /, *, flags: int = 0) -> None: ... + else: + def flush(self, offset: int = 0, size: int = ..., /) -> None: ... + def move(self, dest: int, src: int, count: int, /) -> None: ... def read_byte(self) -> int: ... def readline(self) -> bytes: ... - def resize(self, newsize: int, /) -> None: ... + if sys.version_info < (3, 15) or sys.platform != "darwin": + def resize(self, newsize: int, /) -> None: ... if sys.platform != "win32": def seek(self, pos: int, whence: Literal[0, 1, 2, 3, 4] = os.SEEK_SET, /) -> None: ... else: @@ -70,21 +90,36 @@ class mmap: def __len__(self) -> int: ... closed: bool if sys.platform != "win32": - def madvise(self, option: int, start: int = 0, length: int = ..., /) -> None: ... + if sys.version_info >= (3, 15): + def madvise(self, option: int, start: int = 0, length: int | None = None, /) -> None: ... + else: + def madvise(self, option: int, start: int = 0, length: int = ..., /) -> None: ... + + if sys.version_info >= (3, 15): + def find(self, view: ReadableBuffer, start: int | None = None, end: int | None = None, /) -> int: ... + def rfind(self, view: ReadableBuffer, start: int | None = None, end: int | None = None, /) -> int: ... + + else: + def find(self, view: ReadableBuffer, start: int = ..., end: int = ..., /) -> int: ... + def rfind(self, view: ReadableBuffer, start: int = ..., end: int = ..., /) -> int: ... - def find(self, view: ReadableBuffer, start: int = ..., end: int = ..., /) -> int: ... - def rfind(self, view: ReadableBuffer, start: int = ..., end: int = ..., /) -> int: ... def read(self, n: int | None = None, /) -> bytes: ... def write(self, bytes: ReadableBuffer, /) -> int: ... + if sys.version_info >= (3, 15): + def set_name(self, name: str, /) -> None: ... + @overload def __getitem__(self, key: SupportsIndex, /) -> int: ... @overload def __getitem__(self, key: slice[SupportsIndex | None], /) -> bytes: ... + def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> NoReturn: ... + @overload def __setitem__(self, key: SupportsIndex, value: int, /) -> None: ... @overload def __setitem__(self, key: slice[SupportsIndex | None], value: ReadableBuffer, /) -> None: ... + # Doesn't actually exist, but the object actually supports "in" because it has __getitem__, # so we claim that there is also a __contains__ to help type checkers. def __contains__(self, o: object, /) -> bool: ... @@ -129,7 +164,7 @@ if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win MADV_CORE: Final[int] MADV_PROTECT: Final[int] -if sys.version_info >= (3, 10) and sys.platform == "darwin": +if sys.platform == "darwin": MADV_FREE_REUSABLE: Final[int] MADV_FREE_REUSE: Final[int] diff --git a/mypy/typeshed/stdlib/msilib/sequence.pyi b/mypy/typeshed/stdlib/msilib/sequence.pyi index a9f5c24717bd3..9b01c416f1d68 100644 --- a/mypy/typeshed/stdlib/msilib/sequence.pyi +++ b/mypy/typeshed/stdlib/msilib/sequence.pyi @@ -1,6 +1,5 @@ import sys -from typing import Final -from typing_extensions import TypeAlias +from typing import Final, TypeAlias if sys.platform == "win32": _SequenceType: TypeAlias = list[tuple[str, str | None, int]] diff --git a/mypy/typeshed/stdlib/msvcrt.pyi b/mypy/typeshed/stdlib/msvcrt.pyi index 5feca8eab5c1c..1518f7974de7c 100644 --- a/mypy/typeshed/stdlib/msvcrt.pyi +++ b/mypy/typeshed/stdlib/msvcrt.pyi @@ -28,5 +28,4 @@ if sys.platform == "win32": def ungetwch(unicode_char: str, /) -> None: ... def heapmin() -> None: ... def SetErrorMode(mode: int, /) -> int: ... - if sys.version_info >= (3, 10): - def GetErrorMode() -> int: ... # undocumented + def GetErrorMode() -> int: ... # undocumented diff --git a/mypy/typeshed/stdlib/multiprocessing/connection.pyi b/mypy/typeshed/stdlib/multiprocessing/connection.pyi index cd4fa102c0f3e..b9475c5baa49d 100644 --- a/mypy/typeshed/stdlib/multiprocessing/connection.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/connection.pyi @@ -3,8 +3,8 @@ import sys from _typeshed import Incomplete, ReadableBuffer from collections.abc import Iterable from types import TracebackType -from typing import Any, Generic, SupportsIndex, TypeVar -from typing_extensions import Self, TypeAlias +from typing import Any, Generic, SupportsIndex, TypeAlias, TypeVar +from typing_extensions import Self __all__ = ["Client", "Listener", "Pipe", "wait"] diff --git a/mypy/typeshed/stdlib/multiprocessing/context.pyi b/mypy/typeshed/stdlib/multiprocessing/context.pyi index 03d1d2e5c2203..13fd967515d09 100644 --- a/mypy/typeshed/stdlib/multiprocessing/context.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/context.pyi @@ -9,8 +9,7 @@ from multiprocessing.managers import SyncManager from multiprocessing.pool import Pool as _Pool from multiprocessing.process import BaseProcess from multiprocessing.sharedctypes import Synchronized, SynchronizedArray, SynchronizedString -from typing import Any, ClassVar, Literal, TypeVar, overload -from typing_extensions import TypeAlias +from typing import Any, ClassVar, Literal, TypeAlias, TypeVar, overload if sys.platform != "win32": from multiprocessing.connection import Connection @@ -75,14 +74,17 @@ class BaseContext: initargs: Iterable[Any] = (), maxtasksperchild: int | None = None, ) -> _Pool: ... + @overload def RawValue(self, typecode_or_type: type[_CT], *args: Any) -> _CT: ... @overload def RawValue(self, typecode_or_type: str, *args: Any) -> Any: ... + @overload def RawArray(self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... @overload def RawArray(self, typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ... + @overload def Value( self, typecode_or_type: type[_SimpleCData[_T]], *args: Any, lock: Literal[True] | _LockLike = True @@ -95,6 +97,7 @@ class BaseContext: def Value(self, typecode_or_type: str, *args: Any, lock: Literal[True] | _LockLike = True) -> Synchronized[Any]: ... @overload def Value(self, typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = True) -> Any: ... + @overload def Array( self, typecode_or_type: type[_SimpleCData[_T]], size_or_initializer: int | Sequence[Any], *, lock: Literal[False] @@ -119,40 +122,44 @@ class BaseContext: def Array( self, typecode_or_type: str | type[_CData], size_or_initializer: int | Sequence[Any], *, lock: bool | _LockLike = True ) -> Any: ... + def freeze_support(self) -> None: ... def get_logger(self) -> Logger: ... def log_to_stderr(self, level: _LoggingLevel | None = None) -> Logger: ... def allow_connection_pickling(self) -> None: ... def set_executable(self, executable: str) -> None: ... - def set_forkserver_preload(self, module_names: list[str]) -> None: ... + if sys.version_info >= (3, 15): + def set_forkserver_preload( + self, module_names: list[str], *, on_error: Literal["ignore", "warn", "fail"] = "ignore" + ) -> None: ... + else: + def set_forkserver_preload(self, module_names: list[str]) -> None: ... + + @overload + def get_context(self, method: None = None) -> DefaultContext: ... + @overload + def get_context(self, method: Literal["spawn"]) -> SpawnContext: ... if sys.platform != "win32": - @overload - def get_context(self, method: None = None) -> DefaultContext: ... - @overload - def get_context(self, method: Literal["spawn"]) -> SpawnContext: ... @overload def get_context(self, method: Literal["fork"]) -> ForkContext: ... @overload def get_context(self, method: Literal["forkserver"]) -> ForkServerContext: ... - @overload - def get_context(self, method: str) -> BaseContext: ... - else: - @overload - def get_context(self, method: None = None) -> DefaultContext: ... - @overload - def get_context(self, method: Literal["spawn"]) -> SpawnContext: ... - @overload - def get_context(self, method: str) -> BaseContext: ... + + @overload + def get_context(self, method: str) -> BaseContext: ... @overload def get_start_method(self, allow_none: Literal[False] = False) -> str: ... @overload def get_start_method(self, allow_none: bool) -> str | None: ... + def set_start_method(self, method: str | None, force: bool = False) -> None: ... + @property def reducer(self) -> str: ... @reducer.setter def reducer(self, reduction: str) -> None: ... + def _check_available(self) -> None: ... class Process(BaseProcess): @@ -201,6 +208,13 @@ if sys.platform != "win32": Process: ClassVar[type[ForkServerProcess]] def _force_start_method(method: str) -> None: ... -def get_spawning_popen() -> Any | None: ... -def set_spawning_popen(popen: Any) -> None: ... + +if sys.platform != "win32": + def get_spawning_popen() -> popen_forkserver.Popen | popen_spawn_posix.Popen | None: ... + def set_spawning_popen(popen: popen_forkserver.Popen | popen_spawn_posix.Popen | None) -> None: ... + +else: + def get_spawning_popen() -> popen_spawn_win32.Popen | None: ... + def set_spawning_popen(popen: popen_spawn_win32.Popen | None) -> None: ... + def assert_spawning(obj: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/forkserver.pyi b/mypy/typeshed/stdlib/multiprocessing/forkserver.pyi index 570b492e9daf3..e48be5f07949e 100644 --- a/mypy/typeshed/stdlib/multiprocessing/forkserver.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/forkserver.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import FileDescriptorLike, Unused from collections.abc import Sequence from struct import Struct -from typing import Any, Final +from typing import Any, Final, Literal __all__ = ["ensure_running", "get_inherited_fds", "connect_to_new_process", "set_forkserver_preload"] @@ -10,12 +10,31 @@ MAXFDS_TO_SEND: Final = 256 SIGNED_STRUCT: Final[Struct] class ForkServer: - def set_forkserver_preload(self, modules_names: list[str]) -> None: ... + if sys.version_info >= (3, 15): + def set_forkserver_preload( + self, modules_names: list[str], *, on_error: Literal["ignore", "warn", "fail"] = "ignore" + ) -> None: ... + else: + def set_forkserver_preload(self, modules_names: list[str]) -> None: ... + def get_inherited_fds(self) -> list[int] | None: ... def connect_to_new_process(self, fds: Sequence[int]) -> tuple[int, int]: ... def ensure_running(self) -> None: ... -if sys.version_info >= (3, 14): +if sys.version_info >= (3, 15): + def main( + listener_fd: int | None, + alive_r: FileDescriptorLike, + preload: Sequence[str], + main_path: str | None = None, + sys_path: list[str] | None = None, + *, + sys_argv: list[str] | None = None, + authkey_r: int | None = None, + on_error: str = "ignore", + ) -> None: ... + +elif sys.version_info >= (3, 14): # `sys_argv` parameter added in Python 3.14.3 def main( listener_fd: int | None, diff --git a/mypy/typeshed/stdlib/multiprocessing/heap.pyi b/mypy/typeshed/stdlib/multiprocessing/heap.pyi index 38191a099f1ec..bf6f853a97608 100644 --- a/mypy/typeshed/stdlib/multiprocessing/heap.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/heap.pyi @@ -1,9 +1,8 @@ import sys -from _typeshed import Incomplete from collections.abc import Callable from mmap import mmap -from typing import Protocol, type_check_only -from typing_extensions import TypeAlias +from multiprocessing import popen_forkserver, popen_spawn_posix, resource_sharer +from typing import Protocol, TypeAlias, type_check_only __all__ = ["BufferWrapper"] @@ -24,7 +23,12 @@ if sys.platform != "win32": class _SupportsDetach(Protocol): def detach(self) -> int: ... - def reduce_arena(a: Arena) -> tuple[Callable[[int, _SupportsDetach], Arena], tuple[int, Incomplete]]: ... + def reduce_arena( + a: Arena, + ) -> tuple[ + Callable[[int, _SupportsDetach], Arena], + tuple[int, popen_forkserver._DupFd | popen_spawn_posix._DupFd | resource_sharer.DupFd], + ]: ... def rebuild_arena(size: int, dupfd: _SupportsDetach) -> Arena: ... class Heap: diff --git a/mypy/typeshed/stdlib/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi index bb169ed6b2ed4..40639e8678348 100644 --- a/mypy/typeshed/stdlib/multiprocessing/managers.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/managers.pyi @@ -14,8 +14,8 @@ from collections.abc import ( Set as AbstractSet, ) from types import GenericAlias, TracebackType -from typing import Any, AnyStr, ClassVar, Generic, SupportsIndex, TypeVar, overload -from typing_extensions import Self, TypeAlias +from typing import Any, AnyStr, ClassVar, Generic, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import Self from . import pool from .connection import Connection, _Address @@ -81,18 +81,21 @@ if sys.version_info >= (3, 13): def __delitem__(self, key: _KT, /) -> None: ... def __iter__(self) -> Iterator[_KT]: ... def copy(self) -> dict[_KT, _VT]: ... + @overload # type: ignore[override] def get(self, key: _KT, /) -> _VT | None: ... @overload def get(self, key: _KT, default: _VT, /) -> _VT: ... @overload def get(self, key: _KT, default: _T, /) -> _VT | _T: ... + @overload def pop(self, key: _KT, /) -> _VT: ... @overload def pop(self, key: _KT, default: _VT, /) -> _VT: ... @overload def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... + def keys(self) -> list[_KT]: ... # type: ignore[override] def items(self) -> list[tuple[_KT, _VT]]: ... # type: ignore[override] def values(self) -> list[_VT]: ... # type: ignore[override] @@ -102,15 +105,19 @@ if sys.version_info >= (3, 13): def fromkeys(self, iterable: Iterable[_T], value: None = None, /) -> dict[_T, Any | None]: ... @overload def fromkeys(self, iterable: Iterable[_T], value: _S, /) -> dict[_T, _S]: ... + def __reversed__(self) -> Iterator[_KT]: ... + @overload def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... @overload def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + @overload def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... @overload def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + @overload # type: ignore[misc] def __ior__(self, value: SupportsKeysAndGetItem[_KT, _VT], /) -> Self: ... @overload @@ -128,18 +135,21 @@ else: def __delitem__(self, key: _KT, /) -> None: ... def __iter__(self) -> Iterator[_KT]: ... def copy(self) -> dict[_KT, _VT]: ... + @overload # type: ignore[override] def get(self, key: _KT, /) -> _VT | None: ... @overload def get(self, key: _KT, default: _VT, /) -> _VT: ... @overload def get(self, key: _KT, default: _T, /) -> _VT | _T: ... + @overload def pop(self, key: _KT, /) -> _VT: ... @overload def pop(self, key: _KT, default: _VT, /) -> _VT: ... @overload def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... + def keys(self) -> list[_KT]: ... # type: ignore[override] def items(self) -> list[tuple[_KT, _VT]]: ... # type: ignore[override] def values(self) -> list[_VT]: ... # type: ignore[override] @@ -194,14 +204,17 @@ class BaseListProxy(BaseProxy, MutableSequence[_T]): def __len__(self) -> int: ... def __add__(self, x: list[_T], /) -> list[_T]: ... def __delitem__(self, i: SupportsIndex | slice[SupportsIndex | None], /) -> None: ... + @overload def __getitem__(self, i: SupportsIndex, /) -> _T: ... @overload def __getitem__(self, s: slice[SupportsIndex | None], /) -> list[_T]: ... + @overload def __setitem__(self, i: SupportsIndex, o: _T, /) -> None: ... @overload def __setitem__(self, s: slice[SupportsIndex | None], o: Iterable[_T], /) -> None: ... + def __mul__(self, n: SupportsIndex, /) -> list[_T]: ... def __rmul__(self, n: SupportsIndex, /) -> list[_T]: ... def __imul__(self, value: SupportsIndex, /) -> Self: ... @@ -217,6 +230,7 @@ class BaseListProxy(BaseProxy, MutableSequence[_T]): # Next methods are copied from builtins.list def clear(self) -> None: ... def copy(self) -> list[_T]: ... + # Use BaseListProxy[SupportsRichComparisonT] for the first overload rather than [SupportsRichComparison] # to work around invariance @overload @@ -250,11 +264,7 @@ class Server: ) -> None: ... def serve_forever(self) -> None: ... def accepter(self) -> None: ... - if sys.version_info >= (3, 10): - def handle_request(self, conn: _ServerConnection) -> None: ... - else: - def handle_request(self, c: _ServerConnection) -> None: ... - + def handle_request(self, conn: _ServerConnection) -> None: ... def serve_client(self, conn: _ServerConnection) -> None: ... def fallback_getvalue(self, conn: _ServerConnection, ident: str, obj: _T) -> _T: ... def fallback_str(self, conn: _ServerConnection, ident: str, obj: Any) -> str: ... @@ -334,6 +344,7 @@ class SyncManager(BaseManager): def Semaphore(self, value: int = 1) -> threading.Semaphore: ... def Array(self, typecode: Any, sequence: Sequence[_T]) -> Sequence[_T]: ... def Value(self, typecode: Any, value: _T) -> ValueProxy[_T]: ... + # Overloads are copied from builtins.dict.__init__ @overload def dict(self) -> DictProxy[Any, Any]: ... @@ -351,11 +362,13 @@ class SyncManager(BaseManager): def dict(self, iterable: Iterable[list[str]], /) -> DictProxy[str, str]: ... @overload def dict(self, iterable: Iterable[list[bytes]], /) -> DictProxy[bytes, bytes]: ... + # Overloads are copied from builtins.list.__init__ @overload def list(self, iterable: Iterable[_T], /) -> ListProxy[_T]: ... @overload def list(self) -> ListProxy[Any]: ... + if sys.version_info >= (3, 14): @overload def set(self, iterable: Iterable[_T], /) -> SetProxy[_T]: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/reduction.pyi b/mypy/typeshed/stdlib/multiprocessing/reduction.pyi index ddc676efccc39..476cf9b26f718 100644 --- a/mypy/typeshed/stdlib/multiprocessing/reduction.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/reduction.pyi @@ -6,7 +6,7 @@ from abc import ABCMeta from builtins import type as Type # alias to avoid name clash from collections.abc import Callable from copyreg import _DispatchTableType -from multiprocessing import connection +from multiprocessing import connection, popen_forkserver, popen_spawn_posix, resource_sharer from socket import socket from typing import Any, Final @@ -57,7 +57,7 @@ else: def send_handle(conn: HasFileno, handle: int, destination_pid: Unused) -> None: ... def recv_handle(conn: HasFileno) -> int: ... def sendfds(sock: socket, fds: list[int]) -> None: ... - def DupFd(fd: int) -> Any: ... # Return type is really hard to get right + def DupFd(fd: int) -> popen_forkserver._DupFd | popen_spawn_posix._DupFd | resource_sharer.DupFd: ... # These aliases are to work around pyright complaints. # Pyright doesn't like it when a class object is defined as an alias diff --git a/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi index f75a372a69a2d..90777a4e771bd 100644 --- a/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi @@ -26,10 +26,12 @@ class SharedMemory: class ShareableList(Generic[_SLT]): shm: SharedMemory + @overload def __init__(self, sequence: None = None, *, name: str | None = None) -> None: ... @overload def __init__(self, sequence: Iterable[_SLT], *, name: str | None = None) -> None: ... + def __getitem__(self, position: int) -> _SLT: ... def __setitem__(self, position: int, value: _SLT) -> None: ... def __reduce__(self) -> tuple[Self, tuple[_SLT, ...]]: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi b/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi index f61ca26aab5d6..693fd2f701396 100644 --- a/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi @@ -16,10 +16,12 @@ _CT = TypeVar("_CT", bound=_CData) def RawValue(typecode_or_type: type[_CT], *args: Any) -> _CT: ... @overload def RawValue(typecode_or_type: str, *args: Any) -> Any: ... + @overload def RawArray(typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... @overload def RawArray(typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ... + @overload def Value(typecode_or_type: type[_CT], *args: Any, lock: Literal[False], ctx: BaseContext | None = None) -> _CT: ... @overload @@ -34,6 +36,7 @@ def Value( def Value( typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = True, ctx: BaseContext | None = None ) -> Any: ... + @overload def Array( typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False], ctx: BaseContext | None = None @@ -70,7 +73,9 @@ def Array( lock: bool | _LockLike = True, ctx: BaseContext | None = None, ) -> Any: ... + def copy(obj: _CT) -> _CT: ... + @overload def synchronized(obj: _SimpleCData[_T], lock: _LockLike | None = None, ctx: Any | None = None) -> Synchronized[_T]: ... @overload @@ -81,6 +86,7 @@ def synchronized( ) -> SynchronizedArray[_T]: ... @overload def synchronized(obj: _CT, lock: _LockLike | None = None, ctx: Any | None = None) -> SynchronizedBase[_CT]: ... + @type_check_only class _AcquireFunc(Protocol): def __call__(self, block: bool = ..., timeout: float | None = ..., /) -> bool: ... @@ -102,14 +108,17 @@ class Synchronized(SynchronizedBase[_SimpleCData[_T]], Generic[_T]): class SynchronizedArray(SynchronizedBase[ctypes.Array[_SimpleCData[_T]]], Generic[_T]): def __len__(self) -> int: ... + @overload def __getitem__(self, i: slice[SupportsIndex | None]) -> list[_T]: ... @overload def __getitem__(self, i: SupportsIndex) -> _T: ... + @overload def __setitem__(self, i: slice[SupportsIndex | None], value: Iterable[_T]) -> None: ... @overload def __setitem__(self, i: SupportsIndex, value: _T) -> None: ... + def __getslice__(self, start: SupportsIndex, stop: SupportsIndex) -> list[_T]: ... def __setslice__(self, start: SupportsIndex, stop: SupportsIndex, values: Iterable[_T]) -> None: ... @@ -118,10 +127,12 @@ class SynchronizedString(SynchronizedArray[bytes]): def __getitem__(self, i: slice[SupportsIndex | None]) -> bytes: ... @overload def __getitem__(self, i: SupportsIndex) -> bytes: ... + @overload # type: ignore[override] def __setitem__(self, i: slice[SupportsIndex | None], value: bytes) -> None: ... @overload def __setitem__(self, i: SupportsIndex, value: bytes) -> None: ... + def __getslice__(self, start: SupportsIndex, stop: SupportsIndex) -> bytes: ... # type: ignore[override] def __setslice__(self, start: SupportsIndex, stop: SupportsIndex, values: bytes) -> None: ... # type: ignore[override] diff --git a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi index 541e0b05dd8a6..889e71c061e11 100644 --- a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi @@ -3,7 +3,7 @@ import threading from collections.abc import Callable from multiprocessing.context import BaseContext from types import TracebackType -from typing_extensions import TypeAlias +from typing import TypeAlias __all__ = ["Lock", "RLock", "Semaphore", "BoundedSemaphore", "Condition", "Event"] diff --git a/mypy/typeshed/stdlib/multiprocessing/util.pyi b/mypy/typeshed/stdlib/multiprocessing/util.pyi index 3583194c77e29..5eb31de77f0f7 100644 --- a/mypy/typeshed/stdlib/multiprocessing/util.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/util.pyi @@ -82,6 +82,7 @@ class Finalize(Generic[_R_co]): kwargs: Mapping[str, Any] | None = None, exitpriority: int | None = None, ) -> None: ... + def __call__( self, wr: Unused = None, diff --git a/mypy/typeshed/stdlib/netrc.pyi b/mypy/typeshed/stdlib/netrc.pyi index 480f55a46d645..4b7035c3e565e 100644 --- a/mypy/typeshed/stdlib/netrc.pyi +++ b/mypy/typeshed/stdlib/netrc.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import StrOrBytesPath -from typing_extensions import TypeAlias +from typing import TypeAlias __all__ = ["netrc", "NetrcParseError"] diff --git a/mypy/typeshed/stdlib/nntplib.pyi b/mypy/typeshed/stdlib/nntplib.pyi index 1fb1e79f69a1f..50b633ce1ad12 100644 --- a/mypy/typeshed/stdlib/nntplib.pyi +++ b/mypy/typeshed/stdlib/nntplib.pyi @@ -4,8 +4,8 @@ import ssl from _typeshed import Unused from builtins import list as _list # conflicts with a method named "list" from collections.abc import Iterable -from typing import IO, Any, Final, NamedTuple -from typing_extensions import Self, TypeAlias +from typing import IO, Any, Final, NamedTuple, TypeAlias +from typing_extensions import Self __all__ = [ "NNTP", diff --git a/mypy/typeshed/stdlib/ntpath.pyi b/mypy/typeshed/stdlib/ntpath.pyi index 074df075b9727..c912d77158ecc 100644 --- a/mypy/typeshed/stdlib/ntpath.pyi +++ b/mypy/typeshed/stdlib/ntpath.pyi @@ -51,6 +51,8 @@ if sys.version_info >= (3, 12): from posixpath import isjunction as isjunction, splitroot as splitroot if sys.version_info >= (3, 13): from genericpath import isdevdrive as isdevdrive +if sys.version_info >= (3, 15): + from genericpath import ALL_BUT_LAST as ALL_BUT_LAST __all__ = [ "normcase", @@ -97,6 +99,8 @@ if sys.version_info >= (3, 12): __all__ += ["isjunction", "splitroot"] if sys.version_info >= (3, 13): __all__ += ["isdevdrive", "isreserved"] +if sys.version_info >= (3, 15): + __all__ += ["ALL_BUT_LAST"] altsep: LiteralString @@ -110,14 +114,21 @@ def join(path: StrPath, /, *paths: StrPath) -> str: ... @overload def join(path: BytesPath, /, *paths: BytesPath) -> bytes: ... -if sys.platform == "win32": +if sys.version_info >= (3, 15): @overload - def realpath(path: PathLike[AnyStr], *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + def realpath(path: PathLike[AnyStr], /, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... @overload - def realpath(path: AnyStr, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + def realpath(path: AnyStr, /, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... else: - realpath = abspath + if sys.platform == "win32": + @overload + def realpath(path: PathLike[AnyStr], *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + @overload + def realpath(path: AnyStr, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + + else: + realpath = abspath if sys.version_info >= (3, 13): def isreserved(path: StrOrBytesPath) -> bool: ... diff --git a/mypy/typeshed/stdlib/nturl2path.pyi b/mypy/typeshed/stdlib/nturl2path.pyi index 014af8a0fd2ed..98686ed65420f 100644 --- a/mypy/typeshed/stdlib/nturl2path.pyi +++ b/mypy/typeshed/stdlib/nturl2path.pyi @@ -1,12 +1,6 @@ -import sys from typing_extensions import deprecated -if sys.version_info >= (3, 14): - @deprecated("The `nturl2path` module is deprecated since Python 3.14.") - def url2pathname(url: str) -> str: ... - @deprecated("The `nturl2path` module is deprecated since Python 3.14.") - def pathname2url(p: str) -> str: ... - -else: - def url2pathname(url: str) -> str: ... - def pathname2url(p: str) -> str: ... +@deprecated("The `nturl2path` module is deprecated since Python 3.14.") +def url2pathname(url: str) -> str: ... +@deprecated("The `nturl2path` module is deprecated since Python 3.14.") +def pathname2url(p: str) -> str: ... diff --git a/mypy/typeshed/stdlib/numbers.pyi b/mypy/typeshed/stdlib/numbers.pyi index 64fb16581e952..434e52c4cac80 100644 --- a/mypy/typeshed/stdlib/numbers.pyi +++ b/mypy/typeshed/stdlib/numbers.pyi @@ -120,12 +120,14 @@ class Real(Complex, _RealLike): def __floor__(self) -> _IntegralLike: ... @abstractmethod def __ceil__(self) -> _IntegralLike: ... + @abstractmethod @overload def __round__(self, ndigits: None = None) -> _IntegralLike: ... @abstractmethod @overload def __round__(self, ndigits: int) -> _RealLike: ... + def __divmod__(self, other) -> tuple[_RealLike, _RealLike]: ... def __rdivmod__(self, other) -> tuple[_RealLike, _RealLike]: ... @abstractmethod @@ -209,6 +211,7 @@ class Integral(Rational, _IntegralLike): def __neg__(self) -> _IntegralLike: ... @abstractmethod def __abs__(self) -> _IntegralLike: ... + @abstractmethod @overload def __round__(self, ndigits: None = None) -> _IntegralLike: ... diff --git a/mypy/typeshed/stdlib/opcode.pyi b/mypy/typeshed/stdlib/opcode.pyi index 67c2ef27ff360..3bc41db42bb63 100644 --- a/mypy/typeshed/stdlib/opcode.pyi +++ b/mypy/typeshed/stdlib/opcode.pyi @@ -1,6 +1,9 @@ import sys from typing import Final, Literal +if sys.version_info >= (3, 15): + from builtins import frozendict + __all__ = [ "cmp_op", "hasconst", @@ -40,7 +43,10 @@ if sys.version_info >= (3, 13): hasjump: Final[list[int]] opname: Final[list[str]] -opmap: Final[dict[str, int]] +if sys.version_info >= (3, 15): + opmap: Final[frozendict[str, int]] +else: + opmap: Final[dict[str, int]] HAVE_ARGUMENT: Final[int] EXTENDED_ARG: Final[int] diff --git a/mypy/typeshed/stdlib/operator.pyi b/mypy/typeshed/stdlib/operator.pyi index 2f919514b0b8b..5998d6d16e98b 100644 --- a/mypy/typeshed/stdlib/operator.pyi +++ b/mypy/typeshed/stdlib/operator.pyi @@ -192,6 +192,7 @@ class attrgetter(Generic[_T_co]): def __new__(cls, attr: str, attr2: str, attr3: str, attr4: str, /) -> attrgetter[tuple[Any, Any, Any, Any]]: ... @overload def __new__(cls, attr: str, /, *attrs: str) -> attrgetter[tuple[Any, ...]]: ... + def __call__(self, obj: Any, /) -> _T_co: ... @final @@ -200,6 +201,7 @@ class itemgetter(Generic[_T_co]): def __new__(cls, item: _T, /) -> itemgetter[_T]: ... @overload def __new__(cls, item1: _T1, item2: _T2, /, *items: Unpack[_Ts]) -> itemgetter[tuple[_T1, _T2, Unpack[_Ts]]]: ... + # __key: _KT_contra in SupportsGetItem seems to be causing variance issues, ie: # TypeVar "_KT_contra@SupportsGetItem" is contravariant # "tuple[int, int]" is incompatible with protocol "SupportsIndex" diff --git a/mypy/typeshed/stdlib/optparse.pyi b/mypy/typeshed/stdlib/optparse.pyi index 305b6a4f06d66..9e5536610272e 100644 --- a/mypy/typeshed/stdlib/optparse.pyi +++ b/mypy/typeshed/stdlib/optparse.pyi @@ -184,6 +184,7 @@ class OptionContainer: def _check_conflict(self, option: Option) -> None: ... def _create_option_mappings(self) -> None: ... def _share_option_mappings(self, parser: OptionParser) -> None: ... + @overload def add_option(self, opt: Option, /) -> Option: ... @overload @@ -206,6 +207,7 @@ class OptionContainer: metavar: str | None = None, **kwargs: Any, # Allow arbitrary keyword arguments for user defined option_class ) -> Option: ... + def add_options(self, option_list: Iterable[Option]) -> None: ... def destroy(self) -> None: ... def format_option_help(self, formatter: HelpFormatter) -> str: ... @@ -280,10 +282,12 @@ class OptionParser(OptionContainer): def _process_args(self, largs: list[str], rargs: list[str], values: Values) -> None: ... def _process_long_opt(self, rargs: list[str], values: Values) -> None: ... def _process_short_opts(self, rargs: list[str], values: Values) -> None: ... + @overload def add_option_group(self, opt_group: OptionGroup, /) -> OptionGroup: ... @overload def add_option_group(self, title: str, /, description: str | None = None) -> OptionGroup: ... + def check_values(self, values: Values, args: list[str]) -> tuple[Values, list[str]]: ... def disable_interspersed_args(self) -> None: ... def enable_interspersed_args(self) -> None: ... diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 66a9d1dd3bc6d..836d6e2ef4461 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -35,13 +35,14 @@ from typing import ( Literal, NoReturn, Protocol, + TypeAlias, TypeVar, final, overload, runtime_checkable, type_check_only, ) -from typing_extensions import LiteralString, Self, TypeAlias, Unpack, deprecated +from typing_extensions import LiteralString, Self, Unpack, deprecated from . import path as _path @@ -176,9 +177,11 @@ __all__ = [ if sys.version_info >= (3, 14): # reload_environ was added to __all__ in Python 3.14.1 __all__ += ["readinto", "reload_environ"] +if sys.platform == "linux" and sys.version_info >= (3, 15): + __all__ += ["_clearenv"] if sys.platform == "darwin" and sys.version_info >= (3, 12): __all__ += ["PRIO_DARWIN_BG", "PRIO_DARWIN_NONUI", "PRIO_DARWIN_PROCESS", "PRIO_DARWIN_THREAD"] -if sys.platform == "darwin" and sys.version_info >= (3, 10): +if sys.platform == "darwin": __all__ += ["O_EVTONLY", "O_NOFOLLOW_ANY", "O_SYMLINK"] if sys.platform == "linux": __all__ += [ @@ -226,6 +229,31 @@ if sys.platform == "linux": ] if sys.platform == "linux" and sys.version_info >= (3, 14): __all__ += ["SCHED_DEADLINE", "SCHED_NORMAL"] +if sys.platform == "linux" and sys.version_info >= (3, 15): + __all__ += [ + "AT_NO_AUTOMOUNT", + "AT_STATX_DONT_SYNC", + "AT_STATX_FORCE_SYNC", + "AT_STATX_SYNC_AS_STAT", + "STATX_ATIME", + "STATX_BASIC_STATS", + "STATX_BLOCKS", + "STATX_BTIME", + "STATX_CTIME", + "STATX_DIOALIGN", + "STATX_GID", + "STATX_INO", + "STATX_MNT_ID", + "STATX_MNT_ID_UNIQUE", + "STATX_MODE", + "STATX_MTIME", + "STATX_NLINK", + "STATX_SIZE", + "STATX_TYPE", + "STATX_UID", + "statx", + "statx_result", + ] if sys.platform == "linux" and sys.version_info >= (3, 13): __all__ += [ "POSIX_SPAWN_CLOSEFROM", @@ -259,7 +287,7 @@ if sys.platform == "linux" and sys.version_info >= (3, 12): "unshare", "PIDFD_NONBLOCK", ] -if sys.platform == "linux" and sys.version_info >= (3, 10): +if sys.platform == "linux": __all__ += [ "EFD_CLOEXEC", "EFD_NONBLOCK", @@ -446,7 +474,9 @@ if sys.platform != "win32" and sys.version_info >= (3, 13): __all__ += ["grantpt", "posix_openpt", "ptsname", "unlockpt"] if sys.platform != "win32" and sys.version_info >= (3, 11): __all__ += ["login_tty"] -if sys.platform != "win32" and sys.version_info >= (3, 10): +if sys.platform != "win32" and sys.version_info >= (3, 15): + __all__ += ["NODEV", "O_FSYNC"] +elif sys.platform != "win32": __all__ += ["O_FSYNC"] if sys.platform != "darwin" and sys.platform != "win32": __all__ += [ @@ -661,12 +691,37 @@ if sys.platform != "linux" and sys.platform != "win32": O_SHLOCK: Final[int] O_EXLOCK: Final[int] -if sys.platform == "darwin" and sys.version_info >= (3, 10): +if sys.platform == "darwin": O_EVTONLY: Final[int] O_NOFOLLOW_ANY: Final[int] O_SYMLINK: Final[int] -if sys.platform != "win32" and sys.version_info >= (3, 10): +if sys.platform != "win32" and sys.version_info >= (3, 15): + NODEV: Final[int] + +if sys.platform == "linux" and sys.version_info >= (3, 15): + AT_NO_AUTOMOUNT: Final[int] + AT_STATX_DONT_SYNC: Final[int] + AT_STATX_FORCE_SYNC: Final[int] + AT_STATX_SYNC_AS_STAT: Final[int] + STATX_ATIME: Final[int] + STATX_BASIC_STATS: Final[int] + STATX_BLOCKS: Final[int] + STATX_BTIME: Final[int] + STATX_CTIME: Final[int] + STATX_DIOALIGN: Final[int] + STATX_GID: Final[int] + STATX_INO: Final[int] + STATX_MNT_ID: Final[int] + STATX_MNT_ID_UNIQUE: Final[int] + STATX_MODE: Final[int] + STATX_MTIME: Final[int] + STATX_NLINK: Final[int] + STATX_SIZE: Final[int] + STATX_TYPE: Final[int] + STATX_UID: Final[int] + +if sys.platform != "win32": O_FSYNC: Final[int] if sys.platform != "linux" and sys.platform != "win32" and sys.version_info >= (3, 13): @@ -713,18 +768,21 @@ class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): encodevalue: _EnvironCodeFunc[AnyStr], decodevalue: _EnvironCodeFunc[AnyStr], ) -> None: ... + @overload def get(self, key: AnyStr, default: None = None) -> AnyStr | None: ... @overload def get(self, key: AnyStr, default: AnyStr) -> AnyStr: ... @overload def get(self, key: AnyStr, default: _T) -> AnyStr | _T: ... + @overload def pop(self, key: AnyStr) -> AnyStr: ... @overload def pop(self, key: AnyStr, default: AnyStr) -> AnyStr: ... @overload def pop(self, key: AnyStr, default: _T) -> AnyStr | _T: ... + def setdefault(self, key: AnyStr, value: AnyStr) -> AnyStr: ... def copy(self) -> dict[AnyStr, AnyStr]: ... def __delitem__(self, key: AnyStr) -> None: ... @@ -734,6 +792,7 @@ class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): def __len__(self) -> int: ... def __or__(self, other: Mapping[_T1, _T2]) -> dict[AnyStr | _T1, AnyStr | _T2]: ... def __ror__(self, other: Mapping[_T1, _T2]) -> dict[AnyStr | _T1, AnyStr | _T2]: ... + # We use @overload instead of a Union for reasons similar to those given for # overloading MutableMapping.update in stdlib/typing.pyi # The type: ignore is needed due to incompatible __or__/__ior__ signatures @@ -749,6 +808,9 @@ if sys.platform != "win32": if sys.version_info >= (3, 14): def reload_environ() -> None: ... +if sys.platform == "linux" and sys.version_info >= (3, 15): + def _clearenv() -> None: ... + if sys.version_info >= (3, 11) or sys.platform != "win32": EX_OK: Final[int] @@ -805,8 +867,7 @@ class stat_result(structseq[float], tuple[int, int, int, int, int, int, int, flo # st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime. # # More items may be added at the end by some implementations. - if sys.version_info >= (3, 10): - __match_args__: Final = ("st_mode", "st_ino", "st_dev", "st_nlink", "st_uid", "st_gid", "st_size") + __match_args__: Final = ("st_mode", "st_ino", "st_dev", "st_nlink", "st_uid", "st_gid", "st_size") @property def st_mode(self) -> int: ... # protection bits, @@ -890,6 +951,7 @@ def listdir(path: StrPath | None = None) -> list[str]: ... def listdir(path: BytesPath) -> list[bytes]: ... @overload def listdir(path: int) -> list[str]: ... + @final class DirEntry(Generic[AnyStr]): # This is what the scandir iterator yields @@ -911,19 +973,18 @@ class DirEntry(Generic[AnyStr]): @final class statvfs_result(structseq[int], tuple[int, int, int, int, int, int, int, int, int, int, int]): - if sys.version_info >= (3, 10): - __match_args__: Final = ( - "f_bsize", - "f_frsize", - "f_blocks", - "f_bfree", - "f_bavail", - "f_files", - "f_ffree", - "f_favail", - "f_flag", - "f_namemax", - ) + __match_args__: Final = ( + "f_bsize", + "f_frsize", + "f_blocks", + "f_bfree", + "f_bavail", + "f_files", + "f_ffree", + "f_favail", + "f_flag", + "f_namemax", + ) @property def f_bsize(self) -> int: ... @@ -951,22 +1012,24 @@ class statvfs_result(structseq[int], tuple[int, int, int, int, int, int, int, in # ----- os function stubs ----- def fsencode(filename: StrOrBytesPath) -> bytes: ... def fsdecode(filename: StrOrBytesPath) -> str: ... + @overload def fspath(path: str) -> str: ... @overload def fspath(path: bytes) -> bytes: ... @overload def fspath(path: PathLike[AnyStr]) -> AnyStr: ... + def get_exec_path(env: Mapping[str, str] | None = None) -> list[str]: ... def getlogin() -> str: ... def getpid() -> int: ... def getppid() -> int: ... def strerror(code: int, /) -> str: ... def umask(mask: int, /) -> int: ... + @final class uname_result(structseq[str], tuple[str, str, str, str, str]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("sysname", "nodename", "release", "version", "machine") + __match_args__: Final = ("sysname", "nodename", "release", "version", "machine") @property def sysname(self) -> str: ... @@ -1023,6 +1086,7 @@ if sys.platform != "win32": def getenvb(key: bytes) -> bytes | None: ... @overload def getenvb(key: bytes, default: _T) -> bytes | _T: ... + def putenv(name: StrOrBytesPath, value: StrOrBytesPath, /) -> None: ... def unsetenv(name: StrOrBytesPath, /) -> None: ... @@ -1109,6 +1173,7 @@ def fdopen( closefd: bool = True, opener: _Opener | None = None, ) -> IO[Any]: ... + def close(fd: int) -> None: ... def closerange(fd_low: int, fd_high: int, /) -> None: ... def device_encoding(fd: int) -> str | None: ... @@ -1154,8 +1219,7 @@ if sys.platform != "win32": def preadv(fd: int, buffers: SupportsLenAndGetItem[WriteableBuffer], offset: int, flags: int = 0, /) -> int: ... def pwritev(fd: int, buffers: SupportsLenAndGetItem[ReadableBuffer], offset: int, flags: int = 0, /) -> int: ... if sys.platform != "darwin": - if sys.version_info >= (3, 10): - RWF_APPEND: Final[int] # docs say available on 3.7+, stubtest says otherwise + RWF_APPEND: Final[int] RWF_DSYNC: Final[int] RWF_SYNC: Final[int] RWF_HIPRI: Final[int] @@ -1182,8 +1246,7 @@ if sys.version_info >= (3, 14): @final class terminal_size(structseq[int], tuple[int, int]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("columns", "lines") + __match_args__: Final = ("columns", "lines") @property def columns(self) -> int: ... @@ -1260,6 +1323,7 @@ def replace( src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = None, dst_dir_fd: int | None = None ) -> None: ... def rmdir(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: ... + @final @type_check_only class _ScandirIterator(Generic[AnyStr]): @@ -1276,11 +1340,76 @@ def scandir(path: None = None) -> _ScandirIterator[str]: ... def scandir(path: int) -> _ScandirIterator[str]: ... @overload def scandir(path: GenericPath[AnyStr]) -> _ScandirIterator[AnyStr]: ... + def stat(path: FileDescriptorOrPath, *, dir_fd: int | None = None, follow_symlinks: bool = True) -> stat_result: ... if sys.platform != "win32": def statvfs(path: FileDescriptorOrPath) -> statvfs_result: ... # Unix only +if sys.platform == "linux" and sys.version_info >= (3, 15): + @final + class statx_result: + @property + def stx_mask(self) -> int: ... + @property + def stx_blksize(self) -> int: ... + @property + def stx_attributes(self) -> int: ... + @property + def stx_attributes_mask(self) -> int: ... + @property + def stx_rdev_major(self) -> int: ... + @property + def stx_rdev_minor(self) -> int: ... + @property + def stx_rdev(self) -> int: ... + @property + def stx_dev_major(self) -> int: ... + @property + def stx_dev_minor(self) -> int: ... + @property + def stx_dev(self) -> int: ... + @property + def stx_mode(self) -> int | None: ... + @property + def stx_nlink(self) -> int | None: ... + @property + def stx_uid(self) -> int | None: ... + @property + def stx_gid(self) -> int | None: ... + @property + def stx_ino(self) -> int | None: ... + @property + def stx_size(self) -> int | None: ... + @property + def stx_blocks(self) -> int | None: ... + @property + def stx_atime(self) -> float | None: ... + @property + def stx_atime_ns(self) -> int | None: ... + @property + def stx_btime(self) -> float | None: ... + @property + def stx_btime_ns(self) -> int | None: ... + @property + def stx_ctime(self) -> float | None: ... + @property + def stx_ctime_ns(self) -> int | None: ... + @property + def stx_mtime(self) -> float | None: ... + @property + def stx_mtime_ns(self) -> int | None: ... + @property + def stx_mnt_id(self) -> int | None: ... + @property + def stx_dio_mem_align(self) -> int | None: ... + @property + def stx_dio_offset_align(self) -> int | None: ... + + def statx( + path: FileDescriptorOrPath, mask: int, *, flags: int = 0, dir_fd: int | None = None, follow_symlinks: bool = True + ) -> statx_result: ... + def symlink( src: StrOrBytesPath, dst: StrOrBytesPath, target_is_directory: bool = False, *, dir_fd: int | None = None ) -> None: ... @@ -1324,6 +1453,7 @@ if sys.platform != "win32": follow_symlinks: bool = False, dir_fd: int | None = None, ) -> Iterator[tuple[bytes, list[bytes], list[bytes], int]]: ... + if sys.platform == "linux": def getxattr(path: FileDescriptorOrPath, attribute: StrOrBytesPath, *, follow_symlinks: bool = True) -> bytes: ... def listxattr(path: FileDescriptorOrPath | None = None, *, follow_symlinks: bool = True) -> list[str]: ... @@ -1408,52 +1538,30 @@ class _wrap_close: def write(self, s: str, /) -> int: ... def writelines(self, lines: Iterable[str], /) -> None: ... -if sys.version_info >= (3, 14): - @deprecated("Soft deprecated. Use the subprocess module instead.") - def popen(cmd: str, mode: str = "r", buffering: int = -1) -> _wrap_close: ... - @deprecated("Soft deprecated. Use the subprocess module instead.") - def spawnl(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ... - @deprecated("Soft deprecated. Use the subprocess module instead.") - def spawnle(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ... # Imprecise sig - -else: - def popen(cmd: str, mode: str = "r", buffering: int = -1) -> _wrap_close: ... - def spawnl(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ... - def spawnle(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ... # Imprecise sig +@deprecated("Soft deprecated. Use the subprocess module instead.") +def popen(cmd: str, mode: str = "r", buffering: int = -1) -> _wrap_close: ... +@deprecated("Soft deprecated. Use the subprocess module instead.") +def spawnl(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ... +@deprecated("Soft deprecated. Use the subprocess module instead.") +def spawnle(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ... # Imprecise sig if sys.platform != "win32": - if sys.version_info >= (3, 14): - @deprecated("Soft deprecated. Use the subprocess module instead.") - def spawnv(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ... - @deprecated("Soft deprecated. Use the subprocess module instead.") - def spawnve(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... - - else: - def spawnv(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ... - def spawnve(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... - + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnv(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ... + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnve(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... else: - if sys.version_info >= (3, 14): - @deprecated("Soft deprecated. Use the subprocess module instead.") - def spawnv(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, /) -> int: ... - @deprecated("Soft deprecated. Use the subprocess module instead.") - def spawnve(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, env: _ExecEnv, /) -> int: ... - - else: - def spawnv(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, /) -> int: ... - def spawnve(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, env: _ExecEnv, /) -> int: ... - -if sys.version_info >= (3, 14): @deprecated("Soft deprecated. Use the subprocess module instead.") - def system(command: StrOrBytesPath) -> int: ... + def spawnv(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, /) -> int: ... + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnve(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, env: _ExecEnv, /) -> int: ... -else: - def system(command: StrOrBytesPath) -> int: ... +@deprecated("Soft deprecated. Use the subprocess module instead.") +def system(command: StrOrBytesPath) -> int: ... @final class times_result(structseq[float], tuple[float, float, float, float, float]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("user", "system", "children_user", "children_system", "elapsed") + __match_args__: Final = ("user", "system", "children_user", "children_system", "elapsed") @property def user(self) -> float: ... @@ -1470,41 +1578,25 @@ def times() -> times_result: ... def waitpid(pid: int, options: int, /) -> tuple[int, int]: ... if sys.platform == "win32": - if sys.version_info >= (3, 10): - def startfile( - filepath: StrOrBytesPath, - operation: str = ..., - arguments: str = "", - cwd: StrOrBytesPath | None = None, - show_cmd: int = 1, - ) -> None: ... - else: - def startfile(filepath: StrOrBytesPath, operation: str = ...) -> None: ... + def startfile( + filepath: StrOrBytesPath, operation: str = ..., arguments: str = "", cwd: StrOrBytesPath | None = None, show_cmd: int = 1 + ) -> None: ... else: - if sys.version_info >= (3, 14): - @deprecated("Soft deprecated. Use the subprocess module instead.") - def spawnlp(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ... - @deprecated("Soft deprecated. Use the subprocess module instead.") - def spawnlpe(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ... # Imprecise signature - @deprecated("Soft deprecated. Use the subprocess module instead.") - def spawnvp(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ... - @deprecated("Soft deprecated. Use the subprocess module instead.") - def spawnvpe(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... - - else: - def spawnlp(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ... - def spawnlpe(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ... # Imprecise signature - def spawnvp(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ... - def spawnvpe(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... - + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnlp(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ... + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnlpe(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ... # Imprecise signature + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnvp(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ... + @deprecated("Soft deprecated. Use the subprocess module instead.") + def spawnvpe(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... def wait() -> tuple[int, int]: ... # Unix only # Added to MacOS in 3.13 if sys.platform != "darwin" or sys.version_info >= (3, 13): @final class waitid_result(structseq[int], tuple[int, int, int, int, int]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("si_pid", "si_uid", "si_signo", "si_status", "si_code") + __match_args__: Final = ("si_pid", "si_uid", "si_signo", "si_status", "si_code") @property def si_pid(self) -> int: ... @@ -1627,8 +1719,7 @@ else: if sys.platform != "win32": @final class sched_param(structseq[int], tuple[int]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("sched_priority",) + __match_args__: Final = ("sched_priority",) def __new__(cls, sched_priority: int) -> Self: ... @property @@ -1719,7 +1810,7 @@ if sys.version_info >= (3, 12) and sys.platform == "win32": def listmounts(volume: str) -> list[str]: ... def listvolumes() -> list[str]: ... -if sys.version_info >= (3, 10) and sys.platform == "linux": +if sys.platform == "linux": EFD_CLOEXEC: Final[int] EFD_NONBLOCK: Final[int] EFD_SEMAPHORE: Final[int] diff --git a/mypy/typeshed/stdlib/parser.pyi b/mypy/typeshed/stdlib/parser.pyi deleted file mode 100644 index 9b287fcc6529d..0000000000000 --- a/mypy/typeshed/stdlib/parser.pyi +++ /dev/null @@ -1,25 +0,0 @@ -from _typeshed import StrOrBytesPath -from collections.abc import Sequence -from types import CodeType -from typing import Any, ClassVar, final - -def expr(source: str) -> STType: ... -def suite(source: str) -> STType: ... -def sequence2st(sequence: Sequence[Any]) -> STType: ... -def tuple2st(sequence: Sequence[Any]) -> STType: ... -def st2list(st: STType, line_info: bool = False, col_info: bool = False) -> list[Any]: ... -def st2tuple(st: STType, line_info: bool = False, col_info: bool = False) -> tuple[Any, ...]: ... -def compilest(st: STType, filename: StrOrBytesPath = ...) -> CodeType: ... -def isexpr(st: STType) -> bool: ... -def issuite(st: STType) -> bool: ... - -class ParserError(Exception): ... - -@final -class STType: - __hash__: ClassVar[None] # type: ignore[assignment] - def compile(self, filename: StrOrBytesPath = ...) -> CodeType: ... - def isexpr(self) -> bool: ... - def issuite(self) -> bool: ... - def tolist(self, line_info: bool = False, col_info: bool = False) -> list[Any]: ... - def totuple(self, line_info: bool = False, col_info: bool = False) -> tuple[Any, ...]: ... diff --git a/mypy/typeshed/stdlib/pathlib/__init__.pyi b/mypy/typeshed/stdlib/pathlib/__init__.pyi index 4f094130665c8..0d3b5aef56bdf 100644 --- a/mypy/typeshed/stdlib/pathlib/__init__.pyi +++ b/mypy/typeshed/stdlib/pathlib/__init__.pyi @@ -29,31 +29,32 @@ if sys.version_info >= (3, 13): __all__ += ["UnsupportedOperation"] class PurePath(PathLike[str]): - if sys.version_info >= (3, 13): - __slots__ = ( - "_raw_paths", - "_drv", - "_root", - "_tail_cached", - "_str", - "_str_normcase_cached", - "_parts_normcase_cached", - "_hash", - ) - elif sys.version_info >= (3, 12): - __slots__ = ( - "_raw_paths", - "_drv", - "_root", - "_tail_cached", - "_str", - "_str_normcase_cached", - "_parts_normcase_cached", - "_lines_cached", - "_hash", - ) - else: - __slots__ = ("_drv", "_root", "_parts", "_str", "_hash", "_pparts", "_cached_cparts") + if sys.version_info < (3, 15): + if sys.version_info >= (3, 13): + __slots__ = ( + "_raw_paths", + "_drv", + "_root", + "_tail_cached", + "_str", + "_str_normcase_cached", + "_parts_normcase_cached", + "_hash", + ) + elif sys.version_info >= (3, 12): + __slots__ = ( + "_raw_paths", + "_drv", + "_root", + "_tail_cached", + "_str", + "_str_normcase_cached", + "_parts_normcase_cached", + "_lines_cached", + "_hash", + ) + else: + __slots__ = ("_drv", "_root", "_parts", "_str", "_hash", "_pparts", "_cached_cparts") if sys.version_info >= (3, 13): parser: ClassVar[types.ModuleType] def full_match(self, pattern: StrPath, *, case_sensitive: bool | None = None) -> bool: ... @@ -82,6 +83,9 @@ class PurePath(PathLike[str]): def __hash__(self) -> int: ... def __fspath__(self) -> str: ... + if sys.version_info >= (3, 15): + def __vfspath__(self) -> str: ... + def __lt__(self, other: PurePath) -> bool: ... def __le__(self, other: PurePath) -> bool: ... def __gt__(self, other: PurePath) -> bool: ... @@ -93,24 +97,23 @@ class PurePath(PathLike[str]): @deprecated("Deprecated since Python 3.14; will be removed in Python 3.19. Use `Path.as_uri()` instead.") def as_uri(self) -> str: ... def is_absolute(self) -> bool: ... - if sys.version_info >= (3, 13): - @deprecated( - "Deprecated since Python 3.13; will be removed in Python 3.15. " - "Use `os.path.isreserved()` to detect reserved paths on Windows." - ) - def is_reserved(self) -> bool: ... - else: - def is_reserved(self) -> bool: ... + if sys.version_info < (3, 15): + if sys.version_info >= (3, 13): + @deprecated( + "Deprecated since Python 3.13; will be removed in Python 3.15. " + "Use `os.path.isreserved()` to detect reserved paths on Windows." + ) + def is_reserved(self) -> bool: ... + else: + def is_reserved(self) -> bool: ... if sys.version_info >= (3, 14): def is_relative_to(self, other: StrPath) -> bool: ... - elif sys.version_info >= (3, 12): + else: @overload def is_relative_to(self, other: StrPath, /) -> bool: ... @overload @deprecated("Passing additional arguments is deprecated since Python 3.12; removed in Python 3.14.") def is_relative_to(self, other: StrPath, /, *_deprecated: StrPath) -> bool: ... - else: - def is_relative_to(self, *other: StrPath) -> bool: ... if sys.version_info >= (3, 12): def match(self, path_pattern: str, *, case_sensitive: bool | None = None) -> bool: ... @@ -151,10 +154,8 @@ class PureWindowsPath(PurePath): class Path(PurePath): if sys.version_info >= (3, 14): __slots__ = ("_info",) - elif sys.version_info >= (3, 10): - __slots__ = () else: - __slots__ = ("_accessor",) + __slots__ = () if sys.version_info >= (3, 12): def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ... # pyright: ignore[reportInconsistentConstructor] @@ -163,12 +164,8 @@ class Path(PurePath): @classmethod def cwd(cls) -> Self: ... - if sys.version_info >= (3, 10): - def stat(self, *, follow_symlinks: bool = True) -> stat_result: ... - def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: ... - else: - def stat(self) -> stat_result: ... - def chmod(self, mode: int) -> None: ... + def stat(self, *, follow_symlinks: bool = True) -> stat_result: ... + def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: ... if sys.version_info >= (3, 13): @classmethod @@ -216,18 +213,22 @@ class Path(PurePath): if sys.version_info >= (3, 14): @property def info(self) -> PathInfo: ... + @overload def move_into(self, target_dir: _PathT) -> _PathT: ... # type: ignore[overload-overlap] @overload def move_into(self, target_dir: StrPath) -> Self: ... # type: ignore[overload-overlap] + @overload def move(self, target: _PathT) -> _PathT: ... # type: ignore[overload-overlap] @overload def move(self, target: StrPath) -> Self: ... # type: ignore[overload-overlap] + @overload def copy_into(self, target_dir: _PathT, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> _PathT: ... # type: ignore[overload-overlap] @overload def copy_into(self, target_dir: StrPath, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> Self: ... # type: ignore[overload-overlap] + @overload def copy(self, target: _PathT, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> _PathT: ... # type: ignore[overload-overlap] @overload @@ -314,20 +315,12 @@ class Path(PurePath): def is_mount(self) -> bool: ... def readlink(self) -> Self: ... - - if sys.version_info >= (3, 10): - def rename(self, target: StrPath) -> Self: ... - def replace(self, target: StrPath) -> Self: ... - else: - def rename(self, target: str | PurePath) -> Self: ... - def replace(self, target: str | PurePath) -> Self: ... - + def rename(self, target: StrPath) -> Self: ... + def replace(self, target: StrPath) -> Self: ... def resolve(self, strict: bool = False) -> Self: ... def rmdir(self) -> None: ... def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None: ... - if sys.version_info >= (3, 10): - def hardlink_to(self, target: StrOrBytesPath) -> None: ... - + def hardlink_to(self, target: StrOrBytesPath) -> None: ... def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: ... def unlink(self, missing_ok: bool = False) -> None: ... @classmethod @@ -337,18 +330,12 @@ class Path(PurePath): def read_bytes(self) -> bytes: ... def samefile(self, other_path: StrPath) -> bool: ... def write_bytes(self, data: ReadableBuffer) -> int: ... - if sys.version_info >= (3, 10): - def write_text( - self, data: str, encoding: str | None = None, errors: str | None = None, newline: str | None = None - ) -> int: ... - else: - def write_text(self, data: str, encoding: str | None = None, errors: str | None = None) -> int: ... + def write_text( + self, data: str, encoding: str | None = None, errors: str | None = None, newline: str | None = None + ) -> int: ... if sys.version_info < (3, 12): - if sys.version_info >= (3, 10): - @deprecated("Deprecated since Python 3.10; removed in Python 3.12. Use `hardlink_to()` instead.") - def link_to(self, target: StrOrBytesPath) -> None: ... - else: - def link_to(self, target: StrOrBytesPath) -> None: ... + @deprecated("Deprecated since Python 3.10; removed in Python 3.12. Use `hardlink_to()` instead.") + def link_to(self, target: StrOrBytesPath) -> None: ... if sys.version_info >= (3, 12): def walk( self, top_down: bool = True, on_error: Callable[[OSError], object] | None = None, follow_symlinks: bool = False diff --git a/mypy/typeshed/stdlib/pdb.pyi b/mypy/typeshed/stdlib/pdb.pyi index dc1cf3b280860..289637cb5f048 100644 --- a/mypy/typeshed/stdlib/pdb.pyi +++ b/mypy/typeshed/stdlib/pdb.pyi @@ -1,14 +1,14 @@ import signal import sys +from _typeshed import ReadableBuffer from bdb import Bdb, _Backend from cmd import Cmd from collections.abc import Callable, Iterable, Mapping, Sequence -from inspect import _SourceObjectType from linecache import _ModuleGlobals from rlcompleter import Completer from types import CodeType, FrameType, TracebackType -from typing import IO, Any, ClassVar, Final, Literal, TypeVar -from typing_extensions import ParamSpec, Self, TypeAlias, deprecated +from typing import IO, Any, ClassVar, Final, Literal, ParamSpec, TypeAlias, TypeVar +from typing_extensions import Self, deprecated __all__ = ["run", "pm", "Pdb", "runeval", "runctx", "runcall", "set_trace", "post_mortem", "help"] if sys.version_info >= (3, 14): @@ -22,9 +22,15 @@ line_prefix: Final[str] # undocumented class Restart(Exception): ... -def run(statement: str, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None) -> None: ... -def runeval(expression: str, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None) -> Any: ... -def runctx(statement: str, globals: dict[str, Any], locals: Mapping[str, Any]) -> None: ... +def run( # matches `builtins.exec` + statement: str | ReadableBuffer | CodeType, globals: dict[str, Any] | None = None, locals: Mapping[str, object] | None = None +) -> None: ... +def runctx( # matches `builtins.exec` + statement: str | ReadableBuffer | CodeType, globals: dict[str, Any], locals: Mapping[str, object] +) -> None: ... +def runeval( # matches `builtins.eval` + expression: str | ReadableBuffer | CodeType, globals: dict[str, Any] | None = None, locals: Mapping[str, object] | None = None +) -> Any: ... def runcall(func: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> _T | None: ... if sys.version_info >= (3, 14): @@ -130,7 +136,11 @@ class Pdb(Bdb, Cmd): else: def print_stack_trace(self) -> None: ... - def print_stack_entry(self, frame_lineno: tuple[FrameType, int], prompt_prefix: str = "\n-> ") -> None: ... + if sys.version_info >= (3, 15): + def print_stack_entry(self, frame_lineno: tuple[FrameType, int], prompt_prefix: str | None = None) -> None: ... + else: + def print_stack_entry(self, frame_lineno: tuple[FrameType, int], prompt_prefix: str = "\n-> ") -> None: ... + def lookupmodule(self, filename: str) -> str | None: ... if sys.version_info < (3, 11): def _runscript(self, filename: str) -> None: ... @@ -259,10 +269,6 @@ class Pdb(Bdb, Cmd): def find_function(funcname: str, filename: str) -> tuple[str, str, int] | None: ... def main() -> None: ... def help() -> None: ... - -if sys.version_info < (3, 10): - def getsourcelines(obj: _SourceObjectType) -> tuple[list[str], int]: ... - def lasti2lineno(code: CodeType, lasti: int) -> int: ... class _rstr(str): diff --git a/mypy/typeshed/stdlib/pickletools.pyi b/mypy/typeshed/stdlib/pickletools.pyi index 8bbfaba31b671..98353d9608880 100644 --- a/mypy/typeshed/stdlib/pickletools.pyi +++ b/mypy/typeshed/stdlib/pickletools.pyi @@ -1,7 +1,6 @@ import sys from collections.abc import Callable, Iterator, MutableMapping -from typing import IO, Any, Final -from typing_extensions import TypeAlias +from typing import IO, Any, Final, TypeAlias __all__ = ["dis", "genops", "optimize"] diff --git a/mypy/typeshed/stdlib/pkgutil.pyi b/mypy/typeshed/stdlib/pkgutil.pyi index 7c70dcc4c5ab1..365792bed9528 100644 --- a/mypy/typeshed/stdlib/pkgutil.pyi +++ b/mypy/typeshed/stdlib/pkgutil.pyi @@ -39,14 +39,10 @@ if sys.version_info < (3, 12): def __init__(self, fullname: str, file: IO[str], filename: StrOrBytesPath, etc: tuple[str, str, int]) -> None: ... if sys.version_info < (3, 14): - if sys.version_info >= (3, 12): - @deprecated("Deprecated since Python 3.12; removed in Python 3.14. Use `importlib.util.find_spec()` instead.") - def find_loader(fullname: str) -> LoaderProtocol | None: ... - @deprecated("Deprecated since Python 3.12; removed in Python 3.14. Use `importlib.util.find_spec()` instead.") - def get_loader(module_or_name: str) -> LoaderProtocol | None: ... - else: - def find_loader(fullname: str) -> LoaderProtocol | None: ... - def get_loader(module_or_name: str) -> LoaderProtocol | None: ... + @deprecated("Deprecated since Python 3.12; removed in Python 3.14. Use `importlib.util.find_spec()` instead.") + def find_loader(fullname: str) -> LoaderProtocol | None: ... + @deprecated("Deprecated since Python 3.12; removed in Python 3.14. Use `importlib.util.find_spec()` instead.") + def get_loader(module_or_name: str) -> LoaderProtocol | None: ... def get_importer(path_item: StrOrBytesPath) -> PathEntryFinderProtocol | None: ... def iter_importers(fullname: str = "") -> Iterator[MetaPathFinderProtocol | PathEntryFinderProtocol]: ... @@ -56,4 +52,9 @@ def walk_packages( path: Iterable[StrOrBytesPath] | None = None, prefix: str = "", onerror: Callable[[str], object] | None = None ) -> Iterator[ModuleInfo]: ... def get_data(package: str, resource: str) -> bytes | None: ... -def resolve_name(name: str) -> Any: ... + +if sys.version_info >= (3, 15): + def resolve_name(name: str, *, strict: bool = False) -> Any: ... + +else: + def resolve_name(name: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/platform.pyi b/mypy/typeshed/stdlib/platform.pyi index 69d702bb155cd..7d837436ef794 100644 --- a/mypy/typeshed/stdlib/platform.pyi +++ b/mypy/typeshed/stdlib/platform.pyi @@ -10,7 +10,7 @@ def mac_ver( release: str = "", versioninfo: tuple[str, str, str] = ("", "", ""), machine: str = "" ) -> tuple[str, tuple[str, str, str], str]: ... -if sys.version_info >= (3, 13): +if sys.version_info < (3, 15): @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") def java_ver( release: str = "", @@ -19,14 +19,6 @@ if sys.version_info >= (3, 13): osinfo: tuple[str, str, str] = ("", "", ""), ) -> tuple[str, str, tuple[str, str, str], tuple[str, str, str]]: ... -else: - def java_ver( - release: str = "", - vendor: str = "", - vminfo: tuple[str, str, str] = ("", "", ""), - osinfo: tuple[str, str, str] = ("", "", ""), - ) -> tuple[str, str, tuple[str, str, str], tuple[str, str, str]]: ... - def system_alias(system: str, release: str, version: str) -> tuple[str, str, str]: ... def architecture(executable: str = sys.executable, bits: str = "", linkage: str = "") -> tuple[str, str]: ... @@ -57,9 +49,7 @@ if sys.version_info >= (3, 12): else: @disjoint_base class uname_result(_uname_result_base): - if sys.version_info >= (3, 10): - __match_args__ = ("system", "node", "release", "version", "machine") # pyright: ignore[reportAssignmentType] - + __match_args__ = ("system", "node", "release", "version", "machine") # pyright: ignore[reportAssignmentType] def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self: ... @property def processor(self) -> str: ... @@ -79,9 +69,7 @@ def python_revision() -> str: ... def python_build() -> tuple[str, str]: ... def python_compiler() -> str: ... def platform(aliased: bool = False, terse: bool = False) -> str: ... - -if sys.version_info >= (3, 10): - def freedesktop_os_release() -> dict[str, str]: ... +def freedesktop_os_release() -> dict[str, str]: ... if sys.version_info >= (3, 13): class AndroidVer(NamedTuple): diff --git a/mypy/typeshed/stdlib/poplib.pyi b/mypy/typeshed/stdlib/poplib.pyi index f5669ec87e87e..d4555a6b5ec0c 100644 --- a/mypy/typeshed/stdlib/poplib.pyi +++ b/mypy/typeshed/stdlib/poplib.pyi @@ -4,8 +4,8 @@ import sys from _typeshed import StrOrBytesPath from builtins import list as _list # conflicts with a method named "list" from re import Pattern -from typing import Any, BinaryIO, Final, NoReturn, overload -from typing_extensions import TypeAlias, deprecated +from typing import Any, BinaryIO, Final, NoReturn, TypeAlias, overload +from typing_extensions import deprecated __all__ = ["POP3", "error_proto", "POP3_SSL"] @@ -44,10 +44,12 @@ class POP3: timestamp: Pattern[str] def apop(self, user: str, password: str) -> bytes: ... def top(self, which: Any, howmuch: int) -> _LongResp: ... + @overload def uidl(self) -> _LongResp: ... @overload def uidl(self, which: Any) -> bytes: ... + def utf8(self) -> bytes: ... def capa(self) -> dict[str, _list[str]]: ... def stls(self, context: ssl.SSLContext | None = None) -> bytes: ... @@ -83,6 +85,7 @@ class POP3_SSL(POP3): timeout: float = ..., context: None = None, ) -> None: ... + keyfile: StrOrBytesPath | None certfile: StrOrBytesPath | None # "context" is actually the last argument, diff --git a/mypy/typeshed/stdlib/posix.pyi b/mypy/typeshed/stdlib/posix.pyi index 6d0d76ab82176..36bb5be18e88f 100644 --- a/mypy/typeshed/stdlib/posix.pyi +++ b/mypy/typeshed/stdlib/posix.pyi @@ -39,6 +39,7 @@ if sys.platform != "win32": O_DIRECTORY as O_DIRECTORY, O_DSYNC as O_DSYNC, O_EXCL as O_EXCL, + O_FSYNC as O_FSYNC, O_NDELAY as O_NDELAY, O_NOCTTY as O_NOCTTY, O_NOFOLLOW as O_NOFOLLOW, @@ -227,9 +228,6 @@ if sys.platform != "win32": writev as writev, ) - if sys.version_info >= (3, 10): - from os import O_FSYNC as O_FSYNC - if sys.version_info >= (3, 11): from os import login_tty as login_tty @@ -265,6 +263,36 @@ if sys.platform != "win32": if sys.platform != "linux" and sys.version_info >= (3, 13): from os import O_EXEC as O_EXEC, O_SEARCH as O_SEARCH + if sys.version_info >= (3, 15): + from os import NODEV as NODEV + + if sys.version_info >= (3, 15) and sys.platform == "linux": + from os import ( + AT_NO_AUTOMOUNT as AT_NO_AUTOMOUNT, + AT_STATX_DONT_SYNC as AT_STATX_DONT_SYNC, + AT_STATX_FORCE_SYNC as AT_STATX_FORCE_SYNC, + AT_STATX_SYNC_AS_STAT as AT_STATX_SYNC_AS_STAT, + STATX_ATIME as STATX_ATIME, + STATX_BASIC_STATS as STATX_BASIC_STATS, + STATX_BLOCKS as STATX_BLOCKS, + STATX_BTIME as STATX_BTIME, + STATX_CTIME as STATX_CTIME, + STATX_DIOALIGN as STATX_DIOALIGN, + STATX_GID as STATX_GID, + STATX_INO as STATX_INO, + STATX_MNT_ID as STATX_MNT_ID, + STATX_MNT_ID_UNIQUE as STATX_MNT_ID_UNIQUE, + STATX_MODE as STATX_MODE, + STATX_MTIME as STATX_MTIME, + STATX_NLINK as STATX_NLINK, + STATX_SIZE as STATX_SIZE, + STATX_TYPE as STATX_TYPE, + STATX_UID as STATX_UID, + _clearenv as _clearenv, + statx as statx, + statx_result as statx_result, + ) + if sys.platform != "darwin": from os import ( POSIX_FADV_DONTNEED as POSIX_FADV_DONTNEED, @@ -273,6 +301,7 @@ if sys.platform != "win32": POSIX_FADV_RANDOM as POSIX_FADV_RANDOM, POSIX_FADV_SEQUENTIAL as POSIX_FADV_SEQUENTIAL, POSIX_FADV_WILLNEED as POSIX_FADV_WILLNEED, + RWF_APPEND as RWF_APPEND, RWF_DSYNC as RWF_DSYNC, RWF_HIPRI as RWF_HIPRI, RWF_NOWAIT as RWF_NOWAIT, @@ -303,14 +332,14 @@ if sys.platform != "win32": setresuid as setresuid, ) - if sys.version_info >= (3, 10): - from os import RWF_APPEND as RWF_APPEND - if sys.platform != "darwin" or sys.version_info >= (3, 13): from os import waitid as waitid, waitid_result as waitid_result if sys.platform == "linux": from os import ( + EFD_CLOEXEC as EFD_CLOEXEC, + EFD_NONBLOCK as EFD_NONBLOCK, + EFD_SEMAPHORE as EFD_SEMAPHORE, GRND_NONBLOCK as GRND_NONBLOCK, GRND_RANDOM as GRND_RANDOM, MFD_ALLOW_SEALING as MFD_ALLOW_SEALING, @@ -341,10 +370,16 @@ if sys.platform != "win32": SCHED_BATCH as SCHED_BATCH, SCHED_IDLE as SCHED_IDLE, SCHED_RESET_ON_FORK as SCHED_RESET_ON_FORK, + SPLICE_F_MORE as SPLICE_F_MORE, + SPLICE_F_MOVE as SPLICE_F_MOVE, + SPLICE_F_NONBLOCK as SPLICE_F_NONBLOCK, XATTR_CREATE as XATTR_CREATE, XATTR_REPLACE as XATTR_REPLACE, XATTR_SIZE_MAX as XATTR_SIZE_MAX, copy_file_range as copy_file_range, + eventfd as eventfd, + eventfd_read as eventfd_read, + eventfd_write as eventfd_write, getrandom as getrandom, getxattr as getxattr, listxattr as listxattr, @@ -352,22 +387,9 @@ if sys.platform != "win32": pidfd_open as pidfd_open, removexattr as removexattr, setxattr as setxattr, + splice as splice, ) - if sys.version_info >= (3, 10): - from os import ( - EFD_CLOEXEC as EFD_CLOEXEC, - EFD_NONBLOCK as EFD_NONBLOCK, - EFD_SEMAPHORE as EFD_SEMAPHORE, - SPLICE_F_MORE as SPLICE_F_MORE, - SPLICE_F_MOVE as SPLICE_F_MOVE, - SPLICE_F_NONBLOCK as SPLICE_F_NONBLOCK, - eventfd as eventfd, - eventfd_read as eventfd_read, - eventfd_write as eventfd_write, - splice as splice, - ) - if sys.version_info >= (3, 12): from os import ( CLONE_FILES as CLONE_FILES, @@ -390,6 +412,8 @@ if sys.platform != "win32": ) if sys.platform == "darwin": + from os import O_EVTONLY as O_EVTONLY, O_NOFOLLOW_ANY as O_NOFOLLOW_ANY, O_SYMLINK as O_SYMLINK + if sys.version_info >= (3, 12): from os import ( PRIO_DARWIN_BG as PRIO_DARWIN_BG, @@ -397,8 +421,6 @@ if sys.platform != "win32": PRIO_DARWIN_PROCESS as PRIO_DARWIN_PROCESS, PRIO_DARWIN_THREAD as PRIO_DARWIN_THREAD, ) - if sys.platform == "darwin" and sys.version_info >= (3, 10): - from os import O_EVTONLY as O_EVTONLY, O_NOFOLLOW_ANY as O_NOFOLLOW_ANY, O_SYMLINK as O_SYMLINK # Not same as os.environ or os.environb # Because of this variable, we can't do "from posix import *" in os/__init__.pyi diff --git a/mypy/typeshed/stdlib/posixpath.pyi b/mypy/typeshed/stdlib/posixpath.pyi index 84e1b1e028bde..b4068629b698e 100644 --- a/mypy/typeshed/stdlib/posixpath.pyi +++ b/mypy/typeshed/stdlib/posixpath.pyi @@ -17,6 +17,9 @@ from genericpath import ( samestat as samestat, ) +if sys.version_info >= (3, 15): + from genericpath import ALL_BUT_LAST as ALL_BUT_LAST + if sys.version_info >= (3, 13): from genericpath import isdevdrive as isdevdrive from os import PathLike @@ -64,6 +67,8 @@ __all__ = [ "commonpath", ] __all__ += ["ALLOW_MISSING"] +if sys.version_info >= (3, 15): + __all__ += ["ALL_BUT_LAST"] if sys.version_info >= (3, 12): __all__ += ["isjunction", "splitroot"] if sys.version_info >= (3, 13): @@ -85,30 +90,54 @@ devnull: LiteralString def abspath(path: PathLike[AnyStr]) -> AnyStr: ... @overload def abspath(path: AnyStr) -> AnyStr: ... -@overload -def basename(p: PathLike[AnyStr]) -> AnyStr: ... -@overload -def basename(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ... -@overload -def dirname(p: PathLike[AnyStr]) -> AnyStr: ... -@overload -def dirname(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ... + +if sys.version_info >= (3, 15): + @overload + def basename(p: PathLike[AnyStr], /) -> AnyStr: ... + @overload + def basename(p: AnyOrLiteralStr, /) -> AnyOrLiteralStr: ... + + @overload + def dirname(p: PathLike[AnyStr], /) -> AnyStr: ... + @overload + def dirname(p: AnyOrLiteralStr, /) -> AnyOrLiteralStr: ... +else: + @overload + def basename(p: PathLike[AnyStr]) -> AnyStr: ... + @overload + def basename(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ... + + @overload + def dirname(p: PathLike[AnyStr]) -> AnyStr: ... + @overload + def dirname(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ... + @overload def expanduser(path: PathLike[AnyStr]) -> AnyStr: ... @overload def expanduser(path: AnyStr) -> AnyStr: ... + @overload def expandvars(path: PathLike[AnyStr]) -> AnyStr: ... @overload def expandvars(path: AnyStr) -> AnyStr: ... -@overload -def normcase(s: PathLike[AnyStr]) -> AnyStr: ... -@overload -def normcase(s: AnyOrLiteralStr) -> AnyOrLiteralStr: ... + +if sys.version_info >= (3, 15): + @overload + def normcase(s: PathLike[AnyStr], /) -> AnyStr: ... + @overload + def normcase(s: AnyOrLiteralStr, /) -> AnyOrLiteralStr: ... +else: + @overload + def normcase(s: PathLike[AnyStr]) -> AnyStr: ... + @overload + def normcase(s: AnyOrLiteralStr) -> AnyOrLiteralStr: ... + @overload def normpath(path: PathLike[AnyStr]) -> AnyStr: ... @overload def normpath(path: AnyOrLiteralStr) -> AnyOrLiteralStr: ... + @overload def commonpath(paths: Iterable[LiteralString]) -> LiteralString: ... @overload @@ -116,7 +145,7 @@ def commonpath(paths: Iterable[StrPath]) -> str: ... @overload def commonpath(paths: Iterable[BytesPath]) -> bytes: ... -# First parameter is not actually pos-only, +# First parameter is not actually pos-only before Python 3.15, # but must be defined as pos-only in the stub or cross-platform code doesn't type-check, # as the parameter name is different in ntpath.join() @overload @@ -125,36 +154,77 @@ def join(a: LiteralString, /, *paths: LiteralString) -> LiteralString: ... def join(a: StrPath, /, *paths: StrPath) -> str: ... @overload def join(a: BytesPath, /, *paths: BytesPath) -> bytes: ... -@overload -def realpath(filename: PathLike[AnyStr], *, strict: bool | _AllowMissingType = False) -> AnyStr: ... -@overload -def realpath(filename: AnyStr, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + +if sys.version_info >= (3, 15): + @overload + def realpath(filename: PathLike[AnyStr], /, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + @overload + def realpath(filename: AnyStr, /, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... +else: + @overload + def realpath(filename: PathLike[AnyStr], *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + @overload + def realpath(filename: AnyStr, *, strict: bool | _AllowMissingType = False) -> AnyStr: ... + @overload def relpath(path: LiteralString, start: LiteralString | None = None) -> LiteralString: ... @overload def relpath(path: BytesPath, start: BytesPath | None = None) -> bytes: ... @overload def relpath(path: StrPath, start: StrPath | None = None) -> str: ... -@overload -def split(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... -@overload -def split(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... -@overload -def splitdrive(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... -@overload -def splitdrive(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... -@overload -def splitext(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... -@overload -def splitext(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... -def isabs(s: StrOrBytesPath) -> bool: ... + +if sys.version_info >= (3, 15): + @overload + def split(p: PathLike[AnyStr], /) -> tuple[AnyStr, AnyStr]: ... + @overload + def split(p: AnyOrLiteralStr, /) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... + + @overload + def splitdrive(p: PathLike[AnyStr], /) -> tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: AnyOrLiteralStr, /) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... +else: + @overload + def split(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... + @overload + def split(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... + + @overload + def splitdrive(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... + @overload + def splitdrive(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... + +if sys.version_info >= (3, 15): + @overload + def splitext(p: PathLike[AnyStr], /) -> tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: AnyOrLiteralStr, /) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... +else: + @overload + def splitext(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... + @overload + def splitext(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... + +if sys.version_info >= (3, 15): + def isabs(s: StrOrBytesPath, /) -> bool: ... + +else: + def isabs(s: StrOrBytesPath) -> bool: ... + def islink(path: FileDescriptorOrPath) -> bool: ... def ismount(path: FileDescriptorOrPath) -> bool: ... def lexists(path: FileDescriptorOrPath) -> bool: ... if sys.version_info >= (3, 12): def isjunction(path: StrOrBytesPath) -> bool: ... - @overload - def splitroot(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr, AnyOrLiteralStr]: ... - @overload - def splitroot(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr, AnyStr]: ... + + if sys.version_info >= (3, 15): + @overload + def splitroot(path: AnyOrLiteralStr, /) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr, AnyOrLiteralStr]: ... + @overload + def splitroot(path: PathLike[AnyStr], /) -> tuple[AnyStr, AnyStr, AnyStr]: ... + else: + @overload + def splitroot(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr, AnyOrLiteralStr]: ... + @overload + def splitroot(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr, AnyStr]: ... diff --git a/mypy/typeshed/stdlib/pprint.pyi b/mypy/typeshed/stdlib/pprint.pyi index 1e80462e25657..1d3705ec6ff67 100644 --- a/mypy/typeshed/stdlib/pprint.pyi +++ b/mypy/typeshed/stdlib/pprint.pyi @@ -5,11 +5,11 @@ from typing import IO __all__ = ["pprint", "pformat", "isreadable", "isrecursive", "saferepr", "PrettyPrinter", "pp"] -if sys.version_info >= (3, 10): +if sys.version_info >= (3, 15): def pformat( object: object, - indent: int = 1, - width: int = 80, + indent: int = 4, + width: int = 88, depth: int | None = None, *, compact: bool = False, @@ -26,14 +26,15 @@ else: *, compact: bool = False, sort_dicts: bool = True, + underscore_numbers: bool = False, ) -> str: ... -if sys.version_info >= (3, 10): +if sys.version_info >= (3, 15): def pp( object: object, stream: IO[str] | None = None, - indent: int = 1, - width: int = 80, + indent: int = 4, + width: int = 88, depth: int | None = None, *, compact: bool = False, @@ -51,14 +52,15 @@ else: *, compact: bool = False, sort_dicts: bool = False, + underscore_numbers: bool = False, ) -> None: ... -if sys.version_info >= (3, 10): +if sys.version_info >= (3, 15): def pprint( object: object, stream: IO[str] | None = None, - indent: int = 1, - width: int = 80, + indent: int = 4, + width: int = 88, depth: int | None = None, *, compact: bool = False, @@ -76,6 +78,7 @@ else: *, compact: bool = False, sort_dicts: bool = True, + underscore_numbers: bool = False, ) -> None: ... def isreadable(object: object) -> bool: ... @@ -83,11 +86,11 @@ def isrecursive(object: object) -> bool: ... def saferepr(object: object) -> str: ... class PrettyPrinter: - if sys.version_info >= (3, 10): + if sys.version_info >= (3, 15): def __init__( self, - indent: int = 1, - width: int = 80, + indent: int = 4, + width: int = 88, depth: int | None = None, stream: IO[str] | None = None, *, @@ -105,6 +108,7 @@ class PrettyPrinter: *, compact: bool = False, sort_dicts: bool = True, + underscore_numbers: bool = False, ) -> None: ... def pformat(self, object: object) -> str: ... @@ -155,5 +159,4 @@ class PrettyPrinter: self, items: list[object], stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int ) -> None: ... def _repr(self, object: object, context: dict[int, int], level: int) -> str: ... - if sys.version_info >= (3, 10): - def _safe_repr(self, object: object, context: dict[int, int], maxlevels: int, level: int) -> tuple[str, bool, bool]: ... + def _safe_repr(self, object: object, context: dict[int, int], maxlevels: int, level: int) -> tuple[str, bool, bool]: ... diff --git a/mypy/typeshed/stdlib/profile.pyi b/mypy/typeshed/stdlib/profile.pyi index 696193d9dc169..06ce9a0e44c82 100644 --- a/mypy/typeshed/stdlib/profile.pyi +++ b/mypy/typeshed/stdlib/profile.pyi @@ -1,7 +1,7 @@ from _typeshed import StrOrBytesPath from collections.abc import Callable, Mapping -from typing import Any, TypeVar -from typing_extensions import ParamSpec, Self, TypeAlias +from typing import Any, ParamSpec, TypeAlias, TypeVar +from typing_extensions import Self __all__ = ["run", "runctx", "Profile"] diff --git a/mypy/typeshed/stdlib/profiling/__init__.pyi b/mypy/typeshed/stdlib/profiling/__init__.pyi new file mode 100644 index 0000000000000..435f5a6cc66c3 --- /dev/null +++ b/mypy/typeshed/stdlib/profiling/__init__.pyi @@ -0,0 +1,3 @@ +from . import sampling as sampling, tracing as tracing + +__all__ = ("tracing", "sampling") diff --git a/mypy/typeshed/stdlib/profiling/sampling/__init__.pyi b/mypy/typeshed/stdlib/profiling/sampling/__init__.pyi new file mode 100644 index 0000000000000..1f8b3f7d98fef --- /dev/null +++ b/mypy/typeshed/stdlib/profiling/sampling/__init__.pyi @@ -0,0 +1,17 @@ +from .collector import Collector as Collector +from .gecko_collector import GeckoCollector as GeckoCollector +from .heatmap_collector import HeatmapCollector as HeatmapCollector +from .jsonl_collector import JsonlCollector as JsonlCollector +from .pstats_collector import PstatsCollector as PstatsCollector +from .stack_collector import CollapsedStackCollector as CollapsedStackCollector +from .string_table import StringTable as StringTable + +__all__ = ( + "Collector", + "PstatsCollector", + "CollapsedStackCollector", + "HeatmapCollector", + "GeckoCollector", + "JsonlCollector", + "StringTable", +) diff --git a/mypy/typeshed/stdlib/profiling/sampling/collector.pyi b/mypy/typeshed/stdlib/profiling/sampling/collector.pyi new file mode 100644 index 0000000000000..f191dbb660391 --- /dev/null +++ b/mypy/typeshed/stdlib/profiling/sampling/collector.pyi @@ -0,0 +1,24 @@ +from _typeshed import StrOrBytesPath +from abc import ABC, abstractmethod +from collections.abc import Sequence +from typing import TypeAlias + +from _remote_debugging import AwaitedInfo, FrameInfo, InterpreterInfo, LocationInfo + +_Location: TypeAlias = int | tuple[int, int, int, int] | LocationInfo | None +_Frame: TypeAlias = FrameInfo | tuple[str, _Location, str, int | None] +_Timestamps: TypeAlias = Sequence[int] | None + +def normalize_location(location: _Location) -> tuple[int, int, int, int]: ... +def extract_lineno(location: _Location) -> int: ... +def filter_internal_frames(frames: Sequence[_Frame]) -> list[_Frame]: ... +def iter_async_frames(awaited_info_list: Sequence[AwaitedInfo]) -> object: ... + +class Collector(ABC): + @abstractmethod + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def collect_failed_sample(self) -> None: ... + @abstractmethod + def export(self, filename: StrOrBytesPath) -> None: ... diff --git a/mypy/typeshed/stdlib/profiling/sampling/gecko_collector.pyi b/mypy/typeshed/stdlib/profiling/sampling/gecko_collector.pyi new file mode 100644 index 0000000000000..6072d4f2359af --- /dev/null +++ b/mypy/typeshed/stdlib/profiling/sampling/gecko_collector.pyi @@ -0,0 +1,13 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Sequence + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import Collector, _Timestamps + +class GeckoCollector(Collector): + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False, opcodes: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... diff --git a/mypy/typeshed/stdlib/profiling/sampling/heatmap_collector.pyi b/mypy/typeshed/stdlib/profiling/sampling/heatmap_collector.pyi new file mode 100644 index 0000000000000..bd523bc382458 --- /dev/null +++ b/mypy/typeshed/stdlib/profiling/sampling/heatmap_collector.pyi @@ -0,0 +1,24 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Sequence + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import Collector, _Frame, _Timestamps + +class HeatmapCollector(Collector): + FILE_INDEX_FORMAT: str + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def export(self, output_path: StrOrBytesPath) -> None: ... + def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... + def set_stats( + self, + sample_interval_usec: int, + duration_sec: float, + sample_rate: float, + error_rate: float | None = None, + missed_samples: float | None = None, + **kwargs: object, + ) -> None: ... diff --git a/mypy/typeshed/stdlib/profiling/sampling/jsonl_collector.pyi b/mypy/typeshed/stdlib/profiling/sampling/jsonl_collector.pyi new file mode 100644 index 0000000000000..3bdc4b81c01dc --- /dev/null +++ b/mypy/typeshed/stdlib/profiling/sampling/jsonl_collector.pyi @@ -0,0 +1,15 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Sequence + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import _Frame, _Timestamps +from .stack_collector import StackTraceCollector + +class JsonlCollector(StackTraceCollector): + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False, mode: int | None = None) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... + def process_frames(self, frames: Sequence[_Frame], _thread_id: int, weight: int = 1) -> None: ... diff --git a/mypy/typeshed/stdlib/profiling/sampling/pstats_collector.pyi b/mypy/typeshed/stdlib/profiling/sampling/pstats_collector.pyi new file mode 100644 index 0000000000000..178d55a7af8e0 --- /dev/null +++ b/mypy/typeshed/stdlib/profiling/sampling/pstats_collector.pyi @@ -0,0 +1,17 @@ +from _typeshed import StrOrBytesPath +from collections.abc import Sequence + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import Collector, _Timestamps + +class PstatsCollector(Collector): + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... + def create_stats(self) -> None: ... + def print_stats( + self, sort: int = -1, limit: int | None = None, show_summary: bool = True, mode: int | None = None + ) -> None: ... diff --git a/mypy/typeshed/stdlib/profiling/sampling/stack_collector.pyi b/mypy/typeshed/stdlib/profiling/sampling/stack_collector.pyi new file mode 100644 index 0000000000000..0788e08295ad6 --- /dev/null +++ b/mypy/typeshed/stdlib/profiling/sampling/stack_collector.pyi @@ -0,0 +1,39 @@ +from _typeshed import StrOrBytesPath +from abc import ABCMeta +from collections.abc import Sequence + +from _remote_debugging import AwaitedInfo, InterpreterInfo + +from .collector import Collector, _Frame, _Timestamps + +class StackTraceCollector(Collector, metaclass=ABCMeta): + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... + +class CollapsedStackCollector(StackTraceCollector): + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... + +class FlamegraphCollector(StackTraceCollector): + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... + def collect( + self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None + ) -> None: ... + def set_stats( + self, + sample_interval_usec: int, + duration_sec: float, + sample_rate: float, + error_rate: float | None = None, + missed_samples: float | None = None, + mode: int | None = None, + ) -> None: ... + def export(self, filename: StrOrBytesPath) -> None: ... + def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... + +class DiffFlamegraphCollector(FlamegraphCollector): + def __init__(self, sample_interval_usec: int, *, baseline_binary_path: StrOrBytesPath, skip_idle: bool = False) -> None: ... diff --git a/mypy/typeshed/stdlib/profiling/sampling/string_table.pyi b/mypy/typeshed/stdlib/profiling/sampling/string_table.pyi new file mode 100644 index 0000000000000..cb71e82ec036d --- /dev/null +++ b/mypy/typeshed/stdlib/profiling/sampling/string_table.pyi @@ -0,0 +1,5 @@ +class StringTable: + def intern(self, string: object) -> int: ... + def get_string(self, index: int) -> str: ... + def get_strings(self) -> list[str]: ... + def __len__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/profiling/tracing.pyi b/mypy/typeshed/stdlib/profiling/tracing.pyi new file mode 100644 index 0000000000000..af4ab508406ac --- /dev/null +++ b/mypy/typeshed/stdlib/profiling/tracing.pyi @@ -0,0 +1,9 @@ +from cProfile import Profile as Profile, run as run, runctx as runctx +from types import CodeType +from typing import TypeAlias + +__all__ = ("run", "runctx", "Profile") + +_Label: TypeAlias = tuple[str, int, str] + +def label(code: str | CodeType) -> _Label: ... # undocumented diff --git a/mypy/typeshed/stdlib/pstats.pyi b/mypy/typeshed/stdlib/pstats.pyi index c1da2aea0fc5a..19eb683df1666 100644 --- a/mypy/typeshed/stdlib/pstats.pyi +++ b/mypy/typeshed/stdlib/pstats.pyi @@ -4,8 +4,8 @@ from collections.abc import Iterable from cProfile import Profile as _cProfile from dataclasses import dataclass from profile import Profile -from typing import IO, Any, Literal, overload -from typing_extensions import Self, TypeAlias +from typing import IO, Any, Literal, TypeAlias, overload +from typing_extensions import Self if sys.version_info >= (3, 11): from enum import StrEnum @@ -72,10 +72,12 @@ class Stats: def add(self, *arg_list: None | str | Profile | _cProfile | Self) -> Self: ... def dump_stats(self, filename: StrOrBytesPath) -> None: ... def get_sort_arg_defs(self) -> _SortArgDict: ... + @overload def sort_stats(self, field: Literal[-1, 0, 1, 2]) -> Self: ... @overload def sort_stats(self, *field: str) -> Self: ... + def reverse_order(self) -> Self: ... def strip_dirs(self) -> Self: ... def calc_callees(self) -> None: ... @@ -86,6 +88,9 @@ class Stats: def print_callees(self, *amount: _Selector) -> Self: ... def print_callers(self, *amount: _Selector) -> Self: ... def print_call_heading(self, name_size: int, column_title: str) -> None: ... + if sys.version_info >= (3, 15): + def print_call_subheading(self, name_size: int) -> None: ... + def print_call_line(self, name_size: int, source: str, call_dict: dict[str, Any], arrow: str = "->") -> None: ... def print_title(self) -> None: ... def print_line(self, func: str) -> None: ... diff --git a/mypy/typeshed/stdlib/pty.pyi b/mypy/typeshed/stdlib/pty.pyi index d1c78f9e3dd67..e74c02ab1e1e6 100644 --- a/mypy/typeshed/stdlib/pty.pyi +++ b/mypy/typeshed/stdlib/pty.pyi @@ -1,7 +1,7 @@ import sys from collections.abc import Callable, Iterable -from typing import Final -from typing_extensions import TypeAlias, deprecated +from typing import Final, TypeAlias +from typing_extensions import deprecated if sys.platform != "win32": __all__ = ["openpty", "fork", "spawn"] @@ -15,14 +15,10 @@ if sys.platform != "win32": def openpty() -> tuple[int, int]: ... if sys.version_info < (3, 14): - if sys.version_info >= (3, 12): - @deprecated("Deprecated since Python 3.12; removed in Python 3.14. Use `openpty()` instead.") - def master_open() -> tuple[int, str]: ... - @deprecated("Deprecated since Python 3.12; removed in Python 3.14. Use `openpty()` instead.") - def slave_open(tty_name: str) -> int: ... - else: - def master_open() -> tuple[int, str]: ... - def slave_open(tty_name: str) -> int: ... + @deprecated("Deprecated since Python 3.12; removed in Python 3.14. Use `openpty()` instead.") + def master_open() -> tuple[int, str]: ... + @deprecated("Deprecated since Python 3.12; removed in Python 3.14. Use `openpty()` instead.") + def slave_open(tty_name: str) -> int: ... def fork() -> tuple[int, int]: ... def spawn(argv: str | Iterable[str], master_read: _Reader = ..., stdin_read: _Reader = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/pwd.pyi b/mypy/typeshed/stdlib/pwd.pyi index a84ba324718af..6a7e24f78125d 100644 --- a/mypy/typeshed/stdlib/pwd.pyi +++ b/mypy/typeshed/stdlib/pwd.pyi @@ -5,8 +5,7 @@ from typing import Any, Final, final if sys.platform != "win32": @final class struct_passwd(structseq[Any], tuple[str, str, int, int, str, str, str]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("pw_name", "pw_passwd", "pw_uid", "pw_gid", "pw_gecos", "pw_dir", "pw_shell") + __match_args__: Final = ("pw_name", "pw_passwd", "pw_uid", "pw_gid", "pw_gecos", "pw_dir", "pw_shell") @property def pw_name(self) -> str: ... diff --git a/mypy/typeshed/stdlib/py_compile.pyi b/mypy/typeshed/stdlib/py_compile.pyi index 334ce79b5dd04..e0ee67c5e93fe 100644 --- a/mypy/typeshed/stdlib/py_compile.pyi +++ b/mypy/typeshed/stdlib/py_compile.pyi @@ -1,5 +1,4 @@ import enum -import sys from typing import AnyStr __all__ = ["compile", "main", "PyCompileError", "PycInvalidationMode"] @@ -26,9 +25,4 @@ def compile( invalidation_mode: PycInvalidationMode | None = None, quiet: int = 0, ) -> AnyStr | None: ... - -if sys.version_info >= (3, 10): - def main() -> None: ... - -else: - def main(args: list[str] | None = None) -> int: ... +def main() -> None: ... diff --git a/mypy/typeshed/stdlib/pyclbr.pyi b/mypy/typeshed/stdlib/pyclbr.pyi index 504a5d5f115a0..541f962d33e1c 100644 --- a/mypy/typeshed/stdlib/pyclbr.pyi +++ b/mypy/typeshed/stdlib/pyclbr.pyi @@ -1,4 +1,3 @@ -import sys from collections.abc import Mapping, Sequence __all__ = ["readmodule", "readmodule_ex", "Class", "Function"] @@ -8,44 +7,33 @@ class _Object: name: str file: int lineno: int - - if sys.version_info >= (3, 10): - end_lineno: int | None - + end_lineno: int | None parent: _Object | None # This is a dict at runtime, but we're typing it as Mapping to # avoid variance issues in the subclasses children: Mapping[str, _Object] - if sys.version_info >= (3, 10): - def __init__( - self, module: str, name: str, file: str, lineno: int, end_lineno: int | None, parent: _Object | None - ) -> None: ... - else: - def __init__(self, module: str, name: str, file: str, lineno: int, parent: _Object | None) -> None: ... + def __init__( + self, module: str, name: str, file: str, lineno: int, end_lineno: int | None, parent: _Object | None + ) -> None: ... class Function(_Object): - if sys.version_info >= (3, 10): - is_async: bool - + is_async: bool parent: Function | Class | None children: dict[str, Class | Function] - if sys.version_info >= (3, 10): - def __init__( - self, - module: str, - name: str, - file: str, - lineno: int, - parent: Function | Class | None = None, - is_async: bool = False, - *, - end_lineno: int | None = None, - ) -> None: ... - else: - def __init__(self, module: str, name: str, file: str, lineno: int, parent: Function | Class | None = None) -> None: ... + def __init__( + self, + module: str, + name: str, + file: str, + lineno: int, + parent: Function | Class | None = None, + is_async: bool = False, + *, + end_lineno: int | None = None, + ) -> None: ... class Class(_Object): super: list[Class | str] | None @@ -53,22 +41,17 @@ class Class(_Object): parent: Class | None children: dict[str, Class | Function] - if sys.version_info >= (3, 10): - def __init__( - self, - module: str, - name: str, - super_: list[Class | str] | None, - file: str, - lineno: int, - parent: Class | None = None, - *, - end_lineno: int | None = None, - ) -> None: ... - else: - def __init__( - self, module: str, name: str, super: list[Class | str] | None, file: str, lineno: int, parent: Class | None = None - ) -> None: ... + def __init__( + self, + module: str, + name: str, + super_: list[Class | str] | None, + file: str, + lineno: int, + parent: Class | None = None, + *, + end_lineno: int | None = None, + ) -> None: ... def readmodule(module: str, path: Sequence[str] | None = None) -> dict[str, Class]: ... def readmodule_ex(module: str, path: Sequence[str] | None = None) -> dict[str, Class | Function | list[str]]: ... diff --git a/mypy/typeshed/stdlib/pydoc.pyi b/mypy/typeshed/stdlib/pydoc.pyi index f8129ac20ade7..2e423dd3d425e 100644 --- a/mypy/typeshed/stdlib/pydoc.pyi +++ b/mypy/typeshed/stdlib/pydoc.pyi @@ -1,12 +1,12 @@ import sys -from _typeshed import OptExcInfo, SupportsWrite, Unused +from _typeshed import OptExcInfo, StrPath, SupportsWrite, Unused from abc import abstractmethod from builtins import list as _list # "list" conflicts with method name from collections.abc import Callable, Container, Mapping, MutableMapping from reprlib import Repr from types import MethodType, ModuleType, TracebackType -from typing import IO, Any, AnyStr, Final, NoReturn, Protocol, TypeVar, overload, type_check_only -from typing_extensions import TypeGuard, deprecated +from typing import IO, Any, AnyStr, Final, NoReturn, Protocol, TypeGuard, TypeVar, overload, type_check_only +from typing_extensions import deprecated __all__ = ["help"] @@ -32,14 +32,8 @@ def stripid(text: str) -> str: ... def allmethods(cl: type) -> MutableMapping[str, MethodType]: ... def visiblename(name: str, all: Container[str] | None = None, obj: object = None) -> bool: ... def classify_class_attrs(object: object) -> list[tuple[str, str, type, str]]: ... - -if sys.version_info >= (3, 13): - @deprecated("Deprecated since Python 3.13.") - def ispackage(path: str) -> bool: ... # undocumented - -else: - def ispackage(path: str) -> bool: ... # undocumented - +@deprecated("Deprecated since Python 3.13.") +def ispackage(path: StrPath) -> bool: ... # undocumented def source_synopsis(file: IO[AnyStr]) -> AnyStr | None: ... def synopsis(filename: str, cache: MutableMapping[str, tuple[int, str]] = {}) -> str | None: ... @@ -62,6 +56,9 @@ def safeimport(path: str, forceload: bool = ..., cache: MutableMapping[str, Modu class Doc: PYTHONDOCS: str + if sys.version_info >= (3, 15): + STDLIB_DIR: str + def document(self, object: object, name: str | None = None, *args: Any) -> str: ... def fail(self, object: object, name: str | None = None, *args: Any) -> NoReturn: ... @abstractmethod @@ -76,7 +73,10 @@ class Doc: def docproperty(self, object: object, name: str | None = None, *args: Any) -> str: ... @abstractmethod def docdata(self, object: object, name: str | None = None, *args: Any) -> str: ... - def getdocloc(self, object: object, basedir: str = ...) -> str | None: ... + if sys.version_info >= (3, 15): + def getdocloc(self, object: object, basedir: str | None = None) -> str | None: ... + else: + def getdocloc(self, object: object, basedir: str = ...) -> str | None: ... class HTMLRepr(Repr): def __init__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/pyexpat/__init__.pyi index bc522d5f3c92d..806db63693b50 100644 --- a/mypy/typeshed/stdlib/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/pyexpat/__init__.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import ReadableBuffer, SupportsRead from collections.abc import Callable from pyexpat import errors as errors, model as model -from typing import Any, Final, final -from typing_extensions import CapsuleType, TypeAlias +from typing import Any, Final, TypeAlias, final +from typing_extensions import CapsuleType from xml.parsers.expat import ExpatError as ExpatError EXPAT_VERSION: Final[str] # undocumented @@ -30,10 +30,12 @@ class XMLParserType: def UseForeignDTD(self, flag: bool = True, /) -> None: ... def GetReparseDeferralEnabled(self) -> bool: ... def SetReparseDeferralEnabled(self, enabled: bool, /) -> None: ... - if sys.version_info >= (3, 10): - # Added in Python 3.10.20, 3.11.15, 3.12.3, 3.13.10, 3.14.1 - def SetAllocTrackerActivationThreshold(self, threshold: int, /) -> None: ... - def SetAllocTrackerMaximumAmplification(self, max_factor: float, /) -> None: ... + # Added in Python 3.10.20, 3.11.15, 3.12.3, 3.13.10, 3.14.1 + def SetAllocTrackerActivationThreshold(self, threshold: int, /) -> None: ... + def SetAllocTrackerMaximumAmplification(self, max_factor: float, /) -> None: ... + if sys.version_info >= (3, 15): + def SetBillionLaughsAttackProtectionActivationThreshold(self, threshold: int, /) -> None: ... + def SetBillionLaughsAttackProtectionMaximumAmplification(self, max_factor: float, /) -> None: ... @property def intern(self) -> dict[str, str]: ... diff --git a/mypy/typeshed/stdlib/random.pyi b/mypy/typeshed/stdlib/random.pyi index 08619bf66351a..80fd2c7628a52 100644 --- a/mypy/typeshed/stdlib/random.pyi +++ b/mypy/typeshed/stdlib/random.pyi @@ -4,7 +4,7 @@ from _typeshed import SupportsLenAndGetItem from collections.abc import Callable, Iterable, MutableSequence, Sequence, Set as AbstractSet from fractions import Fraction from typing import Any, ClassVar, NoReturn, TypeVar, overload -from typing_extensions import Self, deprecated +from typing_extensions import deprecated __all__ = [ "Random", @@ -45,9 +45,6 @@ class Random(_random.Random): # Using other `seed` types is deprecated since 3.9 and removed in 3.11 # Ignore Y041, since random.seed doesn't treat int like a float subtype. Having an explicit # int better documents conventional usage of random.seed. - if sys.version_info < (3, 10): - # this is a workaround for pyright correctly flagging an inconsistent inherited constructor, see #14624 - def __new__(cls, x: int | float | str | bytes | bytearray | None = None) -> Self: ... # noqa: Y041 def seed(self, a: int | float | str | bytes | bytearray | None = None, version: int = 2) -> None: ... # type: ignore[override] # noqa: Y041 def getstate(self) -> tuple[Any, ...]: ... @@ -72,6 +69,7 @@ class Random(_random.Random): @overload @deprecated("The `random` parameter is deprecated since Python 3.9; removed in Python 3.11.") def shuffle(self, x: MutableSequence[Any], random: Callable[[], float] | None = None) -> None: ... + if sys.version_info >= (3, 11): def sample(self, population: Sequence[_T], k: int, *, counts: Iterable[int] | None = None) -> list[_T]: ... else: diff --git a/mypy/typeshed/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi index fb2a06d5e4c81..0183d7a813318 100644 --- a/mypy/typeshed/stdlib/re.pyi +++ b/mypy/typeshed/stdlib/re.pyi @@ -1,12 +1,10 @@ import enum -import sre_compile -import sre_constants import sys from _typeshed import MaybeNone, ReadableBuffer from collections.abc import Callable, Iterator, Mapping from types import GenericAlias -from typing import Any, AnyStr, Final, Generic, Literal, TypeVar, final, overload -from typing_extensions import TypeAlias, deprecated +from typing import Any, AnyStr, Final, Generic, Literal, TypeAlias, TypeVar, final, overload +from typing_extensions import deprecated __all__ = [ "match", @@ -38,6 +36,8 @@ __all__ = [ "Match", "Pattern", ] +if sys.version_info >= (3, 15): + __all__ += ["prefixmatch"] if sys.version_info < (3, 13): __all__ += ["template"] @@ -47,8 +47,6 @@ if sys.version_info >= (3, 11): if sys.version_info >= (3, 13): __all__ += ["PatternError"] - PatternError = sre_constants.error - _T = TypeVar("_T") # The implementation defines this in re._constants (version_info >= 3, 11) or @@ -61,6 +59,9 @@ class error(Exception): colno: int def __init__(self, msg: str, pattern: str | bytes | None = None, pos: int | None = None) -> None: ... +if sys.version_info >= (3, 13): + PatternError = error + @final class Match(Generic[AnyStr]): @property @@ -78,12 +79,14 @@ class Match(Generic[AnyStr]): # this match instance. @property def re(self) -> Pattern[AnyStr]: ... + @overload def expand(self: Match[str], template: str) -> str: ... @overload def expand(self: Match[bytes], template: ReadableBuffer) -> bytes: ... @overload def expand(self, template: AnyStr) -> AnyStr: ... + # group() returns "AnyStr" or "AnyStr | None", depending on the pattern. @overload def group(self, group: Literal[0] = 0, /) -> AnyStr: ... @@ -91,28 +94,33 @@ class Match(Generic[AnyStr]): def group(self, group: str | int, /) -> AnyStr | MaybeNone: ... @overload def group(self, group1: str | int, group2: str | int, /, *groups: str | int) -> tuple[AnyStr | MaybeNone, ...]: ... + # Each item of groups()'s return tuple is either "AnyStr" or # "AnyStr | None", depending on the pattern. @overload def groups(self) -> tuple[AnyStr | MaybeNone, ...]: ... @overload def groups(self, default: _T) -> tuple[AnyStr | _T, ...]: ... + # Each value in groupdict()'s return dict is either "AnyStr" or # "AnyStr | None", depending on the pattern. @overload def groupdict(self) -> dict[str, AnyStr | MaybeNone]: ... @overload def groupdict(self, default: _T) -> dict[str, AnyStr | _T]: ... + def start(self, group: int | str = 0, /) -> int: ... def end(self, group: int | str = 0, /) -> int: ... def span(self, group: int | str = 0, /) -> tuple[int, int]: ... @property def regs(self) -> tuple[tuple[int, int], ...]: ... # undocumented + # __getitem__() returns "AnyStr" or "AnyStr | None", depending on the pattern. @overload def __getitem__(self, key: Literal[0], /) -> AnyStr: ... @overload def __getitem__(self, key: int | str, /) -> AnyStr | MaybeNone: ... + def __copy__(self) -> Match[AnyStr]: ... def __deepcopy__(self, memo: Any, /) -> Match[AnyStr]: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @@ -127,18 +135,24 @@ class Pattern(Generic[AnyStr]): def groups(self) -> int: ... @property def pattern(self) -> AnyStr: ... + @overload def search(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: ... @overload def search(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> Match[bytes] | None: ... @overload def search(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ... + @overload def match(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: ... @overload def match(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> Match[bytes] | None: ... @overload def match(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ... + + if sys.version_info >= (3, 15): + prefixmatch = match + @overload def fullmatch(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: ... @overload @@ -147,12 +161,14 @@ class Pattern(Generic[AnyStr]): ) -> Match[bytes] | None: ... @overload def fullmatch(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ... + @overload def split(self: Pattern[str], string: str, maxsplit: int = 0) -> list[str | MaybeNone]: ... @overload def split(self: Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0) -> list[bytes | MaybeNone]: ... @overload def split(self, string: AnyStr, maxsplit: int = 0) -> list[AnyStr | MaybeNone]: ... + # return type depends on the number of groups in the pattern @overload def findall(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> list[Any]: ... @@ -160,6 +176,7 @@ class Pattern(Generic[AnyStr]): def findall(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> list[Any]: ... @overload def findall(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> list[AnyStr]: ... + @overload def finditer(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Iterator[Match[str]]: ... @overload @@ -168,6 +185,7 @@ class Pattern(Generic[AnyStr]): ) -> Iterator[Match[bytes]]: ... @overload def finditer(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Iterator[Match[AnyStr]]: ... + @overload def sub(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0) -> str: ... @overload @@ -179,6 +197,7 @@ class Pattern(Generic[AnyStr]): ) -> bytes: ... @overload def sub(self, repl: AnyStr | Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = 0) -> AnyStr: ... + @overload def subn(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0) -> tuple[str, int]: ... @overload @@ -190,6 +209,7 @@ class Pattern(Generic[AnyStr]): ) -> tuple[bytes, int]: ... @overload def subn(self, repl: AnyStr | Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = 0) -> tuple[AnyStr, int]: ... + def __copy__(self) -> Pattern[AnyStr]: ... def __deepcopy__(self, memo: Any, /) -> Pattern[AnyStr]: ... def __eq__(self, value: object, /) -> bool: ... @@ -199,23 +219,23 @@ class Pattern(Generic[AnyStr]): # ----- re variables and constants ----- class RegexFlag(enum.IntFlag): - A = sre_compile.SRE_FLAG_ASCII + A = 256 ASCII = A - DEBUG = sre_compile.SRE_FLAG_DEBUG - I = sre_compile.SRE_FLAG_IGNORECASE + DEBUG = 128 + I = 2 IGNORECASE = I - L = sre_compile.SRE_FLAG_LOCALE + L = 4 LOCALE = L - M = sre_compile.SRE_FLAG_MULTILINE + M = 8 MULTILINE = M - S = sre_compile.SRE_FLAG_DOTALL + S = 16 DOTALL = S - X = sre_compile.SRE_FLAG_VERBOSE + X = 64 VERBOSE = X - U = sre_compile.SRE_FLAG_UNICODE + U = 32 UNICODE = U if sys.version_info < (3, 13): - T = sre_compile.SRE_FLAG_TEMPLATE + T = 1 TEMPLATE = T if sys.version_info >= (3, 11): NOFLAG = 0 @@ -253,32 +273,45 @@ _FlagsType: TypeAlias = int | RegexFlag def compile(pattern: AnyStr, flags: _FlagsType = 0) -> Pattern[AnyStr]: ... @overload def compile(pattern: Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: ... + @overload def search(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ... @overload def search(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... + @overload def match(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ... @overload def match(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... + +if sys.version_info >= (3, 15): + @overload + def prefixmatch(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ... + @overload + def prefixmatch(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... + @overload def fullmatch(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ... @overload def fullmatch(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... + @overload def split(pattern: str | Pattern[str], string: str, maxsplit: int = 0, flags: _FlagsType = 0) -> list[str | MaybeNone]: ... @overload def split( pattern: bytes | Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0, flags: _FlagsType = 0 ) -> list[bytes | MaybeNone]: ... + @overload def findall(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> list[Any]: ... @overload def findall(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> list[Any]: ... + @overload def finditer(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Iterator[Match[str]]: ... @overload def finditer(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Iterator[Match[bytes]]: ... + @overload def sub( pattern: str | Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0, flags: _FlagsType = 0 @@ -291,6 +324,7 @@ def sub( count: int = 0, flags: _FlagsType = 0, ) -> bytes: ... + @overload def subn( pattern: str | Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0, flags: _FlagsType = 0 @@ -303,12 +337,10 @@ def subn( count: int = 0, flags: _FlagsType = 0, ) -> tuple[bytes, int]: ... + def escape(pattern: AnyStr) -> AnyStr: ... def purge() -> None: ... if sys.version_info < (3, 13): - if sys.version_info >= (3, 11): - @deprecated("Deprecated since Python 3.11; removed in Python 3.13. Use `re.compile()` instead.") - def template(pattern: AnyStr | Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: ... # undocumented - else: - def template(pattern: AnyStr | Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: ... # undocumented + @deprecated("Deprecated since Python 3.11; removed in Python 3.13. Use `re.compile()` instead.") + def template(pattern: AnyStr | Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: ... # undocumented diff --git a/mypy/typeshed/stdlib/readline.pyi b/mypy/typeshed/stdlib/readline.pyi index 7325c267b32c2..aff1e504a174a 100644 --- a/mypy/typeshed/stdlib/readline.pyi +++ b/mypy/typeshed/stdlib/readline.pyi @@ -1,8 +1,7 @@ import sys from _typeshed import StrOrBytesPath from collections.abc import Callable, Sequence -from typing import Literal -from typing_extensions import TypeAlias +from typing import Literal, TypeAlias if sys.platform != "win32": _Completer: TypeAlias = Callable[[str, int], str | None] diff --git a/mypy/typeshed/stdlib/reprlib.pyi b/mypy/typeshed/stdlib/reprlib.pyi index 68ada65693485..d990c2708ae95 100644 --- a/mypy/typeshed/stdlib/reprlib.pyi +++ b/mypy/typeshed/stdlib/reprlib.pyi @@ -2,8 +2,7 @@ import sys from array import array from collections import deque from collections.abc import Callable -from typing import Any -from typing_extensions import TypeAlias +from typing import Any, TypeAlias __all__ = ["Repr", "repr", "recursive_repr"] diff --git a/mypy/typeshed/stdlib/resource.pyi b/mypy/typeshed/stdlib/resource.pyi index f99cd5b088056..7e72b28cc6dd1 100644 --- a/mypy/typeshed/stdlib/resource.pyi +++ b/mypy/typeshed/stdlib/resource.pyi @@ -15,6 +15,9 @@ if sys.platform != "win32": RLIMIT_RSS: Final[int] RLIMIT_STACK: Final[int] RLIM_INFINITY: Final[int] + if sys.version_info >= (3, 15): + RLIM_SAVED_CUR: Final[int] + RLIM_SAVED_MAX: Final[int] RUSAGE_CHILDREN: Final[int] RUSAGE_SELF: Final[int] if sys.platform == "linux": @@ -25,30 +28,34 @@ if sys.platform != "win32": RLIMIT_RTTIME: Final[int] RLIMIT_SIGPENDING: Final[int] RUSAGE_THREAD: Final[int] + if sys.version_info >= (3, 15) and sys.platform != "linux" and sys.platform != "darwin": + RLIMIT_NTHR: Final[int] + RLIMIT_PIPEBUF: Final[int] + RLIMIT_THREADS: Final[int] + RLIMIT_UMTXP: Final[int] @final class struct_rusage( structseq[float], tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] ): - if sys.version_info >= (3, 10): - __match_args__: Final = ( - "ru_utime", - "ru_stime", - "ru_maxrss", - "ru_ixrss", - "ru_idrss", - "ru_isrss", - "ru_minflt", - "ru_majflt", - "ru_nswap", - "ru_inblock", - "ru_oublock", - "ru_msgsnd", - "ru_msgrcv", - "ru_nsignals", - "ru_nvcsw", - "ru_nivcsw", - ) + __match_args__: Final = ( + "ru_utime", + "ru_stime", + "ru_maxrss", + "ru_ixrss", + "ru_idrss", + "ru_isrss", + "ru_minflt", + "ru_majflt", + "ru_nswap", + "ru_inblock", + "ru_oublock", + "ru_msgsnd", + "ru_msgrcv", + "ru_nsignals", + "ru_nvcsw", + "ru_nivcsw", + ) @property def ru_utime(self) -> float: ... diff --git a/mypy/typeshed/stdlib/sched.pyi b/mypy/typeshed/stdlib/sched.pyi index 436d9984ee4da..54eb6ed0cd537 100644 --- a/mypy/typeshed/stdlib/sched.pyi +++ b/mypy/typeshed/stdlib/sched.pyi @@ -1,33 +1,18 @@ -import sys import time from collections.abc import Callable -from typing import Any, ClassVar, NamedTuple, type_check_only -from typing_extensions import TypeAlias +from typing import Any, NamedTuple, TypeAlias __all__ = ["scheduler"] _ActionCallback: TypeAlias = Callable[..., Any] -if sys.version_info >= (3, 10): - class Event(NamedTuple): - time: float - priority: Any - sequence: int - action: _ActionCallback - argument: tuple[Any, ...] - kwargs: dict[str, Any] - -else: - @type_check_only - class _EventBase(NamedTuple): - time: float - priority: Any - action: _ActionCallback - argument: tuple[Any, ...] - kwargs: dict[str, Any] - - class Event(_EventBase): - __hash__: ClassVar[None] # type: ignore[assignment] +class Event(NamedTuple): + time: float + priority: Any + sequence: int + action: _ActionCallback + argument: tuple[Any, ...] + kwargs: dict[str, Any] class scheduler: timefunc: Callable[[], float] diff --git a/mypy/typeshed/stdlib/select.pyi b/mypy/typeshed/stdlib/select.pyi index d2b1d6d676e57..ad93cb0b7055b 100644 --- a/mypy/typeshed/stdlib/select.pyi +++ b/mypy/typeshed/stdlib/select.pyi @@ -24,6 +24,7 @@ if sys.platform != "win32": # This is actually a function that returns an instance of a class. # The class is not accessible directly, and also calls itself select.poll. + @final class poll: # default value is select.POLLIN | select.POLLPRI | select.POLLOUT def register(self, fd: FileDescriptorLike, eventmask: int = 7, /) -> None: ... @@ -31,9 +32,9 @@ if sys.platform != "win32": def unregister(self, fd: FileDescriptorLike, /) -> None: ... def poll(self, timeout: float | None = None, /) -> list[tuple[int, int]]: ... -_R = TypeVar("_R", default=Never) -_W = TypeVar("_W", default=Never) -_X = TypeVar("_X", default=Never) +_R = TypeVar("_R", default=Never, bound=FileDescriptorLike) +_W = TypeVar("_W", default=Never, bound=FileDescriptorLike) +_X = TypeVar("_X", default=Never, bound=FileDescriptorLike) def select( rlist: Iterable[_R], wlist: Iterable[_W], xlist: Iterable[_X], timeout: float | None = None, / @@ -120,6 +121,7 @@ if sys.platform == "linux": "Use `os.set_inheritable()` to make the file descriptor inheritable." ) def __new__(self, sizehint: int = -1, flags: int = 0) -> Self: ... + def __enter__(self) -> Self: ... def __exit__( self, @@ -158,6 +160,7 @@ if sys.platform == "linux": if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win32": # Solaris only + @final class devpoll: def close(self) -> None: ... closed: bool diff --git a/mypy/typeshed/stdlib/selectors.pyi b/mypy/typeshed/stdlib/selectors.pyi index bcca4e341b9a1..4a3478a67552a 100644 --- a/mypy/typeshed/stdlib/selectors.pyi +++ b/mypy/typeshed/stdlib/selectors.pyi @@ -3,9 +3,7 @@ from _typeshed import FileDescriptor, FileDescriptorLike, Unused from abc import ABCMeta, abstractmethod from collections.abc import Mapping from typing import Any, Final, NamedTuple -from typing_extensions import Self, TypeAlias - -_EventMask: TypeAlias = int +from typing_extensions import Self EVENT_READ: Final = 1 EVENT_WRITE: Final = 2 @@ -13,17 +11,17 @@ EVENT_WRITE: Final = 2 class SelectorKey(NamedTuple): fileobj: FileDescriptorLike fd: FileDescriptor - events: _EventMask + events: int data: Any class BaseSelector(metaclass=ABCMeta): @abstractmethod - def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = None) -> SelectorKey: ... + def register(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... @abstractmethod def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... - def modify(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = None) -> SelectorKey: ... + def modify(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... @abstractmethod - def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: ... + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... def close(self) -> None: ... def get_key(self, fileobj: FileDescriptorLike) -> SelectorKey: ... @abstractmethod @@ -32,16 +30,16 @@ class BaseSelector(metaclass=ABCMeta): def __exit__(self, *args: Unused) -> None: ... class _BaseSelectorImpl(BaseSelector, metaclass=ABCMeta): - def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = None) -> SelectorKey: ... + def register(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ... - def modify(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = None) -> SelectorKey: ... + def modify(self, fileobj: FileDescriptorLike, events: int, data: Any = None) -> SelectorKey: ... def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ... class SelectSelector(_BaseSelectorImpl): - def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: ... + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... class _PollLikeSelector(_BaseSelectorImpl): - def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: ... + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... if sys.platform != "win32": class PollSelector(_PollLikeSelector): ... @@ -58,12 +56,12 @@ if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win if sys.platform != "win32" and sys.platform != "linux": class KqueueSelector(_BaseSelectorImpl): def fileno(self) -> int: ... - def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: ... + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... # Not a real class at runtime, it is just a conditional alias to other real selectors. # The runtime logic is more fine-grained than a `sys.platform` check; # not really expressible in the stubs class DefaultSelector(_BaseSelectorImpl): - def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: ... + def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, int]]: ... if sys.platform != "win32": def fileno(self) -> int: ... diff --git a/mypy/typeshed/stdlib/shelve.pyi b/mypy/typeshed/stdlib/shelve.pyi index 654c2ea097f78..c599b0af61384 100644 --- a/mypy/typeshed/stdlib/shelve.pyi +++ b/mypy/typeshed/stdlib/shelve.pyi @@ -1,28 +1,53 @@ import sys from _typeshed import StrOrBytesPath -from collections.abc import Iterator, MutableMapping +from collections.abc import Callable, Iterator, MutableMapping from dbm import _TFlags from types import TracebackType from typing import Any, TypeVar, overload from typing_extensions import Self __all__ = ["Shelf", "BsdDbShelf", "DbfilenameShelf", "open"] +if sys.version_info >= (3, 15): + __all__ += ["ShelveError"] _T = TypeVar("_T") _VT = TypeVar("_VT") +if sys.version_info >= (3, 15): + class ShelveError(Exception): ... + class Shelf(MutableMapping[str, _VT]): - def __init__( - self, dict: MutableMapping[bytes, bytes], protocol: int | None = None, writeback: bool = False, keyencoding: str = "utf-8" - ) -> None: ... + if sys.version_info >= (3, 15): + def __init__( + self, + dict: MutableMapping[bytes, bytes], + protocol: int | None = None, + writeback: bool = False, + keyencoding: str = "utf-8", + *, + serializer: Callable[[Any], bytes] | None = None, + deserializer: Callable[[bytes], Any] | None = None, + ) -> None: ... + + else: + def __init__( + self, + dict: MutableMapping[bytes, bytes], + protocol: int | None = None, + writeback: bool = False, + keyencoding: str = "utf-8", + ) -> None: ... + def __iter__(self) -> Iterator[str]: ... def __len__(self) -> int: ... + @overload # type: ignore[override] def get(self, key: str, default: None = None) -> _VT | None: ... @overload def get(self, key: str, default: _VT) -> _VT: ... @overload def get(self, key: str, default: _T) -> _VT | _T: ... + def __getitem__(self, key: str) -> _VT: ... def __setitem__(self, key: str, value: _VT) -> None: ... def __delitem__(self, key: str) -> None: ... @@ -34,6 +59,8 @@ class Shelf(MutableMapping[str, _VT]): def __del__(self) -> None: ... def close(self) -> None: ... def sync(self) -> None: ... + if sys.version_info >= (3, 15): + def reorganize(self) -> None: ... class BsdDbShelf(Shelf[_VT]): def set_location(self, key: str) -> tuple[str, _VT]: ... @@ -43,14 +70,38 @@ class BsdDbShelf(Shelf[_VT]): def last(self) -> tuple[str, _VT]: ... class DbfilenameShelf(Shelf[_VT]): - if sys.version_info >= (3, 11): + if sys.version_info >= (3, 15): + def __init__( + self, + filename: StrOrBytesPath, + flag: _TFlags = "c", + protocol: int | None = None, + writeback: bool = False, + *, + serializer: Callable[[Any], bytes] | None = None, + deserializer: Callable[[bytes], Any] | None = None, + ) -> None: ... + + elif sys.version_info >= (3, 11): def __init__( self, filename: StrOrBytesPath, flag: _TFlags = "c", protocol: int | None = None, writeback: bool = False ) -> None: ... + else: def __init__(self, filename: str, flag: _TFlags = "c", protocol: int | None = None, writeback: bool = False) -> None: ... -if sys.version_info >= (3, 11): +if sys.version_info >= (3, 15): + def open( + filename: StrOrBytesPath, + flag: _TFlags = "c", + protocol: int | None = None, + writeback: bool = False, + *, + serializer: Callable[[Any], bytes] | None = None, + deserializer: Callable[[bytes], Any] | None = None, + ) -> Shelf[Any]: ... + +elif sys.version_info >= (3, 11): def open( filename: StrOrBytesPath, flag: _TFlags = "c", protocol: int | None = None, writeback: bool = False ) -> Shelf[Any]: ... diff --git a/mypy/typeshed/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi index cc26cfc556a00..badb0bae220dc 100644 --- a/mypy/typeshed/stdlib/shutil.pyi +++ b/mypy/typeshed/stdlib/shutil.pyi @@ -3,8 +3,8 @@ import sys from _typeshed import BytesPath, ExcInfo, FileDescriptorOrPath, MaybeNone, StrOrBytesPath, StrPath, SupportsRead, SupportsWrite from collections.abc import Callable, Iterable, Sequence from tarfile import _TarfileFilter -from typing import Any, AnyStr, NamedTuple, NoReturn, Protocol, TypeVar, overload, type_check_only -from typing_extensions import TypeAlias, deprecated +from typing import Any, AnyStr, NamedTuple, NoReturn, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import deprecated __all__ = [ "copyfileobj", @@ -57,14 +57,17 @@ def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: def copyfile(src: StrOrBytesPath, dst: _StrOrBytesPathT, *, follow_symlinks: bool = True) -> _StrOrBytesPathT: ... def copymode(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: ... def copystat(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: ... + @overload def copy(src: StrPath, dst: _StrPathT, *, follow_symlinks: bool = True) -> _StrPathT | str: ... @overload def copy(src: BytesPath, dst: _BytesPathT, *, follow_symlinks: bool = True) -> _BytesPathT | bytes: ... + @overload def copy2(src: StrPath, dst: _StrPathT, *, follow_symlinks: bool = True) -> _StrPathT | str: ... @overload def copy2(src: BytesPath, dst: _BytesPathT, *, follow_symlinks: bool = True) -> _BytesPathT | bytes: ... + def ignore_patterns(*patterns: StrPath) -> Callable[[Any, list[str]], set[str]]: ... def copytree( src: StrPath, @@ -175,7 +178,6 @@ if sys.version_info >= (3, 13): def chown( path: FileDescriptorOrPath, user: str | int, group: str | int, *, dir_fd: int | None = None, follow_symlinks: bool = True ) -> None: ... - else: @overload def chown(path: FileDescriptorOrPath, user: str | int, group: None = None) -> None: ... @@ -195,6 +197,7 @@ if sys.platform == "win32" and sys.version_info < (3, 12): def which(cmd: StrPath, mode: int = 1, path: StrPath | None = None) -> str | None: ... @overload def which(cmd: bytes, mode: int = 1, path: StrPath | None = None) -> bytes | None: ... + def make_archive( base_name: str, format: str, @@ -207,6 +210,7 @@ def make_archive( logger: Any | None = None, ) -> str: ... def get_archive_formats() -> list[tuple[str, str]]: ... + @overload def register_archive_format( name: str, function: Callable[..., object], extra_args: Sequence[tuple[str, Any] | list[Any]], description: str = "" @@ -215,10 +219,12 @@ def register_archive_format( def register_archive_format( name: str, function: Callable[[str, str], object], extra_args: None = None, description: str = "" ) -> None: ... + def unregister_archive_format(name: str) -> None: ... def unpack_archive( filename: StrPath, extract_dir: StrPath | None = None, format: str | None = None, *, filter: _TarfileFilter | None = None ) -> None: ... + @overload def register_unpack_format( name: str, @@ -231,6 +237,7 @@ def register_unpack_format( def register_unpack_format( name: str, extensions: list[str], function: Callable[[str, str], object], extra_args: None = None, description: str = "" ) -> None: ... + def unregister_unpack_format(name: str) -> None: ... def get_unpack_formats() -> list[tuple[str, list[str], str]]: ... def get_terminal_size(fallback: tuple[int, int] = (80, 24)) -> os.terminal_size: ... diff --git a/mypy/typeshed/stdlib/signal.pyi b/mypy/typeshed/stdlib/signal.pyi index 3bf1d31293787..a6a8853671e23 100644 --- a/mypy/typeshed/stdlib/signal.pyi +++ b/mypy/typeshed/stdlib/signal.pyi @@ -3,8 +3,8 @@ from _typeshed import structseq from collections.abc import Callable, Iterable from enum import IntEnum from types import FrameType -from typing import Any, Final, final -from typing_extensions import Never, TypeAlias +from typing import Any, Final, TypeAlias, final +from typing_extensions import Never NSIG: int @@ -69,14 +69,8 @@ _SIGNUM: TypeAlias = int | Signals _HANDLER: TypeAlias = Callable[[int, FrameType | None], Any] | int | Handlers | None def default_int_handler(signalnum: int, frame: FrameType | None, /) -> Never: ... - -if sys.version_info >= (3, 10): # arguments changed in 3.10.2 - def getsignal(signalnum: _SIGNUM) -> _HANDLER: ... - def signal(signalnum: _SIGNUM, handler: _HANDLER) -> _HANDLER: ... - -else: - def getsignal(signalnum: _SIGNUM, /) -> _HANDLER: ... - def signal(signalnum: _SIGNUM, handler: _HANDLER, /) -> _HANDLER: ... +def getsignal(signalnum: _SIGNUM) -> _HANDLER: ... +def signal(signalnum: _SIGNUM, handler: _HANDLER) -> _HANDLER: ... SIGABRT: Final = Signals.SIGABRT SIGFPE: Final = Signals.SIGFPE @@ -135,18 +129,11 @@ else: def getitimer(which: int, /) -> tuple[float, float]: ... def pause() -> None: ... def pthread_kill(thread_id: int, signalnum: int, /) -> None: ... - if sys.version_info >= (3, 10): # arguments changed in 3.10.2 - def pthread_sigmask(how: int, mask: Iterable[int]) -> set[_SIGNUM]: ... - else: - def pthread_sigmask(how: int, mask: Iterable[int], /) -> set[_SIGNUM]: ... - + def pthread_sigmask(how: int, mask: Iterable[int]) -> set[_SIGNUM]: ... def setitimer(which: int, seconds: float, interval: float = 0.0, /) -> tuple[float, float]: ... def siginterrupt(signalnum: int, flag: bool, /) -> None: ... def sigpending() -> Any: ... - if sys.version_info >= (3, 10): # argument changed in 3.10.2 - def sigwait(sigset: Iterable[int]) -> _SIGNUM: ... - else: - def sigwait(sigset: Iterable[int], /) -> _SIGNUM: ... + def sigwait(sigset: Iterable[int]) -> _SIGNUM: ... if sys.platform != "darwin": SIGCLD: Final = Signals.SIGCHLD # alias SIGPOLL: Final = Signals.SIGIO # alias @@ -158,8 +145,7 @@ else: @final class struct_siginfo(structseq[int], tuple[int, int, int, int, int, int, int]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("si_signo", "si_code", "si_errno", "si_pid", "si_uid", "si_status", "si_band") + __match_args__: Final = ("si_signo", "si_code", "si_errno", "si_pid", "si_uid", "si_status", "si_band") @property def si_signo(self) -> int: ... diff --git a/mypy/typeshed/stdlib/site.pyi b/mypy/typeshed/stdlib/site.pyi index 6e39677aaea0e..da046ee510ad9 100644 --- a/mypy/typeshed/stdlib/site.pyi +++ b/mypy/typeshed/stdlib/site.pyi @@ -10,9 +10,24 @@ USER_BASE: str | None def main() -> None: ... def abs_paths() -> None: ... # undocumented def addpackage(sitedir: StrPath, name: StrPath, known_paths: set[str] | None) -> set[str] | None: ... # undocumented -def addsitedir(sitedir: str, known_paths: set[str] | None = None) -> None: ... -def addsitepackages(known_paths: set[str] | None, prefixes: Iterable[str] | None = None) -> set[str] | None: ... # undocumented -def addusersitepackages(known_paths: set[str] | None) -> set[str] | None: ... # undocumented + +if sys.version_info >= (3, 15): + def process_startup_files() -> None: ... # undocumented + def addsitedir(sitedir: str, known_paths: set[str] | None = None, *, defer_processing_start_files: bool = False) -> None: ... + def addsitepackages( + known_paths: set[str] | None, prefixes: Iterable[str] | None = None, *, defer_processing_start_files: bool = False + ) -> set[str] | None: ... # undocumented + def addusersitepackages( + known_paths: set[str] | None, *, defer_processing_start_files: bool = False + ) -> set[str] | None: ... # undocumented + +else: + def addsitedir(sitedir: str, known_paths: set[str] | None = None) -> None: ... + def addsitepackages( + known_paths: set[str] | None, prefixes: Iterable[str] | None = None + ) -> set[str] | None: ... # undocumented + def addusersitepackages(known_paths: set[str] | None) -> set[str] | None: ... # undocumented + def check_enableusersite() -> bool | None: ... # undocumented if sys.version_info >= (3, 13): diff --git a/mypy/typeshed/stdlib/smtpd.pyi b/mypy/typeshed/stdlib/smtpd.pyi index dee7e949f42fa..cc9ac391a441f 100644 --- a/mypy/typeshed/stdlib/smtpd.pyi +++ b/mypy/typeshed/stdlib/smtpd.pyi @@ -3,8 +3,8 @@ import asyncore import socket import sys from collections import defaultdict -from typing import Any -from typing_extensions import TypeAlias, deprecated +from typing import Any, TypeAlias +from typing_extensions import deprecated if sys.version_info >= (3, 11): __all__ = ["SMTPChannel", "SMTPServer", "DebuggingServer", "PureProxy"] diff --git a/mypy/typeshed/stdlib/smtplib.pyi b/mypy/typeshed/stdlib/smtplib.pyi index 74b5ea2cb6fce..1aaa5b49664b0 100644 --- a/mypy/typeshed/stdlib/smtplib.pyi +++ b/mypy/typeshed/stdlib/smtplib.pyi @@ -7,8 +7,8 @@ from re import Pattern from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, Final, Protocol, overload, type_check_only -from typing_extensions import Self, TypeAlias, deprecated +from typing import Any, Final, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated __all__ = [ "SMTPException", @@ -65,6 +65,7 @@ class SMTPAuthenticationError(SMTPResponseException): ... def quoteaddr(addrstring: str) -> str: ... def quotedata(data: str) -> str: ... + @type_check_only class _AuthObject(Protocol): @overload @@ -121,10 +122,12 @@ class SMTP: user: str password: str def auth(self, mechanism: str, authobject: _AuthObject, *, initial_response_ok: bool = True) -> _Reply: ... + @overload def auth_cram_md5(self, challenge: None = None) -> None: ... @overload def auth_cram_md5(self, challenge: ReadableBuffer) -> str: ... + def auth_plain(self, challenge: ReadableBuffer | None = None) -> str: ... def auth_login(self, challenge: ReadableBuffer | None = None) -> str: ... def login(self, user: str, password: str, *, initial_response_ok: bool = True) -> _Reply: ... @@ -203,6 +206,7 @@ class SMTP_SSL(SMTP): source_address: _SourceAddress | None = None, context: None = None, ) -> None: ... + keyfile: StrOrBytesPath | None certfile: StrOrBytesPath | None diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index a55273a8772c9..76ba0a85c128c 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -28,6 +28,7 @@ from _socket import ( IP_MULTICAST_LOOP as IP_MULTICAST_LOOP, IP_MULTICAST_TTL as IP_MULTICAST_TTL, IP_OPTIONS as IP_OPTIONS, + IP_RECVTOS as IP_RECVTOS, IP_TOS as IP_TOS, IP_TTL as IP_TTL, IPPORT_RESERVED as IPPORT_RESERVED, @@ -223,6 +224,7 @@ __all__ = [ "IP_MULTICAST_LOOP", "IP_MULTICAST_TTL", "IP_OPTIONS", + "IP_RECVTOS", "IP_TOS", "IP_TTL", "MSG_CTRUNC", @@ -357,11 +359,6 @@ if sys.platform != "darwin": __all__ += ["TCP_KEEPIDLE", "AF_IRDA", "MSG_ERRQUEUE"] -if sys.version_info >= (3, 10): - from _socket import IP_RECVTOS as IP_RECVTOS - - __all__ += ["IP_RECVTOS"] - if sys.platform != "win32" and sys.platform != "darwin": from _socket import ( IP_TRANSPARENT as IP_TRANSPARENT, @@ -525,7 +522,7 @@ if sys.platform != "darwin": if sys.platform != "darwin" and sys.platform != "linux": __all__ += ["BDADDR_ANY", "BDADDR_LOCAL", "BTPROTO_RFCOMM"] -if sys.platform == "darwin" and sys.version_info >= (3, 10): +if sys.platform == "darwin": from _socket import TCP_KEEPALIVE as TCP_KEEPALIVE __all__ += ["TCP_KEEPALIVE"] @@ -779,6 +776,68 @@ if sys.platform == "linux": from _socket import CAN_RAW_ERR_FILTER as CAN_RAW_ERR_FILTER __all__ += ["CAN_RAW_ERR_FILTER"] + if sys.version_info >= (3, 15): + from _socket import ( + CAN_ISOTP_CHK_PAD_DATA as CAN_ISOTP_CHK_PAD_DATA, + CAN_ISOTP_CHK_PAD_LEN as CAN_ISOTP_CHK_PAD_LEN, + CAN_ISOTP_DEFAULT_EXT_ADDRESS as CAN_ISOTP_DEFAULT_EXT_ADDRESS, + CAN_ISOTP_DEFAULT_FLAGS as CAN_ISOTP_DEFAULT_FLAGS, + CAN_ISOTP_DEFAULT_FRAME_TXTIME as CAN_ISOTP_DEFAULT_FRAME_TXTIME, + CAN_ISOTP_DEFAULT_LL_MTU as CAN_ISOTP_DEFAULT_LL_MTU, + CAN_ISOTP_DEFAULT_LL_TX_DL as CAN_ISOTP_DEFAULT_LL_TX_DL, + CAN_ISOTP_DEFAULT_LL_TX_FLAGS as CAN_ISOTP_DEFAULT_LL_TX_FLAGS, + CAN_ISOTP_DEFAULT_PAD_CONTENT as CAN_ISOTP_DEFAULT_PAD_CONTENT, + CAN_ISOTP_DEFAULT_RECV_BS as CAN_ISOTP_DEFAULT_RECV_BS, + CAN_ISOTP_DEFAULT_RECV_STMIN as CAN_ISOTP_DEFAULT_RECV_STMIN, + CAN_ISOTP_DEFAULT_RECV_WFTMAX as CAN_ISOTP_DEFAULT_RECV_WFTMAX, + CAN_ISOTP_EXTEND_ADDR as CAN_ISOTP_EXTEND_ADDR, + CAN_ISOTP_FORCE_RXSTMIN as CAN_ISOTP_FORCE_RXSTMIN, + CAN_ISOTP_FORCE_TXSTMIN as CAN_ISOTP_FORCE_TXSTMIN, + CAN_ISOTP_HALF_DUPLEX as CAN_ISOTP_HALF_DUPLEX, + CAN_ISOTP_LISTEN_MODE as CAN_ISOTP_LISTEN_MODE, + CAN_ISOTP_LL_OPTS as CAN_ISOTP_LL_OPTS, + CAN_ISOTP_OPTS as CAN_ISOTP_OPTS, + CAN_ISOTP_RECV_FC as CAN_ISOTP_RECV_FC, + CAN_ISOTP_RX_EXT_ADDR as CAN_ISOTP_RX_EXT_ADDR, + CAN_ISOTP_RX_PADDING as CAN_ISOTP_RX_PADDING, + CAN_ISOTP_RX_STMIN as CAN_ISOTP_RX_STMIN, + CAN_ISOTP_SF_BROADCAST as CAN_ISOTP_SF_BROADCAST, + CAN_ISOTP_TX_PADDING as CAN_ISOTP_TX_PADDING, + CAN_ISOTP_TX_STMIN as CAN_ISOTP_TX_STMIN, + CAN_ISOTP_WAIT_TX_DONE as CAN_ISOTP_WAIT_TX_DONE, + SOL_CAN_ISOTP as SOL_CAN_ISOTP, + ) + + __all__ += [ + "CAN_ISOTP_CHK_PAD_DATA", + "CAN_ISOTP_CHK_PAD_LEN", + "CAN_ISOTP_DEFAULT_EXT_ADDRESS", + "CAN_ISOTP_DEFAULT_FLAGS", + "CAN_ISOTP_DEFAULT_FRAME_TXTIME", + "CAN_ISOTP_DEFAULT_LL_MTU", + "CAN_ISOTP_DEFAULT_LL_TX_DL", + "CAN_ISOTP_DEFAULT_LL_TX_FLAGS", + "CAN_ISOTP_DEFAULT_PAD_CONTENT", + "CAN_ISOTP_DEFAULT_RECV_BS", + "CAN_ISOTP_DEFAULT_RECV_STMIN", + "CAN_ISOTP_DEFAULT_RECV_WFTMAX", + "CAN_ISOTP_EXTEND_ADDR", + "CAN_ISOTP_FORCE_RXSTMIN", + "CAN_ISOTP_FORCE_TXSTMIN", + "CAN_ISOTP_HALF_DUPLEX", + "CAN_ISOTP_LL_OPTS", + "CAN_ISOTP_LISTEN_MODE", + "CAN_ISOTP_OPTS", + "CAN_ISOTP_RECV_FC", + "CAN_ISOTP_RX_EXT_ADDR", + "CAN_ISOTP_RX_PADDING", + "CAN_ISOTP_RX_STMIN", + "CAN_ISOTP_SF_BROADCAST", + "CAN_ISOTP_TX_PADDING", + "CAN_ISOTP_TX_STMIN", + "CAN_ISOTP_WAIT_TX_DONE", + "SOL_CAN_ISOTP", + ] if sys.platform == "linux": from _socket import ( @@ -842,7 +901,7 @@ if sys.platform == "linux": "UDPLITE_RECV_CSCOV", "UDPLITE_SEND_CSCOV", ] -if sys.platform == "linux" and sys.version_info >= (3, 10): +if sys.platform == "linux": from _socket import IPPROTO_MPTCP as IPPROTO_MPTCP __all__ += ["IPPROTO_MPTCP"] @@ -1044,6 +1103,12 @@ if sys.platform != "linux": __all__ += ["IPPROTO_GGP", "IPPROTO_IPV4", "IPPROTO_MAX", "IPPROTO_ND", "IP_RECVDSTADDR", "SO_USELOOPBACK"] +if sys.version_info >= (3, 15): + if sys.platform == "win32" or sys.platform == "linux": + from _socket import IPV6_HDRINCL as IPV6_HDRINCL + + __all__ += ["IPV6_HDRINCL"] + if sys.version_info >= (3, 14): from _socket import IP_RECVTTL as IP_RECVTTL @@ -1087,10 +1152,7 @@ error = OSError class herror(error): ... class gaierror(error): ... -if sys.version_info >= (3, 10): - timeout = TimeoutError -else: - class timeout(error): ... +timeout = TimeoutError class AddressFamily(IntEnum): AF_INET = 2 @@ -1325,6 +1387,7 @@ class socket(_socket.socket): def __exit__(self, *args: Unused) -> None: ... def dup(self) -> Self: ... def accept(self) -> tuple[socket, _RetAddress]: ... + # Note that the makefile's documented windows-specific behavior is not represented # mode strings with duplicates are intentionally excluded @overload @@ -1387,6 +1450,7 @@ class socket(_socket.socket): errors: str | None = None, newline: str | None = None, ) -> TextIOWrapper: ... + def sendfile(self, file: _SendableFile, offset: int = 0, count: int | None = None) -> int: ... @property def family(self) -> AddressFamily: ... diff --git a/mypy/typeshed/stdlib/socketserver.pyi b/mypy/typeshed/stdlib/socketserver.pyi index f321d14a792b2..05e0025d6a15b 100644 --- a/mypy/typeshed/stdlib/socketserver.pyi +++ b/mypy/typeshed/stdlib/socketserver.pyi @@ -5,8 +5,8 @@ from _typeshed import ReadableBuffer from collections.abc import Callable from io import BufferedIOBase from socket import socket as _socket -from typing import Any, ClassVar -from typing_extensions import Self, TypeAlias +from typing import Any, ClassVar, TypeAlias +from typing_extensions import Self __all__ = [ "BaseServer", diff --git a/mypy/typeshed/stdlib/spwd.pyi b/mypy/typeshed/stdlib/spwd.pyi index 3a5d39997dcc7..0a06cdfeef642 100644 --- a/mypy/typeshed/stdlib/spwd.pyi +++ b/mypy/typeshed/stdlib/spwd.pyi @@ -5,18 +5,17 @@ from typing import Any, Final, final if sys.platform != "win32": @final class struct_spwd(structseq[Any], tuple[str, str, int, int, int, int, int, int, int]): - if sys.version_info >= (3, 10): - __match_args__: Final = ( - "sp_namp", - "sp_pwdp", - "sp_lstchg", - "sp_min", - "sp_max", - "sp_warn", - "sp_inact", - "sp_expire", - "sp_flag", - ) + __match_args__: Final = ( + "sp_namp", + "sp_pwdp", + "sp_lstchg", + "sp_min", + "sp_max", + "sp_warn", + "sp_inact", + "sp_expire", + "sp_flag", + ) @property def sp_namp(self) -> str: ... diff --git a/mypy/typeshed/stdlib/sqlite3/__init__.pyi b/mypy/typeshed/stdlib/sqlite3/__init__.pyi index ec37eed8c9277..7bf020558199e 100644 --- a/mypy/typeshed/stdlib/sqlite3/__init__.pyi +++ b/mypy/typeshed/stdlib/sqlite3/__init__.pyi @@ -62,12 +62,15 @@ from sqlite3.dbapi2 import ( threadsafety as threadsafety, ) from types import TracebackType -from typing import Any, Literal, Protocol, SupportsIndex, TypeVar, final, overload, type_check_only -from typing_extensions import Self, TypeAlias, disjoint_base +from typing import Any, Literal, Protocol, SupportsIndex, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import Self, disjoint_base if sys.version_info < (3, 14): from sqlite3.dbapi2 import version_info as version_info +if sys.version_info >= (3, 15): + from sqlite3.dbapi2 import SQLITE_KEYWORDS as SQLITE_KEYWORDS + if sys.version_info >= (3, 12): from sqlite3.dbapi2 import ( LEGACY_TRANSACTION_CONTROL as LEGACY_TRANSACTION_CONTROL, @@ -211,9 +214,6 @@ if sys.version_info >= (3, 11): if sys.version_info < (3, 12): from sqlite3.dbapi2 import enable_shared_cache as enable_shared_cache, version as version -if sys.version_info < (3, 10): - from sqlite3.dbapi2 import OptimizedUnicode as OptimizedUnicode - _CursorT = TypeVar("_CursorT", bound=Cursor) _SqliteData: TypeAlias = str | ReadableBuffer | int | float | None # Data that is passed through adapters can be of any type accepted by an adapter. @@ -301,6 +301,7 @@ class Connection: def autocommit(self) -> int: ... @autocommit.setter def autocommit(self, val: int) -> None: ... + row_factory: _RowFactoryOptions text_factory: Any if sys.version_info >= (3, 12): @@ -334,7 +335,10 @@ class Connection: def blobopen(self, table: str, column: str, row: int, /, *, readonly: bool = False, name: str = "main") -> Blob: ... def commit(self) -> None: ... - def create_aggregate(self, name: str, n_arg: int, aggregate_class: Callable[[], _AggregateProtocol]) -> None: ... + if sys.version_info >= (3, 15): + def create_aggregate(self, name: str, n_arg: int, aggregate_class: Callable[[], _AggregateProtocol], /) -> None: ... + else: + def create_aggregate(self, name: str, n_arg: int, aggregate_class: Callable[[], _AggregateProtocol]) -> None: ... if sys.version_info >= (3, 11): # num_params determines how many params will be passed to the aggregate class. We provide an overload # for the case where num_params = 1, which is expected to be the common case. @@ -353,13 +357,20 @@ class Connection: ) -> None: ... def create_collation(self, name: str, callback: Callable[[str, str], SupportsIndex] | None, /) -> None: ... - def create_function( - self, name: str, narg: int, func: Callable[..., _SqliteData] | None, *, deterministic: bool = False - ) -> None: ... + if sys.version_info >= (3, 15): + def create_function( + self, name: str, narg: int, func: Callable[..., _SqliteData] | None, /, *, deterministic: bool = False + ) -> None: ... + else: + def create_function( + self, name: str, narg: int, func: Callable[..., _SqliteData] | None, *, deterministic: bool = False + ) -> None: ... + @overload def cursor(self, factory: None = None) -> Cursor: ... @overload def cursor(self, factory: Callable[[Connection], _CursorT]) -> _CursorT: ... + def execute(self, sql: str, parameters: _Parameters = ..., /) -> Cursor: ... def executemany(self, sql: str, parameters: Iterable[_Parameters], /) -> Cursor: ... def executescript(self, sql_script: str, /) -> Cursor: ... @@ -370,11 +381,18 @@ class Connection: def iterdump(self) -> Generator[str]: ... def rollback(self) -> None: ... - def set_authorizer( - self, authorizer_callback: Callable[[int, str | None, str | None, str | None, str | None], int] | None - ) -> None: ... - def set_progress_handler(self, progress_handler: Callable[[], int | None] | None, n: int) -> None: ... - def set_trace_callback(self, trace_callback: Callable[[str], object] | None) -> None: ... + if sys.version_info >= (3, 15): + def set_authorizer( + self, authorizer_callback: Callable[[int, str | None, str | None, str | None, str | None], int] | None, / + ) -> None: ... + def set_progress_handler(self, progress_handler: Callable[[], int | None] | None, /, n: int) -> None: ... + def set_trace_callback(self, trace_callback: Callable[[str], object] | None, /) -> None: ... + else: + def set_authorizer( + self, authorizer_callback: Callable[[int, str | None, str | None, str | None, str | None], int] | None + ) -> None: ... + def set_progress_handler(self, progress_handler: Callable[[], int | None] | None, n: int) -> None: ... + def set_trace_callback(self, trace_callback: Callable[[str], object] | None) -> None: ... # enable_load_extension and load_extension is not available on python distributions compiled # without sqlite3 loadable extension support. see footnotes https://docs.python.org/3/library/sqlite3.html#f1 def enable_load_extension(self, enable: bool, /) -> None: ... @@ -443,10 +461,12 @@ class PrepareProtocol: class Row(Sequence[Any]): def __new__(cls, cursor: Cursor, data: tuple[Any, ...], /) -> Self: ... def keys(self) -> list[str]: ... + @overload # Note: really needs int instead of SupportsIndex def __getitem__(self, key: int | str, /) -> Any: ... @overload # Note: SupportsIndex does work within slices. def __getitem__(self, key: slice[SupportsIndex | None], /) -> tuple[Any, ...]: ... + def __hash__(self) -> int: ... def __iter__(self) -> Iterator[Any]: ... def __len__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index 9e170a81243d8..0cd676f9bfc87 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -90,6 +90,9 @@ if sys.version_info >= (3, 12): SQLITE_DBCONFIG_WRITABLE_SCHEMA as SQLITE_DBCONFIG_WRITABLE_SCHEMA, ) +if sys.version_info >= (3, 15): + from _sqlite3 import SQLITE_KEYWORDS as SQLITE_KEYWORDS + if sys.version_info >= (3, 11): from _sqlite3 import ( SQLITE_ABORT as SQLITE_ABORT, @@ -215,18 +218,12 @@ if sys.version_info < (3, 14): version: Final[str] if sys.version_info < (3, 12): - if sys.version_info >= (3, 10): - # deprecation wrapper that has a different name for the argument... - @deprecated( - "Deprecated since Python 3.10; removed in Python 3.12. " - "Open database in URI mode using `cache=shared` parameter instead." - ) - def enable_shared_cache(enable: int) -> None: ... - else: - from _sqlite3 import enable_shared_cache as enable_shared_cache - -if sys.version_info < (3, 10): - from _sqlite3 import OptimizedUnicode as OptimizedUnicode + # deprecation wrapper that has a different name for the argument... + @deprecated( + "Deprecated since Python 3.10; removed in Python 3.12. " + "Open database in URI mode using `cache=shared` parameter instead." + ) + def enable_shared_cache(enable: int) -> None: ... paramstyle: Final = "qmark" threadsafety: Literal[0, 1, 3] diff --git a/mypy/typeshed/stdlib/sre_parse.pyi b/mypy/typeshed/stdlib/sre_parse.pyi index eaacbff312a92..6b873f4043b07 100644 --- a/mypy/typeshed/stdlib/sre_parse.pyi +++ b/mypy/typeshed/stdlib/sre_parse.pyi @@ -3,8 +3,7 @@ from collections.abc import Iterable from re import Match, Pattern as _Pattern from sre_constants import * from sre_constants import _NamedIntConstant as _NIC, error as _Error -from typing import Any, Final, overload -from typing_extensions import TypeAlias +from typing import Any, Final, TypeAlias, overload SPECIAL_CHARS: Final = ".\\[{()*+?^$|" REPEAT_CHARS: Final = "*+?{" @@ -91,7 +90,6 @@ if sys.version_info >= (3, 12): def parse_template(source: str, pattern: _Pattern[Any]) -> _TemplateType: ... @overload def parse_template(source: bytes, pattern: _Pattern[Any]) -> _TemplateByteType: ... - else: @overload def parse_template(source: str, state: _Pattern[Any]) -> _TemplateType: ... diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index 57952cf19bbed..590642d99607d 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -27,21 +27,21 @@ from _ssl import ( ) from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer from collections.abc import Callable, Iterable -from typing import Any, Final, Literal, NamedTuple, TypedDict, overload, type_check_only -from typing_extensions import Never, Self, TypeAlias, deprecated +from typing import Any, Final, Literal, NamedTuple, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Never, Self, deprecated if sys.version_info >= (3, 13): from _ssl import HAS_PSK as HAS_PSK +if sys.version_info >= (3, 15): + from _ssl import HAS_PSK_TLS13 as HAS_PSK_TLS13 + if sys.version_info >= (3, 14): from _ssl import HAS_PHA as HAS_PHA if sys.version_info < (3, 12): from _ssl import RAND_pseudo_bytes as RAND_pseudo_bytes -if sys.version_info < (3, 10): - from _ssl import RAND_egd as RAND_egd - if sys.platform == "win32": from _ssl import enum_certificates as enum_certificates, enum_crls as enum_crls @@ -108,19 +108,16 @@ class VerifyFlags(enum.IntFlag): VERIFY_CRL_CHECK_CHAIN = 0x0C VERIFY_X509_STRICT = 0x20 VERIFY_X509_TRUSTED_FIRST = 0x8000 - if sys.version_info >= (3, 10): - VERIFY_ALLOW_PROXY_CERTS = 0x40 - VERIFY_X509_PARTIAL_CHAIN = 0x80000 + VERIFY_ALLOW_PROXY_CERTS = 0x40 + VERIFY_X509_PARTIAL_CHAIN = 0x80000 VERIFY_DEFAULT: Final = VerifyFlags.VERIFY_DEFAULT VERIFY_CRL_CHECK_LEAF: Final = VerifyFlags.VERIFY_CRL_CHECK_LEAF VERIFY_CRL_CHECK_CHAIN: Final = VerifyFlags.VERIFY_CRL_CHECK_CHAIN VERIFY_X509_STRICT: Final = VerifyFlags.VERIFY_X509_STRICT VERIFY_X509_TRUSTED_FIRST: Final = VerifyFlags.VERIFY_X509_TRUSTED_FIRST - -if sys.version_info >= (3, 10): - VERIFY_ALLOW_PROXY_CERTS: Final = VerifyFlags.VERIFY_ALLOW_PROXY_CERTS - VERIFY_X509_PARTIAL_CHAIN: Final = VerifyFlags.VERIFY_X509_PARTIAL_CHAIN +VERIFY_ALLOW_PROXY_CERTS: Final = VerifyFlags.VERIFY_ALLOW_PROXY_CERTS +VERIFY_X509_PARTIAL_CHAIN: Final = VerifyFlags.VERIFY_X509_PARTIAL_CHAIN class _SSLMethod(enum.IntEnum): PROTOCOL_SSLv23 = 2 @@ -286,33 +283,38 @@ class SSLSocket(socket.socket): ) -> tuple[int, socket._RetAddress]: ... def send(self, data: ReadableBuffer, flags: int = 0) -> int: ... def sendall(self, data: ReadableBuffer, flags: int = 0) -> None: ... + @overload def sendto(self, data: ReadableBuffer, flags_or_addr: socket._Address, addr: None = None) -> int: ... @overload def sendto(self, data: ReadableBuffer, flags_or_addr: int, addr: socket._Address) -> int: ... + def shutdown(self, how: int) -> None: ... @deprecated("Deprecated since Python 3.6. Use `SSLSocket.recv` method instead.") - def read(self, len: int = 1024, buffer: bytearray | None = None) -> bytes: ... + def read(self, len: int = 1024, buffer: WriteableBuffer | None = None) -> bytes: ... @deprecated("Deprecated since Python 3.6. Use `SSLSocket.send` method instead.") def write(self, data: ReadableBuffer) -> int: ... def do_handshake(self, block: bool = False) -> None: ... # block is undocumented + @overload def getpeercert(self, binary_form: Literal[False] = False) -> _PeerCertRetDictType | None: ... @overload def getpeercert(self, binary_form: Literal[True]) -> bytes | None: ... @overload def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... + def cipher(self) -> tuple[str, str, int] | None: ... def shared_ciphers(self) -> list[tuple[str, str, int]] | None: ... def compression(self) -> str | None: ... + if sys.version_info >= (3, 15): + def group(self) -> str | None: ... + def client_sigalg(self) -> str | None: ... + def server_sigalg(self) -> str | None: ... + def get_channel_binding(self, cb_type: str = "tls-unique") -> bytes | None: ... def selected_alpn_protocol(self) -> str | None: ... - if sys.version_info >= (3, 10): - @deprecated("Deprecated since Python 3.10. Use ALPN instead.") - def selected_npn_protocol(self) -> str | None: ... - else: - def selected_npn_protocol(self) -> str | None: ... - + @deprecated("Deprecated since Python 3.10. Use ALPN instead.") + def selected_npn_protocol(self) -> str | None: ... def accept(self) -> tuple[SSLSocket, socket._RetAddress]: ... def unwrap(self) -> socket.socket: ... def version(self) -> str | None: ... @@ -346,19 +348,9 @@ if sys.version_info < (3, 12): def cert_time_to_seconds(cert_time: str) -> int: ... def DER_cert_to_PEM_cert(der_cert_bytes: ReadableBuffer) -> str: ... def PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: ... - -if sys.version_info >= (3, 10): - def get_server_certificate( - addr: tuple[str, int], - ssl_version: int = _SSLMethod.PROTOCOL_TLS_CLIENT, - ca_certs: str | None = None, - timeout: float = ..., - ) -> str: ... - -else: - def get_server_certificate( - addr: tuple[str, int], ssl_version: int = _SSLMethod.PROTOCOL_TLS_CLIENT, ca_certs: str | None = None - ) -> str: ... +def get_server_certificate( + addr: tuple[str, int], ssl_version: int = _SSLMethod.PROTOCOL_TLS_CLIENT, ca_certs: str | None = None, timeout: float = ... +) -> str: ... class TLSVersion(enum.IntEnum): MINIMUM_SUPPORTED = -2 @@ -385,16 +377,13 @@ class SSLContext(_SSLContext): sslsocket_class: type[SSLSocket] keylog_filename: str post_handshake_auth: bool - if sys.version_info >= (3, 10): - security_level: int - if sys.version_info >= (3, 10): - @overload - def __new__(cls, protocol: int, *args: Any, **kwargs: Any) -> Self: ... - @overload - @deprecated("Deprecated since Python 3.10. Use a specific version of the SSL protocol.") - def __new__(cls, protocol: None = None, *args: Any, **kwargs: Any) -> Self: ... - else: - def __new__(cls, protocol: int = ..., *args: Any, **kwargs: Any) -> Self: ... + security_level: int + + @overload + def __new__(cls, protocol: int, *args: Any, **kwargs: Any) -> Self: ... + @overload + @deprecated("Deprecated since Python 3.10. Use a specific version of the SSL protocol.") + def __new__(cls, protocol: None = None, *args: Any, **kwargs: Any) -> Self: ... def load_default_certs(self, purpose: Purpose = Purpose.SERVER_AUTH) -> None: ... def load_verify_locations( @@ -403,22 +392,27 @@ class SSLContext(_SSLContext): capath: StrOrBytesPath | None = None, cadata: str | ReadableBuffer | None = None, ) -> None: ... + @overload def get_ca_certs(self, binary_form: Literal[False] = False) -> list[_PeerCertRetDictType]: ... @overload def get_ca_certs(self, binary_form: Literal[True]) -> list[bytes]: ... @overload def get_ca_certs(self, binary_form: bool = False) -> Any: ... + def get_ciphers(self) -> list[_Cipher]: ... + if sys.version_info >= (3, 15): + def set_ciphersuites(self, ciphersuites: str, /) -> None: ... + def get_groups(self, /, *, include_aliases: bool = False) -> list[str]: ... + def set_groups(self, grouplist: str, /) -> None: ... + def set_client_sigalgs(self, sigalgs: str, /) -> None: ... + def set_server_sigalgs(self, sigalgs: str, /) -> None: ... + def set_default_verify_paths(self) -> None: ... def set_ciphers(self, cipherlist: str, /) -> None: ... def set_alpn_protocols(self, alpn_protocols: Iterable[str]) -> None: ... - if sys.version_info >= (3, 10): - @deprecated("Deprecated since Python 3.10. Use ALPN instead.") - def set_npn_protocols(self, npn_protocols: Iterable[str]) -> None: ... - else: - def set_npn_protocols(self, npn_protocols: Iterable[str]) -> None: ... - + @deprecated("Deprecated since Python 3.10. Use ALPN instead.") + def set_npn_protocols(self, npn_protocols: Iterable[str]) -> None: ... def set_servername_callback(self, server_name_callback: _SrvnmeCbType | None) -> None: ... def load_dh_params(self, path: str, /) -> None: ... def set_ecdh_curve(self, name: str, /) -> None: ... @@ -447,34 +441,18 @@ def create_default_context( capath: StrOrBytesPath | None = None, cadata: str | ReadableBuffer | None = None, ) -> SSLContext: ... - -if sys.version_info >= (3, 10): - def _create_unverified_context( - protocol: int | None = None, - *, - cert_reqs: int = VerifyMode.CERT_NONE, - check_hostname: bool = False, - purpose: Purpose = Purpose.SERVER_AUTH, - certfile: StrOrBytesPath | None = None, - keyfile: StrOrBytesPath | None = None, - cafile: StrOrBytesPath | None = None, - capath: StrOrBytesPath | None = None, - cadata: str | ReadableBuffer | None = None, - ) -> SSLContext: ... - -else: - def _create_unverified_context( - protocol: int = ..., - *, - cert_reqs: int = VerifyMode.CERT_NONE, - check_hostname: bool = False, - purpose: Purpose = Purpose.SERVER_AUTH, - certfile: StrOrBytesPath | None = None, - keyfile: StrOrBytesPath | None = None, - cafile: StrOrBytesPath | None = None, - capath: StrOrBytesPath | None = None, - cadata: str | ReadableBuffer | None = None, - ) -> SSLContext: ... +def _create_unverified_context( + protocol: int | None = None, + *, + cert_reqs: int = VerifyMode.CERT_NONE, + check_hostname: bool = False, + purpose: Purpose = Purpose.SERVER_AUTH, + certfile: StrOrBytesPath | None = None, + keyfile: StrOrBytesPath | None = None, + cafile: StrOrBytesPath | None = None, + capath: StrOrBytesPath | None = None, + cadata: str | ReadableBuffer | None = None, +) -> SSLContext: ... _create_default_https_context = create_default_context @@ -488,24 +466,27 @@ class SSLObject: @property def session_reused(self) -> bool: ... def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def read(self, len: int = 1024, buffer: bytearray | None = None) -> bytes: ... + def read(self, len: int = 1024, buffer: WriteableBuffer | None = None) -> bytes: ... def write(self, data: ReadableBuffer) -> int: ... + @overload def getpeercert(self, binary_form: Literal[False] = False) -> _PeerCertRetDictType | None: ... @overload def getpeercert(self, binary_form: Literal[True]) -> bytes | None: ... @overload def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... - def selected_alpn_protocol(self) -> str | None: ... - if sys.version_info >= (3, 10): - @deprecated("Deprecated since Python 3.10. Use ALPN instead.") - def selected_npn_protocol(self) -> str | None: ... - else: - def selected_npn_protocol(self) -> str | None: ... + def selected_alpn_protocol(self) -> str | None: ... + @deprecated("Deprecated since Python 3.10. Use ALPN instead.") + def selected_npn_protocol(self) -> str | None: ... def cipher(self) -> tuple[str, str, int] | None: ... def shared_ciphers(self) -> list[tuple[str, str, int]] | None: ... def compression(self) -> str | None: ... + if sys.version_info >= (3, 15): + def group(self) -> str | None: ... + def client_sigalg(self) -> str | None: ... + def server_sigalg(self) -> str | None: ... + def pending(self) -> int: ... def do_handshake(self) -> None: ... def unwrap(self) -> None: ... @@ -539,6 +520,9 @@ SSL_ERROR_ZERO_RETURN: Final = SSLErrorNumber.SSL_ERROR_ZERO_RETURN # undocumen def get_protocol_name(protocol_code: int) -> str: ... +if sys.version_info >= (3, 15): + def get_sigalgs() -> list[str]: ... + PEM_FOOTER: Final[str] PEM_HEADER: Final[str] SOCK_STREAM: Final = socket.SOCK_STREAM diff --git a/mypy/typeshed/stdlib/stat.pyi b/mypy/typeshed/stdlib/stat.pyi index 6c26080e06653..155d765d2b160 100644 --- a/mypy/typeshed/stdlib/stat.pyi +++ b/mypy/typeshed/stdlib/stat.pyi @@ -112,3 +112,15 @@ FILE_ATTRIBUTE_VIRTUAL: Final = 65536 if sys.version_info >= (3, 13): # https://github.com/python/cpython/issues/114081#issuecomment-2119017790 SF_RESTRICTED: Final = 0x00080000 + +if sys.version_info >= (3, 15): + STATX_ATTR_COMPRESSED: Final = 0x00000004 + STATX_ATTR_IMMUTABLE: Final = 0x00000010 + STATX_ATTR_APPEND: Final = 0x00000020 + STATX_ATTR_NODUMP: Final = 0x00000040 + STATX_ATTR_ENCRYPTED: Final = 0x00000800 + STATX_ATTR_AUTOMOUNT: Final = 0x00001000 + STATX_ATTR_MOUNT_ROOT: Final = 0x00002000 + STATX_ATTR_VERITY: Final = 0x00100000 + STATX_ATTR_DAX: Final = 0x00200000 + STATX_ATTR_WRITE_ATOMIC: Final = 0x00400000 diff --git a/mypy/typeshed/stdlib/statistics.pyi b/mypy/typeshed/stdlib/statistics.pyi index d9f282b99b662..8cae237f7e0b9 100644 --- a/mypy/typeshed/stdlib/statistics.pyi +++ b/mypy/typeshed/stdlib/statistics.pyi @@ -3,13 +3,16 @@ from _typeshed import SupportsRichComparisonT from collections.abc import Callable, Hashable, Iterable, Sequence, Sized from decimal import Decimal from fractions import Fraction -from typing import Literal, NamedTuple, Protocol, SupportsFloat, SupportsIndex, TypeVar, type_check_only -from typing_extensions import Self, TypeAlias +from typing import Literal, NamedTuple, Protocol, SupportsFloat, SupportsIndex, TypeAlias, TypeVar, type_check_only +from typing_extensions import Self __all__ = [ "StatisticsError", + "covariance", + "correlation", "fmean", "geometric_mean", + "linear_regression", "mean", "harmonic_mean", "pstdev", @@ -26,8 +29,6 @@ __all__ = [ "quantiles", ] -if sys.version_info >= (3, 10): - __all__ += ["covariance", "correlation", "linear_regression"] if sys.version_info >= (3, 13): __all__ += ["kde", "kde_random"] @@ -57,13 +58,7 @@ else: def geometric_mean(data: Iterable[SupportsFloat]) -> float: ... def mean(data: Iterable[_NumberT]) -> _NumberT: ... - -if sys.version_info >= (3, 10): - def harmonic_mean(data: Iterable[_NumberT], weights: Iterable[_Number] | None = None) -> _NumberT: ... - -else: - def harmonic_mean(data: Iterable[_NumberT]) -> _NumberT: ... - +def harmonic_mean(data: Iterable[_NumberT], weights: Iterable[_Number] | None = None) -> _NumberT: ... def median(data: Iterable[_NumberT]) -> _NumberT: ... def median_low(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparisonT: ... def median_high(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparisonT: ... @@ -123,22 +118,21 @@ if sys.version_info >= (3, 12): x: Sequence[_Number], y: Sequence[_Number], /, *, method: Literal["linear", "ranked"] = "linear" ) -> float: ... -elif sys.version_info >= (3, 10): +else: def correlation(x: Sequence[_Number], y: Sequence[_Number], /) -> float: ... -if sys.version_info >= (3, 10): - def covariance(x: Sequence[_Number], y: Sequence[_Number], /) -> float: ... +def covariance(x: Sequence[_Number], y: Sequence[_Number], /) -> float: ... - class LinearRegression(NamedTuple): - slope: float - intercept: float +class LinearRegression(NamedTuple): + slope: float + intercept: float if sys.version_info >= (3, 11): def linear_regression( regressor: _SizedIterable[_Number], dependent_variable: _SizedIterable[_Number], /, *, proportional: bool = False ) -> LinearRegression: ... -elif sys.version_info >= (3, 10): +else: def linear_regression( regressor: _SizedIterable[_Number], dependent_variable: _SizedIterable[_Number], / ) -> LinearRegression: ... diff --git a/mypy/typeshed/stdlib/string/__init__.pyi b/mypy/typeshed/stdlib/string/__init__.pyi index c8b32a98e26d7..df70cdc6b21c8 100644 --- a/mypy/typeshed/stdlib/string/__init__.pyi +++ b/mypy/typeshed/stdlib/string/__init__.pyi @@ -54,12 +54,14 @@ class Formatter: def format(self, format_string: LiteralString, /, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... @overload def format(self, format_string: str, /, *args: Any, **kwargs: Any) -> str: ... + @overload def vformat( self, format_string: LiteralString, args: Sequence[LiteralString], kwargs: Mapping[LiteralString, LiteralString] ) -> LiteralString: ... @overload def vformat(self, format_string: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> str: ... + def _vformat( # undocumented self, format_string: str, diff --git a/mypy/typeshed/stdlib/string/templatelib.pyi b/mypy/typeshed/stdlib/string/templatelib.pyi index 9906d31c63915..ee901cdc43b8e 100644 --- a/mypy/typeshed/stdlib/string/templatelib.pyi +++ b/mypy/typeshed/stdlib/string/templatelib.pyi @@ -1,24 +1,24 @@ from collections.abc import Iterator from types import GenericAlias -from typing import Any, Literal, TypeVar, final, overload +from typing import Any, Generic, Literal, TypeVar, final, overload _T = TypeVar("_T") @final class Template: # TODO: consider making `Template` generic on `TypeVarTuple` strings: tuple[str, ...] - interpolations: tuple[Interpolation, ...] + interpolations: tuple[Interpolation[Any], ...] - def __new__(cls, *args: str | Interpolation) -> Template: ... - def __iter__(self) -> Iterator[str | Interpolation]: ... + def __new__(cls, *args: str | Interpolation[Any]) -> Template: ... + def __iter__(self) -> Iterator[str | Interpolation[Any]]: ... def __add__(self, other: Template, /) -> Template: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @property def values(self) -> tuple[Any, ...]: ... # Tuple of interpolation values, which can have any type @final -class Interpolation: - value: Any # TODO: consider making `Interpolation` generic in runtime +class Interpolation(Generic[_T]): + value: _T expression: str conversion: Literal["a", "r", "s"] | None format_spec: str @@ -26,8 +26,8 @@ class Interpolation: __match_args__ = ("value", "expression", "conversion", "format_spec") def __new__( - cls, value: Any, expression: str = "", conversion: Literal["a", "r", "s"] | None = None, format_spec: str = "" - ) -> Interpolation: ... + cls, value: _T, expression: str = "", conversion: Literal["a", "r", "s"] | None = None, format_spec: str = "" + ) -> Interpolation[_T]: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @overload diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index f6d7b88193ec3..c191f0e35de9b 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import MaybeNone, ReadableBuffer, StrOrBytesPath from collections.abc import Callable, Collection, Iterable, Mapping, Sequence from types import GenericAlias, TracebackType -from typing import IO, Any, AnyStr, Final, Generic, Literal, TypeVar, overload -from typing_extensions import Self, TypeAlias +from typing import IO, Any, AnyStr, Final, Generic, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self __all__ = [ "Popen", @@ -88,7 +88,7 @@ class CompletedProcess(Generic[_T]): if sys.version_info >= (3, 11): # 3.11 adds "process_group" argument - @overload + @overload # text is True def run( args: _CMD, bufsize: int = -1, @@ -101,7 +101,7 @@ if sys.version_info >= (3, 11): shell: bool = False, cwd: StrOrBytesPath | None = None, env: _ENV | None = None, - universal_newlines: bool | None = None, + universal_newlines: Literal[True] | None = None, startupinfo: Any = None, creationflags: int = 0, restore_signals: bool = True, @@ -122,7 +122,7 @@ if sys.version_info >= (3, 11): pipesize: int = -1, process_group: int | None = None, ) -> CompletedProcess[str]: ... - @overload + @overload # encoding is str def run( args: _CMD, bufsize: int = -1, @@ -156,7 +156,7 @@ if sys.version_info >= (3, 11): pipesize: int = -1, process_group: int | None = None, ) -> CompletedProcess[str]: ... - @overload + @overload # errors is str def run( args: _CMD, bufsize: int = -1, @@ -190,7 +190,7 @@ if sys.version_info >= (3, 11): pipesize: int = -1, process_group: int | None = None, ) -> CompletedProcess[str]: ... - @overload + @overload # universal_newlines is True def run( args: _CMD, bufsize: int = -1, @@ -216,7 +216,7 @@ if sys.version_info >= (3, 11): encoding: str | None = None, errors: str | None = None, input: str | None = None, - text: bool | None = None, + text: Literal[True] | None = None, timeout: float | None = None, user: str | int | None = None, group: str | int | None = None, @@ -225,7 +225,7 @@ if sys.version_info >= (3, 11): pipesize: int = -1, process_group: int | None = None, ) -> CompletedProcess[str]: ... - @overload + @overload # universal_newlines and text are False, None, or missing def run( args: _CMD, bufsize: int = -1, @@ -259,7 +259,7 @@ if sys.version_info >= (3, 11): pipesize: int = -1, process_group: int | None = None, ) -> CompletedProcess[bytes]: ... - @overload + @overload # fallback def run( args: _CMD, bufsize: int = -1, @@ -293,10 +293,9 @@ if sys.version_info >= (3, 11): pipesize: int = -1, process_group: int | None = None, ) -> CompletedProcess[Any]: ... - -elif sys.version_info >= (3, 10): +else: # 3.10 adds "pipesize" argument - @overload + @overload # text is True def run( args: _CMD, bufsize: int = -1, @@ -309,7 +308,7 @@ elif sys.version_info >= (3, 10): shell: bool = False, cwd: StrOrBytesPath | None = None, env: _ENV | None = None, - universal_newlines: bool | None = None, + universal_newlines: Literal[True] | None = None, startupinfo: Any = None, creationflags: int = 0, restore_signals: bool = True, @@ -329,7 +328,7 @@ elif sys.version_info >= (3, 10): umask: int = -1, pipesize: int = -1, ) -> CompletedProcess[str]: ... - @overload + @overload # encoding is str def run( args: _CMD, bufsize: int = -1, @@ -362,7 +361,7 @@ elif sys.version_info >= (3, 10): umask: int = -1, pipesize: int = -1, ) -> CompletedProcess[str]: ... - @overload + @overload # errors is str def run( args: _CMD, bufsize: int = -1, @@ -395,7 +394,7 @@ elif sys.version_info >= (3, 10): umask: int = -1, pipesize: int = -1, ) -> CompletedProcess[str]: ... - @overload + @overload # universal_newlines is True def run( args: _CMD, bufsize: int = -1, @@ -421,7 +420,7 @@ elif sys.version_info >= (3, 10): encoding: str | None = None, errors: str | None = None, input: str | None = None, - text: bool | None = None, + text: Literal[True] | None = None, timeout: float | None = None, user: str | int | None = None, group: str | int | None = None, @@ -429,7 +428,7 @@ elif sys.version_info >= (3, 10): umask: int = -1, pipesize: int = -1, ) -> CompletedProcess[str]: ... - @overload + @overload # universal_newlines and text are False, None, or missing def run( args: _CMD, bufsize: int = -1, @@ -462,7 +461,7 @@ elif sys.version_info >= (3, 10): umask: int = -1, pipesize: int = -1, ) -> CompletedProcess[bytes]: ... - @overload + @overload # fallback def run( args: _CMD, bufsize: int = -1, @@ -495,458 +494,16 @@ elif sys.version_info >= (3, 10): umask: int = -1, pipesize: int = -1, ) -> CompletedProcess[Any]: ... - -else: - @overload - def run( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stdout: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - capture_output: bool = False, - check: bool = False, - encoding: str | None = None, - errors: str | None = None, - input: str | None = None, - text: Literal[True], - timeout: float | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - ) -> CompletedProcess[str]: ... - @overload - def run( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stdout: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - capture_output: bool = False, - check: bool = False, - encoding: str, - errors: str | None = None, - input: str | None = None, - text: bool | None = None, - timeout: float | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - ) -> CompletedProcess[str]: ... - @overload - def run( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stdout: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - capture_output: bool = False, - check: bool = False, - encoding: str | None = None, - errors: str, - input: str | None = None, - text: bool | None = None, - timeout: float | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - ) -> CompletedProcess[str]: ... - @overload - def run( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stdout: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - *, - universal_newlines: Literal[True], - startupinfo: Any = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - # where the *real* keyword only args start - capture_output: bool = False, - check: bool = False, - encoding: str | None = None, - errors: str | None = None, - input: str | None = None, - text: bool | None = None, - timeout: float | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - ) -> CompletedProcess[str]: ... - @overload - def run( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stdout: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: Literal[False] | None = None, - startupinfo: Any = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - capture_output: bool = False, - check: bool = False, - encoding: None = None, - errors: None = None, - input: ReadableBuffer | None = None, - text: Literal[False] | None = None, - timeout: float | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - ) -> CompletedProcess[bytes]: ... - @overload - def run( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stdout: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - capture_output: bool = False, - check: bool = False, - encoding: str | None = None, - errors: str | None = None, - input: _InputString | None = None, - text: bool | None = None, - timeout: float | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - ) -> CompletedProcess[Any]: ... - -# Same args as Popen.__init__ -if sys.version_info >= (3, 11): - # 3.11 adds "process_group" argument - def call( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stdout: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - encoding: str | None = None, - timeout: float | None = None, - text: bool | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - pipesize: int = -1, - process_group: int | None = None, - ) -> int: ... - -elif sys.version_info >= (3, 10): - # 3.10 adds "pipesize" argument - def call( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stdout: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - encoding: str | None = None, - timeout: float | None = None, - text: bool | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - pipesize: int = -1, - ) -> int: ... - -else: - def call( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stdout: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - encoding: str | None = None, - timeout: float | None = None, - text: bool | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - ) -> int: ... - -# Same args as Popen.__init__ -if sys.version_info >= (3, 11): - # 3.11 adds "process_group" argument - def check_call( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stdout: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - timeout: float | None = None, - *, - encoding: str | None = None, - text: bool | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - pipesize: int = -1, - process_group: int | None = None, - ) -> int: ... - -elif sys.version_info >= (3, 10): - # 3.10 adds "pipesize" argument - def check_call( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stdout: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - timeout: float | None = None, - *, - encoding: str | None = None, - text: bool | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - pipesize: int = -1, - ) -> int: ... - -else: - def check_call( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stdout: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - timeout: float | None = None, - *, - encoding: str | None = None, - text: bool | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - ) -> int: ... - -if sys.version_info >= (3, 11): - # 3.11 adds "process_group" argument - @overload - def check_output( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - timeout: float | None = None, - input: _InputString | None = None, - encoding: str | None = None, - errors: str | None = None, - text: Literal[True], - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - pipesize: int = -1, - process_group: int | None = None, - ) -> str: ... - @overload - def check_output( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - timeout: float | None = None, - input: _InputString | None = None, - encoding: str, - errors: str | None = None, - text: bool | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - pipesize: int = -1, - process_group: int | None = None, - ) -> str: ... - @overload - def check_output( + +# Same args as Popen.__init__ +if sys.version_info >= (3, 11): + # 3.11 adds "process_group" argument + def call( args: _CMD, bufsize: int = -1, executable: StrOrBytesPath | None = None, stdin: _FILE = None, + stdout: _FILE = None, stderr: _FILE = None, preexec_fn: Callable[[], object] | None = None, close_fds: bool = True, @@ -960,10 +517,8 @@ if sys.version_info >= (3, 11): start_new_session: bool = False, pass_fds: Collection[int] = (), *, - timeout: float | None = None, - input: _InputString | None = None, encoding: str | None = None, - errors: str, + timeout: float | None = None, text: bool | None = None, user: str | int | None = None, group: str | int | None = None, @@ -971,76 +526,80 @@ if sys.version_info >= (3, 11): umask: int = -1, pipesize: int = -1, process_group: int | None = None, - ) -> str: ... - @overload - def check_output( + ) -> int: ... + +else: + # 3.10 adds "pipesize" argument + def call( args: _CMD, bufsize: int = -1, executable: StrOrBytesPath | None = None, stdin: _FILE = None, + stdout: _FILE = None, stderr: _FILE = None, preexec_fn: Callable[[], object] | None = None, close_fds: bool = True, shell: bool = False, cwd: StrOrBytesPath | None = None, env: _ENV | None = None, - *, - universal_newlines: Literal[True], + universal_newlines: bool | None = None, startupinfo: Any = None, creationflags: int = 0, restore_signals: bool = True, start_new_session: bool = False, pass_fds: Collection[int] = (), - # where the real keyword only ones start - timeout: float | None = None, - input: _InputString | None = None, + *, encoding: str | None = None, - errors: str | None = None, + timeout: float | None = None, text: bool | None = None, user: str | int | None = None, group: str | int | None = None, extra_groups: Iterable[str | int] | None = None, umask: int = -1, pipesize: int = -1, - process_group: int | None = None, - ) -> str: ... - @overload - def check_output( + ) -> int: ... + +# Same args as Popen.__init__ +if sys.version_info >= (3, 11): + # 3.11 adds "process_group" argument + def check_call( args: _CMD, bufsize: int = -1, executable: StrOrBytesPath | None = None, stdin: _FILE = None, + stdout: _FILE = None, stderr: _FILE = None, preexec_fn: Callable[[], object] | None = None, close_fds: bool = True, shell: bool = False, cwd: StrOrBytesPath | None = None, env: _ENV | None = None, - universal_newlines: Literal[False] | None = None, + universal_newlines: bool | None = None, startupinfo: Any = None, creationflags: int = 0, restore_signals: bool = True, start_new_session: bool = False, pass_fds: Collection[int] = (), - *, timeout: float | None = None, - input: _InputString | None = None, - encoding: None = None, - errors: None = None, - text: Literal[False] | None = None, + *, + encoding: str | None = None, + text: bool | None = None, user: str | int | None = None, group: str | int | None = None, extra_groups: Iterable[str | int] | None = None, umask: int = -1, pipesize: int = -1, process_group: int | None = None, - ) -> bytes: ... - @overload - def check_output( + ) -> int: ... + +else: + # 3.10 adds "pipesize" argument + def check_call( args: _CMD, bufsize: int = -1, executable: StrOrBytesPath | None = None, stdin: _FILE = None, + stdout: _FILE = None, stderr: _FILE = None, preexec_fn: Callable[[], object] | None = None, close_fds: bool = True, @@ -1053,23 +612,20 @@ if sys.version_info >= (3, 11): restore_signals: bool = True, start_new_session: bool = False, pass_fds: Collection[int] = (), - *, timeout: float | None = None, - input: _InputString | None = None, + *, encoding: str | None = None, - errors: str | None = None, text: bool | None = None, user: str | int | None = None, group: str | int | None = None, extra_groups: Iterable[str | int] | None = None, umask: int = -1, pipesize: int = -1, - process_group: int | None = None, - ) -> Any: ... # morally: -> str | bytes + ) -> int: ... -elif sys.version_info >= (3, 10): - # 3.10 adds "pipesize" argument - @overload +if sys.version_info >= (3, 11): + # 3.11 adds "process_group" argument + @overload # text is True def check_output( args: _CMD, bufsize: int = -1, @@ -1081,7 +637,7 @@ elif sys.version_info >= (3, 10): shell: bool = False, cwd: StrOrBytesPath | None = None, env: _ENV | None = None, - universal_newlines: bool | None = None, + universal_newlines: Literal[True] | None = None, startupinfo: Any = None, creationflags: int = 0, restore_signals: bool = True, @@ -1098,8 +654,9 @@ elif sys.version_info >= (3, 10): extra_groups: Iterable[str | int] | None = None, umask: int = -1, pipesize: int = -1, + process_group: int | None = None, ) -> str: ... - @overload + @overload # encoding is str def check_output( args: _CMD, bufsize: int = -1, @@ -1128,8 +685,9 @@ elif sys.version_info >= (3, 10): extra_groups: Iterable[str | int] | None = None, umask: int = -1, pipesize: int = -1, + process_group: int | None = None, ) -> str: ... - @overload + @overload # errors is str def check_output( args: _CMD, bufsize: int = -1, @@ -1158,8 +716,9 @@ elif sys.version_info >= (3, 10): extra_groups: Iterable[str | int] | None = None, umask: int = -1, pipesize: int = -1, + process_group: int | None = None, ) -> str: ... - @overload + @overload # universal_newlines is True def check_output( args: _CMD, bufsize: int = -1, @@ -1183,14 +742,15 @@ elif sys.version_info >= (3, 10): input: _InputString | None = None, encoding: str | None = None, errors: str | None = None, - text: bool | None = None, + text: Literal[True] | None = None, user: str | int | None = None, group: str | int | None = None, extra_groups: Iterable[str | int] | None = None, umask: int = -1, pipesize: int = -1, + process_group: int | None = None, ) -> str: ... - @overload + @overload # universal_newlines and text are False, None, or missing def check_output( args: _CMD, bufsize: int = -1, @@ -1219,8 +779,9 @@ elif sys.version_info >= (3, 10): extra_groups: Iterable[str | int] | None = None, umask: int = -1, pipesize: int = -1, + process_group: int | None = None, ) -> bytes: ... - @overload + @overload # fallback def check_output( args: _CMD, bufsize: int = -1, @@ -1249,10 +810,11 @@ elif sys.version_info >= (3, 10): extra_groups: Iterable[str | int] | None = None, umask: int = -1, pipesize: int = -1, + process_group: int | None = None, ) -> Any: ... # morally: -> str | bytes - else: - @overload + # 3.10 adds "pipesize" argument + @overload # text is True def check_output( args: _CMD, bufsize: int = -1, @@ -1264,7 +826,7 @@ else: shell: bool = False, cwd: StrOrBytesPath | None = None, env: _ENV | None = None, - universal_newlines: bool | None = None, + universal_newlines: Literal[True] | None = None, startupinfo: Any = None, creationflags: int = 0, restore_signals: bool = True, @@ -1280,8 +842,9 @@ else: group: str | int | None = None, extra_groups: Iterable[str | int] | None = None, umask: int = -1, + pipesize: int = -1, ) -> str: ... - @overload + @overload # encoding is str def check_output( args: _CMD, bufsize: int = -1, @@ -1309,8 +872,9 @@ else: group: str | int | None = None, extra_groups: Iterable[str | int] | None = None, umask: int = -1, + pipesize: int = -1, ) -> str: ... - @overload + @overload # errors is str def check_output( args: _CMD, bufsize: int = -1, @@ -1338,8 +902,9 @@ else: group: str | int | None = None, extra_groups: Iterable[str | int] | None = None, umask: int = -1, + pipesize: int = -1, ) -> str: ... - @overload + @overload # universal_newlines is True def check_output( args: _CMD, bufsize: int = -1, @@ -1363,13 +928,14 @@ else: input: _InputString | None = None, encoding: str | None = None, errors: str | None = None, - text: bool | None = None, + text: Literal[True] | None = None, user: str | int | None = None, group: str | int | None = None, extra_groups: Iterable[str | int] | None = None, umask: int = -1, + pipesize: int = -1, ) -> str: ... - @overload + @overload # universal_newlines and text are False, None, or missing def check_output( args: _CMD, bufsize: int = -1, @@ -1397,8 +963,9 @@ else: group: str | int | None = None, extra_groups: Iterable[str | int] | None = None, umask: int = -1, + pipesize: int = -1, ) -> bytes: ... - @overload + @overload # fallback def check_output( args: _CMD, bufsize: int = -1, @@ -1426,6 +993,7 @@ else: group: str | int | None = None, extra_groups: Iterable[str | int] | None = None, umask: int = -1, + pipesize: int = -1, ) -> Any: ... # morally: -> str | bytes PIPE: Final[int] @@ -1462,16 +1030,16 @@ class CalledProcessError(SubprocessError): class Popen(Generic[AnyStr]): args: _CMD - stdin: IO[AnyStr] | None - stdout: IO[AnyStr] | None - stderr: IO[AnyStr] | None + stdin: IO[Any] | None + stdout: IO[Any] | None + stderr: IO[Any] | None pid: int returncode: int | MaybeNone universal_newlines: bool if sys.version_info >= (3, 11): # process_group is added in 3.11 - @overload + @overload # encoding is str def __init__( self: Popen[str], args: _CMD, @@ -1502,7 +1070,7 @@ class Popen(Generic[AnyStr]): pipesize: int = -1, process_group: int | None = None, ) -> None: ... - @overload + @overload # errors is str def __init__( self: Popen[str], args: _CMD, @@ -1533,7 +1101,7 @@ class Popen(Generic[AnyStr]): pipesize: int = -1, process_group: int | None = None, ) -> None: ... - @overload + @overload # universal_newlines is True def __init__( self: Popen[str], args: _CMD, @@ -1565,7 +1133,7 @@ class Popen(Generic[AnyStr]): pipesize: int = -1, process_group: int | None = None, ) -> None: ... - @overload + @overload # text is True def __init__( self: Popen[str], args: _CMD, @@ -1579,7 +1147,7 @@ class Popen(Generic[AnyStr]): shell: bool = False, cwd: StrOrBytesPath | None = None, env: _ENV | None = None, - universal_newlines: bool | None = None, + universal_newlines: Literal[True] | None = None, startupinfo: Any | None = None, creationflags: int = 0, restore_signals: bool = True, @@ -1596,7 +1164,7 @@ class Popen(Generic[AnyStr]): pipesize: int = -1, process_group: int | None = None, ) -> None: ... - @overload + @overload # universal_newlines and text are False, None, or missing def __init__( self: Popen[bytes], args: _CMD, @@ -1627,7 +1195,7 @@ class Popen(Generic[AnyStr]): pipesize: int = -1, process_group: int | None = None, ) -> None: ... - @overload + @overload # fallback def __init__( self: Popen[Any], args: _CMD, @@ -1658,9 +1226,9 @@ class Popen(Generic[AnyStr]): pipesize: int = -1, process_group: int | None = None, ) -> None: ... - elif sys.version_info >= (3, 10): + else: # pipesize is added in 3.10 - @overload + @overload # encoding is str def __init__( self: Popen[str], args: _CMD, @@ -1690,7 +1258,7 @@ class Popen(Generic[AnyStr]): umask: int = -1, pipesize: int = -1, ) -> None: ... - @overload + @overload # errors is str def __init__( self: Popen[str], args: _CMD, @@ -1720,7 +1288,7 @@ class Popen(Generic[AnyStr]): umask: int = -1, pipesize: int = -1, ) -> None: ... - @overload + @overload # universal_newlines is True def __init__( self: Popen[str], args: _CMD, @@ -1751,7 +1319,7 @@ class Popen(Generic[AnyStr]): umask: int = -1, pipesize: int = -1, ) -> None: ... - @overload + @overload # text is True def __init__( self: Popen[str], args: _CMD, @@ -1765,7 +1333,7 @@ class Popen(Generic[AnyStr]): shell: bool = False, cwd: StrOrBytesPath | None = None, env: _ENV | None = None, - universal_newlines: bool | None = None, + universal_newlines: Literal[True] | None = None, startupinfo: Any | None = None, creationflags: int = 0, restore_signals: bool = True, @@ -1781,7 +1349,7 @@ class Popen(Generic[AnyStr]): umask: int = -1, pipesize: int = -1, ) -> None: ... - @overload + @overload # universal_newlines and text are False, None, or missing def __init__( self: Popen[bytes], args: _CMD, @@ -1811,7 +1379,7 @@ class Popen(Generic[AnyStr]): umask: int = -1, pipesize: int = -1, ) -> None: ... - @overload + @overload # fallback def __init__( self: Popen[Any], args: _CMD, @@ -1841,182 +1409,6 @@ class Popen(Generic[AnyStr]): umask: int = -1, pipesize: int = -1, ) -> None: ... - else: - @overload - def __init__( - self: Popen[str], - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE | None = None, - stdout: _FILE | None = None, - stderr: _FILE | None = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any | None = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - text: bool | None = None, - encoding: str, - errors: str | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - ) -> None: ... - @overload - def __init__( - self: Popen[str], - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE | None = None, - stdout: _FILE | None = None, - stderr: _FILE | None = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any | None = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - text: bool | None = None, - encoding: str | None = None, - errors: str, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - ) -> None: ... - @overload - def __init__( - self: Popen[str], - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE | None = None, - stdout: _FILE | None = None, - stderr: _FILE | None = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - *, - universal_newlines: Literal[True], - startupinfo: Any | None = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - # where the *real* keyword only args start - text: bool | None = None, - encoding: str | None = None, - errors: str | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - ) -> None: ... - @overload - def __init__( - self: Popen[str], - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE | None = None, - stdout: _FILE | None = None, - stderr: _FILE | None = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any | None = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - text: Literal[True], - encoding: str | None = None, - errors: str | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - ) -> None: ... - @overload - def __init__( - self: Popen[bytes], - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE | None = None, - stdout: _FILE | None = None, - stderr: _FILE | None = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: Literal[False] | None = None, - startupinfo: Any | None = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - text: Literal[False] | None = None, - encoding: None = None, - errors: None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - ) -> None: ... - @overload - def __init__( - self: Popen[Any], - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE | None = None, - stdout: _FILE | None = None, - stderr: _FILE | None = None, - preexec_fn: Callable[[], object] | None = None, - close_fds: bool = True, - shell: bool = False, - cwd: StrOrBytesPath | None = None, - env: _ENV | None = None, - universal_newlines: bool | None = None, - startupinfo: Any | None = None, - creationflags: int = 0, - restore_signals: bool = True, - start_new_session: bool = False, - pass_fds: Collection[int] = (), - *, - text: bool | None = None, - encoding: str | None = None, - errors: str | None = None, - user: str | int | None = None, - group: str | int | None = None, - extra_groups: Iterable[str | int] | None = None, - umask: int = -1, - ) -> None: ... def poll(self) -> int | None: ... def wait(self, timeout: float | None = None) -> int: ... diff --git a/mypy/typeshed/stdlib/sunau.pyi b/mypy/typeshed/stdlib/sunau.pyi index f83a0a4c520e7..1f18c041465ef 100644 --- a/mypy/typeshed/stdlib/sunau.pyi +++ b/mypy/typeshed/stdlib/sunau.pyi @@ -1,6 +1,6 @@ from _typeshed import Unused -from typing import IO, Any, Final, Literal, NamedTuple, NoReturn, overload -from typing_extensions import Self, TypeAlias +from typing import IO, Any, Final, Literal, NamedTuple, NoReturn, TypeAlias, overload +from typing_extensions import Self _File: TypeAlias = str | IO[bytes] diff --git a/mypy/typeshed/stdlib/symbol.pyi b/mypy/typeshed/stdlib/symbol.pyi deleted file mode 100644 index 5344ce504c6c7..0000000000000 --- a/mypy/typeshed/stdlib/symbol.pyi +++ /dev/null @@ -1,95 +0,0 @@ -from typing import Final - -single_input: Final[int] -file_input: Final[int] -eval_input: Final[int] -decorator: Final[int] -decorators: Final[int] -decorated: Final[int] -async_funcdef: Final[int] -funcdef: Final[int] -parameters: Final[int] -typedargslist: Final[int] -tfpdef: Final[int] -varargslist: Final[int] -vfpdef: Final[int] -stmt: Final[int] -simple_stmt: Final[int] -small_stmt: Final[int] -expr_stmt: Final[int] -annassign: Final[int] -testlist_star_expr: Final[int] -augassign: Final[int] -del_stmt: Final[int] -pass_stmt: Final[int] -flow_stmt: Final[int] -break_stmt: Final[int] -continue_stmt: Final[int] -return_stmt: Final[int] -yield_stmt: Final[int] -raise_stmt: Final[int] -import_stmt: Final[int] -import_name: Final[int] -import_from: Final[int] -import_as_name: Final[int] -dotted_as_name: Final[int] -import_as_names: Final[int] -dotted_as_names: Final[int] -dotted_name: Final[int] -global_stmt: Final[int] -nonlocal_stmt: Final[int] -assert_stmt: Final[int] -compound_stmt: Final[int] -async_stmt: Final[int] -if_stmt: Final[int] -while_stmt: Final[int] -for_stmt: Final[int] -try_stmt: Final[int] -with_stmt: Final[int] -with_item: Final[int] -except_clause: Final[int] -suite: Final[int] -test: Final[int] -test_nocond: Final[int] -lambdef: Final[int] -lambdef_nocond: Final[int] -or_test: Final[int] -and_test: Final[int] -not_test: Final[int] -comparison: Final[int] -comp_op: Final[int] -star_expr: Final[int] -expr: Final[int] -xor_expr: Final[int] -and_expr: Final[int] -shift_expr: Final[int] -arith_expr: Final[int] -term: Final[int] -factor: Final[int] -power: Final[int] -atom_expr: Final[int] -atom: Final[int] -testlist_comp: Final[int] -trailer: Final[int] -subscriptlist: Final[int] -subscript: Final[int] -sliceop: Final[int] -exprlist: Final[int] -testlist: Final[int] -dictorsetmaker: Final[int] -classdef: Final[int] -arglist: Final[int] -argument: Final[int] -comp_iter: Final[int] -comp_for: Final[int] -comp_if: Final[int] -encoding_decl: Final[int] -yield_expr: Final[int] -yield_arg: Final[int] -sync_comp_for: Final[int] -func_body_suite: Final[int] -func_type: Final[int] -func_type_input: Final[int] -namedexpr_test: Final[int] -typelist: Final[int] -sym_name: Final[dict[int, str]] diff --git a/mypy/typeshed/stdlib/symtable.pyi b/mypy/typeshed/stdlib/symtable.pyi index a727b878688ed..d41ef8419dec8 100644 --- a/mypy/typeshed/stdlib/symtable.pyi +++ b/mypy/typeshed/stdlib/symtable.pyi @@ -9,7 +9,11 @@ __all__ = ["symtable", "SymbolTable", "Class", "Function", "Symbol"] if sys.version_info >= (3, 13): __all__ += ["SymbolTableType"] -def symtable(code: str, filename: str, compile_type: str) -> SymbolTable: ... +if sys.version_info >= (3, 15): + def symtable(code: str, filename: str, compile_type: str, *, module: str | None = None) -> SymbolTable: ... + +else: + def symtable(code: str, filename: str, compile_type: str) -> SymbolTable: ... if sys.version_info >= (3, 13): from enum import StrEnum @@ -46,14 +50,14 @@ class Function(SymbolTable): def get_locals(self) -> tuple[str, ...]: ... def get_globals(self) -> tuple[str, ...]: ... def get_frees(self) -> tuple[str, ...]: ... + if sys.version_info >= (3, 15): + def get_cells(self) -> tuple[str, ...]: ... + def get_nonlocals(self) -> tuple[str, ...]: ... class Class(SymbolTable): - if sys.version_info >= (3, 14): - @deprecated("Deprecated since Python 3.14; will be removed in Python 3.16.") - def get_methods(self) -> tuple[str, ...]: ... - else: - def get_methods(self) -> tuple[str, ...]: ... + @deprecated("Deprecated since Python 3.14; will be removed in Python 3.16.") + def get_methods(self) -> tuple[str, ...]: ... class Symbol: def __init__( @@ -79,6 +83,8 @@ class Symbol: if sys.version_info >= (3, 14): def is_comp_iter(self) -> bool: ... def is_comp_cell(self) -> bool: ... + if sys.version_info >= (3, 15): + def is_cell(self) -> bool: ... def is_namespace(self) -> bool: ... def get_namespaces(self) -> Sequence[SymbolTable]: ... diff --git a/mypy/typeshed/stdlib/sys/__init__.pyi b/mypy/typeshed/stdlib/sys/__init__.pyi index 6abef85dfb7f1..51c6d1deeecce 100644 --- a/mypy/typeshed/stdlib/sys/__init__.pyi +++ b/mypy/typeshed/stdlib/sys/__init__.pyi @@ -4,18 +4,30 @@ from _typeshed.importlib import MetaPathFinderProtocol, PathEntryFinderProtocol from builtins import object as _object from collections.abc import AsyncGenerator, Callable, Sequence from io import TextIOWrapper -from types import FrameType, ModuleType, TracebackType -from typing import Any, Final, Literal, NoReturn, Protocol, TextIO, TypeVar, final, overload, type_check_only -from typing_extensions import LiteralString, TypeAlias, deprecated +from types import FrameType, ModuleType, SimpleNamespace, TracebackType +from typing import Any, Final, Literal, NoReturn, Protocol, TextIO, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import LiteralString, deprecated _T = TypeVar("_T") +_LazyImportMode: TypeAlias = Literal["normal", "all", "none"] +_LazyImportFilter: TypeAlias = Callable[[str, str, tuple[str, ...] | None], bool] # see https://github.com/python/typeshed/issues/8513#issue-1333671093 for the rationale behind this alias _ExitCode: TypeAlias = str | int | None +if sys.version_info >= (3, 15): + @type_check_only + class _AbiInfo(SimpleNamespace): + pointer_bits: int + free_threaded: bool + debug: bool + byteorder: Literal["little", "big"] + # ----- sys variables ----- if sys.platform != "win32": abiflags: str +if sys.version_info >= (3, 15): + abi_info: _AbiInfo argv: list[str] base_exec_prefix: str base_prefix: str @@ -40,8 +52,9 @@ maxsize: int maxunicode: int meta_path: list[MetaPathFinderProtocol] modules: dict[str, ModuleType] -if sys.version_info >= (3, 10): - orig_argv: list[str] +if sys.version_info >= (3, 15): + lazy_modules: dict[str, set[str]] +orig_argv: list[str] path: list[str] path_hooks: list[Callable[[str], PathEntryFinderProtocol]] path_importer_cache: dict[str, PathEntryFinderProtocol | None] @@ -65,9 +78,7 @@ ps2: object stdin: TextIO | MaybeNone stdout: TextIO | MaybeNone stderr: TextIO | MaybeNone - -if sys.version_info >= (3, 10): - stdlib_module_names: frozenset[str] +stdlib_module_names: frozenset[str] __stdin__: Final[TextIOWrapper | None] # Contains the original value of stdin __stdout__: Final[TextIOWrapper | None] # Contains the original value of stdout @@ -124,7 +135,7 @@ class _flags(_UninstantiableStructseq, tuple[int, ...]): "safe_path", "int_max_str_digits", ) - elif sys.version_info >= (3, 10): + else: __match_args__: Final = ( "debug", "inspect", @@ -175,9 +186,8 @@ class _flags(_UninstantiableStructseq, tuple[int, ...]): def dev_mode(self) -> bool: ... @property def utf8_mode(self) -> int: ... - if sys.version_info >= (3, 10): - @property - def warn_default_encoding(self) -> int: ... + @property + def warn_default_encoding(self) -> int: ... if sys.version_info >= (3, 11): @property def safe_path(self) -> bool: ... @@ -203,20 +213,19 @@ float_info: _float_info @final @type_check_only class _float_info(structseq[float], tuple[float, int, int, float, int, int, int, int, float, int, int]): - if sys.version_info >= (3, 10): - __match_args__: Final = ( - "max", - "max_exp", - "max_10_exp", - "min", - "min_exp", - "min_10_exp", - "dig", - "mant_dig", - "epsilon", - "radix", - "rounds", - ) + __match_args__: Final = ( + "max", + "max_exp", + "max_10_exp", + "min", + "min_exp", + "min_10_exp", + "dig", + "mant_dig", + "epsilon", + "radix", + "rounds", + ) @property def max(self) -> float: ... # DBL_MAX @@ -247,8 +256,7 @@ hash_info: _hash_info @final @type_check_only class _hash_info(structseq[Any | int], tuple[int, int, int, int, int, str, int, int, int]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("width", "modulus", "inf", "nan", "imag", "algorithm", "hash_bits", "seed_bits", "cutoff") + __match_args__: Final = ("width", "modulus", "inf", "nan", "imag", "algorithm", "hash_bits", "seed_bits", "cutoff") @property def width(self) -> int: ... @@ -290,8 +298,7 @@ int_info: _int_info @final @type_check_only class _int_info(structseq[int], tuple[int, int, int, int]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("bits_per_digit", "sizeof_digit", "default_max_str_digits", "str_digits_check_threshold") + __match_args__: Final = ("bits_per_digit", "sizeof_digit", "default_max_str_digits", "str_digits_check_threshold") @property def bits_per_digit(self) -> int: ... @@ -309,8 +316,7 @@ _ThreadInfoLock: TypeAlias = Literal["semaphore", "mutex+cond"] | None @final @type_check_only class _thread_info(_UninstantiableStructseq, tuple[_ThreadInfoName, _ThreadInfoLock, str | None]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("name", "lock", "version") + __match_args__: Final = ("name", "lock", "version") @property def name(self) -> _ThreadInfoName: ... @@ -326,8 +332,7 @@ _ReleaseLevel: TypeAlias = Literal["alpha", "beta", "candidate", "final"] @final @type_check_only class _version_info(_UninstantiableStructseq, tuple[int, int, int, _ReleaseLevel, int]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("major", "minor", "micro", "releaselevel", "serial") + __match_args__: Final = ("major", "minor", "micro", "releaselevel", "serial") @property def major(self) -> int: ... @@ -385,6 +390,11 @@ if sys.platform != "win32": def getfilesystemencoding() -> LiteralString: ... def getfilesystemencodeerrors() -> LiteralString: ... + +if sys.version_info >= (3, 15): + def get_lazy_imports() -> _LazyImportMode: ... + def get_lazy_imports_filter() -> _LazyImportFilter | None: ... + def getrefcount(object: Any, /) -> int: ... def getrecursionlimit() -> int: ... def getsizeof(obj: object, default: int = ...) -> int: ... @@ -467,8 +477,7 @@ _AsyncgenHook: TypeAlias = Callable[[AsyncGenerator[Any, Any]], None] | None @final @type_check_only class _asyncgen_hooks(structseq[_AsyncgenHook], tuple[_AsyncgenHook, _AsyncgenHook]): - if sys.version_info >= (3, 10): - __match_args__: Final = ("firstiter", "finalizer") + __match_args__: Final = ("firstiter", "finalizer") @property def firstiter(self) -> _AsyncgenHook: ... @@ -496,6 +505,10 @@ def set_coroutine_origin_tracking_depth(depth: int) -> None: ... def set_int_max_str_digits(maxdigits: int) -> None: ... def get_int_max_str_digits() -> int: ... +if sys.version_info >= (3, 15): + def set_lazy_imports(mode: _LazyImportMode) -> None: ... + def set_lazy_imports_filter(filter: _LazyImportFilter | None) -> None: ... + if sys.version_info >= (3, 12): if sys.version_info >= (3, 13): def getunicodeinternedsize(*, _only_immortal: bool = False) -> int: ... @@ -518,3 +531,7 @@ if sys.version_info >= (3, 14): def is_remote_debug_enabled() -> bool: ... def remote_exec(pid: int, script: StrOrBytesPath) -> None: ... def _is_immortal(op: object, /) -> bool: ... + + from . import __jit + + _jit = __jit diff --git a/mypy/typeshed/stdlib/sys/__jit.pyi b/mypy/typeshed/stdlib/sys/__jit.pyi new file mode 100644 index 0000000000000..90fb65c1d9efe --- /dev/null +++ b/mypy/typeshed/stdlib/sys/__jit.pyi @@ -0,0 +1,11 @@ +# This py314+ module provides annotations for `sys._jit`. +# It's named `sys.__jit` in typeshed, +# because trying to import `sys._jit` will fail at runtime! +# At runtime, `sys._jit` has the unusual status +# of being a `types.ModuleType` instance that cannot be directly imported, +# (same as sys.monitoring) +# and exists in the `sys`-module namespace despite `sys` not being a package. + +def is_available() -> bool: ... +def is_enabled() -> bool: ... +def is_active() -> bool: ... diff --git a/mypy/typeshed/stdlib/sys/_monitoring.pyi b/mypy/typeshed/stdlib/sys/_monitoring.pyi index 83f1e7dd0f1df..b999d63f64709 100644 --- a/mypy/typeshed/stdlib/sys/_monitoring.pyi +++ b/mypy/typeshed/stdlib/sys/_monitoring.pyi @@ -1,8 +1,9 @@ # This py312+ module provides annotations for `sys.monitoring`. # It's named `sys._monitoring` in typeshed, # because trying to import `sys.monitoring` will fail at runtime! -# At runtime, `sys.monitoring` has the unique status +# At runtime, `sys.monitoring` has the unusual status # of being a `types.ModuleType` instance that cannot be directly imported, +# (same as sys._jit) # and exists in the `sys`-module namespace despite `sys` not being a package. import sys diff --git a/mypy/typeshed/stdlib/sysconfig.pyi b/mypy/typeshed/stdlib/sysconfig.pyi index 8de7ddc4255f2..cfa3fbaceb731 100644 --- a/mypy/typeshed/stdlib/sysconfig.pyi +++ b/mypy/typeshed/stdlib/sysconfig.pyi @@ -21,35 +21,37 @@ __all__ = [ def get_config_var(name: Literal["SO"]) -> Any: ... @overload def get_config_var(name: str) -> Any: ... + @overload def get_config_vars() -> dict[str, Any]: ... @overload def get_config_vars(arg: str, /, *args: str) -> list[Any]: ... -def get_scheme_names() -> tuple[str, ...]: ... -if sys.version_info >= (3, 10): - def get_default_scheme() -> LiteralString: ... - def get_preferred_scheme(key: Literal["prefix", "home", "user"]) -> LiteralString: ... - # Documented -- see https://docs.python.org/3/library/sysconfig.html#sysconfig._get_preferred_schemes - def _get_preferred_schemes() -> dict[Literal["prefix", "home", "user"], LiteralString]: ... +def get_scheme_names() -> tuple[str, ...]: ... +def get_default_scheme() -> LiteralString: ... +def get_preferred_scheme(key: Literal["prefix", "home", "user"]) -> LiteralString: ... +# Documented -- see https://docs.python.org/3/library/sysconfig.html#sysconfig._get_preferred_schemes +def _get_preferred_schemes() -> dict[Literal["prefix", "home", "user"], LiteralString]: ... def get_path_names() -> tuple[str, ...]: ... def get_path(name: str, scheme: str = ..., vars: dict[str, Any] | None = None, expand: bool = True) -> str: ... def get_paths(scheme: str = ..., vars: dict[str, Any] | None = None, expand: bool = True) -> dict[str, str]: ... def get_python_version() -> str: ... def get_platform() -> str: ... -if sys.version_info >= (3, 12): +if sys.version_info >= (3, 15): + def is_python_build() -> bool: ... +elif sys.version_info >= (3, 11): @overload def is_python_build() -> bool: ... @overload @deprecated("The `check_home` parameter is deprecated since Python 3.12; removed in Python 3.15.") def is_python_build(check_home: object = None) -> bool: ... - -elif sys.version_info >= (3, 11): - def is_python_build(check_home: object = None) -> bool: ... - else: + @overload + def is_python_build() -> bool: ... + @overload + @deprecated("The `check_home` parameter is deprecated since Python 3.12; removed in Python 3.15.") def is_python_build(check_home: bool = False) -> bool: ... def parse_config_h(fp: IO[Any], vars: dict[str, Any] | None = None) -> dict[str, Any]: ... diff --git a/mypy/typeshed/stdlib/syslog.pyi b/mypy/typeshed/stdlib/syslog.pyi index b639c28c7f2d7..0cb97dcd3ca7e 100644 --- a/mypy/typeshed/stdlib/syslog.pyi +++ b/mypy/typeshed/stdlib/syslog.pyi @@ -51,6 +51,7 @@ if sys.platform != "win32": def closelog() -> None: ... def openlog(ident: str = ..., logoption: int = 0, facility: int = ...) -> None: ... def setlogmask(maskpri: int, /) -> int: ... + @overload def syslog(priority: int, message: str) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi index 7d6bb341db314..6c55683fbaa37 100644 --- a/mypy/typeshed/stdlib/tarfile.pyi +++ b/mypy/typeshed/stdlib/tarfile.pyi @@ -6,8 +6,8 @@ from builtins import list as _list # aliases to avoid name clashes with fields from collections.abc import Callable, Iterable, Iterator, Mapping from gzip import _ReadableFileobj as _GzipReadableFileobj, _WritableFileobj as _GzipWritableFileobj from types import TracebackType -from typing import IO, ClassVar, Final, Literal, Protocol, overload, type_check_only -from typing_extensions import Self, TypeAlias, deprecated +from typing import IO, ClassVar, Final, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self, deprecated if sys.version_info >= (3, 14): from compression.zstd import ZstdDict @@ -134,6 +134,26 @@ class TarFile: extraction_filter: _FilterFunction | None if sys.version_info >= (3, 13): stream: bool + if sys.version_info >= (3, 15): + def __init__( + self, + name: StrOrBytesPath | None = None, + mode: Literal["r", "a", "w", "x"] = "r", + fileobj: _Fileobj | None = None, + format: int | None = None, + tarinfo: type[TarInfo] | None = None, + dereference: bool | None = None, + ignore_zeros: bool | None = None, + encoding: str | None = None, + errors: str = "surrogateescape", + pax_headers: Mapping[str, str] | None = None, + debug: Literal[0, 1, 2, 3] | None = None, # default 0 + errorlevel: Literal[0, 1, 2] | None = None, # default 1 + copybufsize: int | None = None, # undocumented + stream: bool = False, + mtime: float | None = None, + ) -> None: ... + elif sys.version_info >= (3, 13): def __init__( self, name: StrOrBytesPath | None = None, @@ -193,6 +213,7 @@ class TarFile: debug: Literal[0, 1, 2, 3] | None = None, # default 0 errorlevel: Literal[0, 1, 2] | None = None, # default 1 ) -> Self: ... + if sys.version_info >= (3, 14): @overload @classmethod @@ -495,6 +516,7 @@ class TarFile: errorlevel: Literal[0, 1, 2] | None = None, # default 1 compresslevel: int = 9, ) -> Self: ... + @classmethod def taropen( cls, @@ -512,6 +534,7 @@ class TarFile: debug: Literal[0, 1, 2, 3] | None = None, # default 0 errorlevel: Literal[0, 1, 2] | None = None, # default 1 ) -> Self: ... + @overload @classmethod def gzopen( @@ -548,6 +571,7 @@ class TarFile: debug: Literal[0, 1, 2, 3] | None = None, # default 0 errorlevel: Literal[0, 1, 2] | None = None, # default 1 ) -> Self: ... + @overload @classmethod def bz2open( @@ -584,6 +608,7 @@ class TarFile: debug: Literal[0, 1, 2, 3] | None = None, # default 0 errorlevel: Literal[0, 1, 2] | None = None, # default 1 ) -> Self: ... + @classmethod def xzopen( cls, @@ -785,24 +810,24 @@ class TarInfo: gname: str pax_headers: Mapping[str, str] def __init__(self, name: str = "") -> None: ... - if sys.version_info >= (3, 13): - @property - @deprecated("Deprecated since Python 3.13; will be removed in Python 3.16.") - def tarfile(self) -> TarFile | None: ... - @tarfile.setter - @deprecated("Deprecated since Python 3.13; will be removed in Python 3.16.") - def tarfile(self, tarfile: TarFile | None) -> None: ... - else: - tarfile: TarFile | None + + @property + @deprecated("Deprecated since Python 3.13; will be removed in Python 3.16.") + def tarfile(self) -> TarFile | None: ... + @tarfile.setter + @deprecated("Deprecated since Python 3.13; will be removed in Python 3.16.") + def tarfile(self, tarfile: TarFile | None) -> None: ... @classmethod def frombuf(cls, buf: bytes | bytearray, encoding: str, errors: str) -> Self: ... @classmethod def fromtarfile(cls, tarfile: TarFile) -> Self: ... + @property def linkpath(self) -> str: ... @linkpath.setter def linkpath(self, linkname: str) -> None: ... + def replace( self, *, diff --git a/mypy/typeshed/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi index 26491074ff71d..1df04a3d3667a 100644 --- a/mypy/typeshed/stdlib/tempfile.pyi +++ b/mypy/typeshed/stdlib/tempfile.pyi @@ -81,7 +81,6 @@ if sys.version_info >= (3, 12): errors: str | None = None, delete_on_close: bool = True, ) -> _TemporaryFileWrapper[Any]: ... - else: @overload def NamedTemporaryFile( @@ -249,18 +248,21 @@ class _TemporaryFileWrapper(IO[AnyStr]): def tell(self) -> int: ... def truncate(self, size: int | None = ...) -> int: ... def writable(self) -> bool: ... + @overload def write(self: _TemporaryFileWrapper[str], s: str, /) -> int: ... @overload def write(self: _TemporaryFileWrapper[bytes], s: ReadableBuffer, /) -> int: ... @overload def write(self, s: AnyStr, /) -> int: ... + @overload def writelines(self: _TemporaryFileWrapper[str], lines: Iterable[str]) -> None: ... @overload def writelines(self: _TemporaryFileWrapper[bytes], lines: Iterable[ReadableBuffer]) -> None: ... @overload def writelines(self, lines: Iterable[AnyStr]) -> None: ... + @property def closed(self) -> bool: ... @@ -277,6 +279,7 @@ class SpooledTemporaryFile(IO[AnyStr], _SpooledTemporaryFileBase): def encoding(self) -> str: ... # undocumented @property def newlines(self) -> str | tuple[str, ...] | None: ... # undocumented + # bytes needs to go first, as default mode is to open as bytes @overload def __init__( @@ -348,6 +351,7 @@ class SpooledTemporaryFile(IO[AnyStr], _SpooledTemporaryFileBase): dir: str | None = None, errors: str | None = None, ) -> None: ... + @property def errors(self) -> str | None: ... def rollover(self) -> None: ... @@ -384,12 +388,14 @@ class SpooledTemporaryFile(IO[AnyStr], _SpooledTemporaryFileBase): def write(self: SpooledTemporaryFile[bytes], s: ReadableBuffer) -> int: ... @overload def write(self, s: AnyStr) -> int: ... + @overload # type: ignore[override] def writelines(self: SpooledTemporaryFile[str], iterable: Iterable[str]) -> None: ... @overload def writelines(self: SpooledTemporaryFile[bytes], iterable: Iterable[ReadableBuffer]) -> None: ... @overload def writelines(self, iterable: Iterable[AnyStr]) -> None: ... + def __iter__(self) -> Iterator[AnyStr]: ... # type: ignore[override] # These exist at runtime only on 3.11+. def readable(self) -> bool: ... @@ -421,7 +427,7 @@ class TemporaryDirectory(Generic[AnyStr]): *, delete: bool = True, ) -> None: ... - elif sys.version_info >= (3, 10): + else: @overload def __init__( self: TemporaryDirectory[str], @@ -438,18 +444,6 @@ class TemporaryDirectory(Generic[AnyStr]): dir: BytesPath | None = None, ignore_cleanup_errors: bool = False, ) -> None: ... - else: - @overload - def __init__( - self: TemporaryDirectory[str], suffix: str | None = None, prefix: str | None = None, dir: StrPath | None = None - ) -> None: ... - @overload - def __init__( - self: TemporaryDirectory[bytes], - suffix: bytes | None = None, - prefix: bytes | None = None, - dir: BytesPath | None = None, - ) -> None: ... def cleanup(self) -> None: ... def __enter__(self) -> AnyStr: ... @@ -471,6 +465,7 @@ def mkstemp( def mkdtemp(suffix: str | None = None, prefix: str | None = None, dir: StrPath | None = None) -> str: ... @overload def mkdtemp(suffix: bytes | None = None, prefix: bytes | None = None, dir: BytesPath | None = None) -> bytes: ... + @deprecated("Deprecated since Python 2.3. Use `mkstemp()` or `NamedTemporaryFile(delete=False)` instead.") def mktemp(suffix: str = "", prefix: str = "tmp", dir: StrPath | None = None) -> str: ... def gettempdirb() -> bytes: ... diff --git a/mypy/typeshed/stdlib/termios.pyi b/mypy/typeshed/stdlib/termios.pyi index a35be5dfe740a..971c9ad46bf45 100644 --- a/mypy/typeshed/stdlib/termios.pyi +++ b/mypy/typeshed/stdlib/termios.pyi @@ -1,7 +1,6 @@ import sys from _typeshed import FileDescriptorLike -from typing import Any, Final -from typing_extensions import TypeAlias +from typing import Any, Final, TypeAlias # Must be a list of length 7, containing 6 ints and a list of NCCS 1-character bytes or ints. _Attr: TypeAlias = list[int | list[bytes | int]] | list[int | list[bytes]] | list[int | list[int]] diff --git a/mypy/typeshed/stdlib/threading.pyi b/mypy/typeshed/stdlib/threading.pyi index 03c8865d3c0a4..6b51b424cee6d 100644 --- a/mypy/typeshed/stdlib/threading.pyi +++ b/mypy/typeshed/stdlib/threading.pyi @@ -2,11 +2,11 @@ import _thread import sys from _thread import _ExceptHookArgs, get_native_id as get_native_id from _typeshed import ProfileFunction, TraceFunction -from collections.abc import Callable, Iterable, Mapping +from collections.abc import Callable, Iterable, Iterator, Mapping from contextvars import Context from types import TracebackType from typing import Any, Final, TypeVar, final -from typing_extensions import deprecated +from typing_extensions import Self, deprecated _T = TypeVar("_T") @@ -29,6 +29,8 @@ __all__ = [ "Timer", "ThreadError", "ExceptHookArgs", + "getprofile", + "gettrace", "setprofile", "settrace", "local", @@ -37,12 +39,12 @@ __all__ = [ "get_native_id", ] -if sys.version_info >= (3, 10): - __all__ += ["getprofile", "gettrace"] - if sys.version_info >= (3, 12): __all__ += ["setprofile_all_threads", "settrace_all_threads"] +if sys.version_info >= (3, 15): + __all__ += ["concurrent_tee", "serialize_iterator", "synchronized_iterator"] + _profile_hook: ProfileFunction | None def active_count() -> int: ... @@ -61,9 +63,21 @@ if sys.version_info >= (3, 12): def setprofile_all_threads(func: ProfileFunction | None) -> None: ... def settrace_all_threads(func: TraceFunction | None) -> None: ... -if sys.version_info >= (3, 10): - def gettrace() -> TraceFunction | None: ... - def getprofile() -> ProfileFunction | None: ... +def gettrace() -> TraceFunction | None: ... +def getprofile() -> ProfileFunction | None: ... + +if sys.version_info >= (3, 15): + @final + class serialize_iterator(Iterator[_T]): + def __init__(self, iterable: Iterable[_T]) -> None: ... + def __iter__(self) -> Self: ... + def __next__(self) -> _T: ... + def send(self, value: Any, /) -> _T: ... + def throw(self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ...) -> _T: ... + def close(self) -> None: ... + + def synchronized_iterator(func: Callable[..., Iterable[_T]]) -> Callable[..., Iterator[_T]]: ... + def concurrent_tee(iterable: Iterable[_T], n: int = 2) -> tuple[Iterator[_T], ...]: ... def stack_size(size: int = 0, /) -> int: ... @@ -173,8 +187,7 @@ class Event: def wait(self, timeout: float | None = None) -> bool: ... excepthook: Callable[[_ExceptHookArgs], object] -if sys.version_info >= (3, 10): - __excepthook__: Callable[[_ExceptHookArgs], object] +__excepthook__: Callable[[_ExceptHookArgs], object] ExceptHookArgs = _ExceptHookArgs class Timer(Thread): diff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi index d0853792b636d..9b5344b326cec 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -1,7 +1,6 @@ import sys from _typeshed import structseq -from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, Union, final, type_check_only -from typing_extensions import TypeAlias +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] @@ -47,8 +46,7 @@ if sys.platform == "linux": # https://github.com/python/typeshed/pull/6560#discussion_r767162532 @final class struct_time(structseq[Any | int], _TimeTuple): - if sys.version_info >= (3, 10): - __match_args__: Final = ("tm_year", "tm_mon", "tm_mday", "tm_hour", "tm_min", "tm_sec", "tm_wday", "tm_yday", "tm_isdst") + __match_args__: Final = ("tm_year", "tm_mon", "tm_mday", "tm_hour", "tm_min", "tm_sec", "tm_wday", "tm_yday", "tm_isdst") @property def tm_year(self) -> int: ... diff --git a/mypy/typeshed/stdlib/timeit.pyi b/mypy/typeshed/stdlib/timeit.pyi index 61935815f68b2..cc2b2027a8201 100644 --- a/mypy/typeshed/stdlib/timeit.pyi +++ b/mypy/typeshed/stdlib/timeit.pyi @@ -1,7 +1,7 @@ +import sys import time from collections.abc import Callable, Sequence -from typing import IO, Any -from typing_extensions import TypeAlias +from typing import IO, Any, TypeAlias __all__ = ["Timer", "timeit", "repeat", "default_timer"] @@ -21,7 +21,12 @@ class Timer: def print_exc(self, file: IO[str] | None = None) -> None: ... def timeit(self, number: int = 1000000) -> float: ... def repeat(self, repeat: int = 5, number: int = 1000000) -> list[float]: ... - def autorange(self, callback: Callable[[int, float], object] | None = None) -> tuple[int, float]: ... + if sys.version_info >= (3, 15): + def autorange( + self, callback: Callable[[int, float], object] | None = None, target_time: float = 0.2 + ) -> tuple[int, float]: ... + else: + def autorange(self, callback: Callable[[int, float], object] | None = None) -> tuple[int, float]: ... def timeit( stmt: _Stmt = "pass", diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index a70ef2351f3d4..9f1c346cdc194 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -5,8 +5,22 @@ from collections.abc import Callable, Iterable, Mapping, Sequence from tkinter.constants import * from tkinter.font import _FontDescription from types import GenericAlias, TracebackType -from typing import Any, ClassVar, Final, Generic, Literal, NamedTuple, Protocol, TypedDict, TypeVar, overload, type_check_only -from typing_extensions import TypeAlias, TypeVarTuple, Unpack, deprecated, disjoint_base +from typing import ( + Any, + ClassVar, + Final, + Generic, + Literal, + NamedTuple, + ParamSpec, + Protocol, + TypeAlias, + TypedDict, + TypeVar, + overload, + type_check_only, +) +from typing_extensions import TypeVarTuple, Unpack, deprecated, disjoint_base if sys.version_info >= (3, 11): from enum import StrEnum @@ -299,6 +313,9 @@ class Event(Generic[_W_co]): type: EventType widget: _W_co delta: int + if sys.version_info >= (3, 15): + detail: str + user_data: str if sys.version_info >= (3, 14): def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @@ -312,21 +329,14 @@ class Variable: def trace_add(self, mode: Literal["array", "read", "write", "unset"], callback: Callable[[str, str, str], object]) -> str: ... def trace_remove(self, mode: Literal["array", "read", "write", "unset"], cbname: str) -> None: ... def trace_info(self) -> list[tuple[tuple[Literal["array", "read", "write", "unset"], ...], str]]: ... - if sys.version_info >= (3, 14): - @deprecated("Deprecated since Python 3.14. Use `trace_add()` instead.") - def trace(self, mode, callback) -> str: ... - @deprecated("Deprecated since Python 3.14. Use `trace_add()` instead.") - def trace_variable(self, mode, callback) -> str: ... - @deprecated("Deprecated since Python 3.14. Use `trace_remove()` instead.") - def trace_vdelete(self, mode, cbname) -> None: ... - @deprecated("Deprecated since Python 3.14. Use `trace_info()` instead.") - def trace_vinfo(self) -> list[Incomplete]: ... - else: - def trace(self, mode, callback) -> str: ... - def trace_variable(self, mode, callback) -> str: ... - def trace_vdelete(self, mode, cbname) -> None: ... - def trace_vinfo(self) -> list[Incomplete]: ... - + @deprecated("Deprecated since Python 3.14. Use `trace_add()` instead.") + def trace(self, mode, callback) -> str: ... + @deprecated("Deprecated since Python 3.14. Use `trace_add()` instead.") + def trace_variable(self, mode, callback) -> str: ... + @deprecated("Deprecated since Python 3.14. Use `trace_remove()` instead.") + def trace_vdelete(self, mode, cbname) -> None: ... + @deprecated("Deprecated since Python 3.14. Use `trace_info()` instead.") + def trace_vinfo(self) -> list[Incomplete]: ... def __eq__(self, other: object) -> bool: ... def __del__(self) -> None: ... __hash__: ClassVar[None] # type: ignore[assignment] @@ -363,6 +373,7 @@ getdouble = float def getboolean(s) -> bool: ... _Ts = TypeVarTuple("_Ts") +_P = ParamSpec("_P") @type_check_only class _GridIndexInfo(TypedDict, total=False): @@ -402,11 +413,19 @@ class Misc: def tk_focusFollowsMouse(self) -> None: ... def tk_focusNext(self) -> Misc | None: ... def tk_focusPrev(self) -> Misc | None: ... - # .after() can be called without the "func" argument, but it is basically never what you want. - # It behaves like time.sleep() and freezes the GUI app. - def after(self, ms: int | Literal["idle"], func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> str: ... - # after_idle is essentially partialmethod(after, "idle") - def after_idle(self, func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> str: ... + if sys.version_info >= (3, 14): + # .after() can be called without the "func" argument, but it is basically never what you want. + # It behaves like time.sleep() and freezes the GUI app. + def after(self, ms: int | Literal["idle"], func: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> str: ... + # after_idle is essentially partialmethod(after, "idle") + def after_idle(self, func: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> str: ... + else: + # .after() can be called without the "func" argument, but it is basically never what you want. + # It behaves like time.sleep() and freezes the GUI app. + def after(self, ms: int | Literal["idle"], func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> str: ... + # after_idle is essentially partialmethod(after, "idle") + def after_idle(self, func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> str: ... + def after_cancel(self, id: str) -> None: ... if sys.version_info >= (3, 13): def after_info(self, id: str | None = None) -> tuple[str, ...]: ... @@ -508,10 +527,12 @@ class Misc: def winfo_y(self) -> int: ... def update(self) -> None: ... def update_idletasks(self) -> None: ... + @overload def bindtags(self, tagList: None = None) -> tuple[str, ...]: ... @overload def bindtags(self, tagList: list[str] | tuple[str, ...]) -> None: ... + # bind with isinstance(func, str) doesn't return anything, but all other # binds do. The default value of func is not str. @overload @@ -525,6 +546,7 @@ class Misc: def bind(self, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... @overload def bind(self, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + # There's no way to know what type of widget bind_all and bind_class # callbacks will get, so those are Misc. @overload @@ -538,6 +560,7 @@ class Misc: def bind_all(self, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... @overload def bind_all(self, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + @overload def bind_class( self, @@ -550,6 +573,7 @@ class Misc: def bind_class(self, className: str, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... @overload def bind_class(self, className: str, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + def unbind(self, sequence: str, funcid: str | None = None) -> None: ... def unbind_all(self, sequence: str) -> None: ... def unbind_class(self, className: str, sequence: str) -> None: ... @@ -562,13 +586,16 @@ class Misc: self, func: Callable[..., object], subst: Callable[..., Sequence[Any]] | None = None, needcleanup: int = 1 ) -> str: ... def keys(self) -> list[str]: ... + @overload def pack_propagate(self, flag: bool) -> bool | None: ... @overload def pack_propagate(self) -> None: ... + propagate = pack_propagate def grid_anchor(self, anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] | None = None) -> None: ... anchor = grid_anchor + @overload def grid_bbox( self, column: None = None, row: None = None, col2: None = None, row2: None = None @@ -577,6 +604,7 @@ class Misc: def grid_bbox(self, column: int, row: int, col2: None = None, row2: None = None) -> tuple[int, int, int, int] | None: ... @overload def grid_bbox(self, column: int, row: int, col2: int, row2: int) -> tuple[int, int, int, int] | None: ... + bbox = grid_bbox def grid_columnconfigure( self, @@ -601,10 +629,12 @@ class Misc: columnconfigure = grid_columnconfigure rowconfigure = grid_rowconfigure def grid_location(self, x: float | str, y: float | str) -> tuple[int, int]: ... + @overload def grid_propagate(self, flag: bool) -> None: ... @overload def grid_propagate(self) -> bool: ... + def grid_size(self) -> tuple[int, int]: ... size = grid_size # Widget because Toplevel or Tk is never a slave @@ -612,6 +642,12 @@ class Misc: def grid_slaves(self, row: int | None = None, column: int | None = None) -> list[Widget]: ... def place_slaves(self) -> list[Widget]: ... slaves = pack_slaves + if sys.version_info >= (3, 15): + def pack_content(self) -> list[Widget]: ... + def grid_content(self, row: int | None = None, column: int | None = None) -> list[Widget]: ... + def place_content(self) -> list[Widget]: ... + content = pack_content + def event_add(self, virtual: str, *sequences: str) -> None: ... def event_delete(self, virtual: str, *sequences: str) -> None: ... def event_generate( @@ -654,8 +690,7 @@ class Misc: def __getitem__(self, key: str) -> Any: ... def cget(self, key: str) -> Any: ... def configure(self, cnf: Any = None) -> Any: ... - # TODO: config is an alias of configure, but adding that here creates - # conflict with the type of config in the subclasses. See #13149 + config = configure class CallWrapper: func: Incomplete @@ -669,7 +704,9 @@ class XView: def xview(self) -> tuple[float, float]: ... @overload def xview(self, *args) -> None: ... + def xview_moveto(self, fraction: float) -> None: ... + @overload def xview_scroll(self, number: int, what: Literal["units", "pages"]) -> None: ... @overload @@ -680,7 +717,9 @@ class YView: def yview(self) -> tuple[float, float]: ... @overload def yview(self, *args) -> None: ... + def yview_moveto(self, fraction: float) -> None: ... + @overload def yview_scroll(self, number: int, what: Literal["units", "pages"]) -> None: ... @overload @@ -725,13 +764,13 @@ class Wm: def wm_aspect( self, minNumer: None = None, minDenom: None = None, maxNumer: None = None, maxDenom: None = None ) -> tuple[int, int, int, int] | None: ... + aspect = wm_aspect if sys.version_info >= (3, 13): @overload def wm_attributes(self, *, return_python_dict: Literal[False] = False) -> tuple[Any, ...]: ... @overload def wm_attributes(self, *, return_python_dict: Literal[True]) -> _WmAttributes: ... - else: @overload def wm_attributes(self) -> tuple[Any, ...]: ... @@ -831,6 +870,7 @@ class Wm: @overload def wm_attributes(self, option: str, value, /, *__other_option_value_pairs: Any) -> Literal[""]: ... + if sys.version_info >= (3, 13): if sys.platform == "darwin": @overload @@ -867,12 +907,14 @@ class Wm: attributes = wm_attributes def wm_client(self, name: str | None = None) -> str: ... client = wm_client + @overload def wm_colormapwindows(self) -> list[Misc]: ... @overload def wm_colormapwindows(self, wlist: list[Misc] | tuple[Misc, ...], /) -> None: ... @overload def wm_colormapwindows(self, first_wlist_item: Misc, /, *other_wlist_items: Misc) -> None: ... + colormapwindows = wm_colormapwindows def wm_command(self, value: str | None = None) -> str: ... command = wm_command @@ -885,10 +927,12 @@ class Wm: forget = wm_forget def wm_frame(self) -> str: ... frame = wm_frame + @overload def wm_geometry(self, newGeometry: None = None) -> str: ... @overload def wm_geometry(self, newGeometry: str) -> None: ... + geometry = wm_geometry def wm_grid(self, baseWidth=None, baseHeight=None, widthInc=None, heightInc=None): ... grid = wm_grid @@ -910,51 +954,67 @@ class Wm: iconwindow = wm_iconwindow def wm_manage(self, widget) -> None: ... manage = wm_manage + @overload def wm_maxsize(self, width: None = None, height: None = None) -> tuple[int, int]: ... @overload def wm_maxsize(self, width: int, height: int) -> None: ... + maxsize = wm_maxsize + @overload def wm_minsize(self, width: None = None, height: None = None) -> tuple[int, int]: ... @overload def wm_minsize(self, width: int, height: int) -> None: ... + minsize = wm_minsize + @overload def wm_overrideredirect(self, boolean: None = None) -> bool | None: ... # returns True or None @overload def wm_overrideredirect(self, boolean: bool) -> None: ... + overrideredirect = wm_overrideredirect def wm_positionfrom(self, who: Literal["program", "user"] | None = None) -> Literal["", "program", "user"]: ... positionfrom = wm_positionfrom + @overload def wm_protocol(self, name: str, func: Callable[[], object] | str) -> None: ... @overload def wm_protocol(self, name: str, func: None = None) -> str: ... @overload def wm_protocol(self, name: None = None, func: None = None) -> tuple[str, ...]: ... + protocol = wm_protocol + @overload def wm_resizable(self, width: None = None, height: None = None) -> tuple[bool, bool]: ... @overload def wm_resizable(self, width: bool, height: bool) -> None: ... + resizable = wm_resizable def wm_sizefrom(self, who: Literal["program", "user"] | None = None) -> Literal["", "program", "user"]: ... sizefrom = wm_sizefrom + @overload def wm_state(self, newstate: None = None) -> str: ... @overload def wm_state(self, newstate: str) -> None: ... + state = wm_state + @overload def wm_title(self, string: None = None) -> str: ... @overload def wm_title(self, string: str) -> None: ... + title = wm_title + @overload def wm_transient(self, master: None = None) -> _tkinter.Tcl_Obj: ... @overload def wm_transient(self, master: Wm | _tkinter.Tcl_Obj) -> None: ... + transient = wm_transient def wm_withdraw(self) -> None: ... withdraw = wm_withdraw @@ -973,6 +1033,7 @@ class Tk(Misc, Wm): sync: bool = False, use: str | None = None, ) -> None: ... + # Keep this in sync with ttktheme.ThemedTk. See issue #13858 @overload def configure( @@ -998,6 +1059,7 @@ class Tk(Misc, Wm): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def destroy(self) -> None: ... def readprofile(self, baseName: str, className: str) -> None: ... @@ -1033,6 +1095,7 @@ class Tk(Misc, Wm): def splitlist(self, arg, /) -> tuple[Incomplete, ...]: ... def unsetvar(self, *args, **kwargs): ... + if sys.version_info >= (3, 14): @overload def wantobjects(self) -> Literal[0, 1]: ... @@ -1042,6 +1105,7 @@ class Tk(Misc, Wm): @overload def wantobjects(self, wantobjects: Literal[0, 1] | bool, /) -> None: ... + def willdispatch(self) -> None: ... def Tcl(screenName: str | None = None, baseName: str | None = None, className: str = "Tk", useTk: bool = False) -> Tk: ... @@ -1222,6 +1286,7 @@ class Toplevel(BaseWidget, Wm): visual: str | tuple[str, int] = "", width: float | str = 0, ) -> None: ... + @overload def configure( self, @@ -1246,6 +1311,7 @@ class Toplevel(BaseWidget, Wm): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Button(Widget): @@ -1297,6 +1363,7 @@ class Button(Widget): width: float | str = 0, wraplength: float | str = 0, ) -> None: ... + @overload def configure( self, @@ -1341,6 +1408,7 @@ class Button(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def flash(self) -> None: ... def invoke(self) -> Any: ... @@ -1386,6 +1454,7 @@ class Canvas(Widget, XView, YView): yscrollcommand: str | Callable[[float, float], object] = "", yscrollincrement: float | str = 0, ) -> None: ... + @overload def configure( self, @@ -1424,6 +1493,7 @@ class Canvas(Widget, XView, YView): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def addtag(self, *args): ... # internal method def addtag_above(self, newtag: str, tagOrId: str | int) -> None: ... @@ -1447,6 +1517,7 @@ class Canvas(Widget, XView, YView): def find_withtag(self, tagOrId: str | int) -> tuple[int, ...]: ... # Incompatible with Misc.bbox(), tkinter violates LSP def bbox(self, *args: str | int) -> tuple[int, int, int, int]: ... # type: ignore[override] + @overload def tag_bind( self, @@ -1461,21 +1532,25 @@ class Canvas(Widget, XView, YView): ) -> None: ... @overload def tag_bind(self, tagOrId: str | int, *, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + def tag_unbind(self, tagOrId: str | int, sequence: str, funcid: str | None = None) -> None: ... def canvasx(self, screenx, gridspacing=None): ... def canvasy(self, screeny, gridspacing=None): ... + @overload def coords(self, tagOrId: str | int, /) -> list[float]: ... @overload def coords(self, tagOrId: str | int, args: list[int] | list[float] | tuple[float, ...], /) -> None: ... @overload def coords(self, tagOrId: str | int, x1: float, y1: float, /, *args: float) -> None: ... + # create_foo() methods accept coords as a list or tuple, or as separate arguments. # Lists and tuples can be flat as in [1, 2, 3, 4], or nested as in [(1, 2), (3, 4)]. # Keyword arguments should be the same in all overloads of each method. def create_arc(self, *args, **kw) -> int: ... def create_bitmap(self, *args, **kw) -> int: ... def create_image(self, *args, **kw) -> int: ... + @overload def create_line( self, @@ -1574,6 +1649,7 @@ class Canvas(Widget, XView, YView): tags: str | list[str] | tuple[str, ...] = ..., width: float | str = ..., ) -> int: ... + @overload def create_oval( self, @@ -1675,6 +1751,7 @@ class Canvas(Widget, XView, YView): tags: str | list[str] | tuple[str, ...] = ..., width: float | str = ..., ) -> int: ... + @overload def create_polygon( self, @@ -1785,6 +1862,7 @@ class Canvas(Widget, XView, YView): tags: str | list[str] | tuple[str, ...] = ..., width: float | str = ..., ) -> int: ... + @overload def create_rectangle( self, @@ -1886,6 +1964,7 @@ class Canvas(Widget, XView, YView): tags: str | list[str] | tuple[str, ...] = ..., width: float | str = ..., ) -> int: ... + @overload def create_text( self, @@ -1931,6 +2010,7 @@ class Canvas(Widget, XView, YView): text: float | str = ..., width: float | str = ..., ) -> int: ... + @overload def create_window( self, @@ -1958,12 +2038,15 @@ class Canvas(Widget, XView, YView): width: float | str = ..., window: Widget = ..., ) -> int: ... + def dchars(self, *args) -> None: ... def delete(self, *tagsOrCanvasIds: str | int) -> None: ... + @overload def dtag(self, tag: str, tag_to_delete: str | None = ..., /) -> None: ... @overload def dtag(self, id: int, tag_to_delete: str, /) -> None: ... + def focus(self, *args): ... def gettags(self, tagOrId: str | int, /) -> tuple[str, ...]: ... def icursor(self, *args) -> None: ... @@ -2058,6 +2141,7 @@ class Checkbutton(Widget): width: float | str = 0, wraplength: float | str = 0, ) -> None: ... + @overload def configure( self, @@ -2108,6 +2192,7 @@ class Checkbutton(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def deselect(self) -> None: ... def flash(self) -> None: ... @@ -2160,6 +2245,7 @@ class Entry(Widget, XView): width: int = 20, xscrollcommand: str | Callable[[float, float], object] = "", ) -> None: ... + @overload def configure( self, @@ -2205,6 +2291,7 @@ class Entry(Widget, XView): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def delete(self, first: str | int, last: str | int | None = None) -> None: ... def get(self) -> str: ... @@ -2253,6 +2340,7 @@ class Frame(Widget): visual: str | tuple[str, int] = "", # can't be changed with configure() width: float | str = 0, ) -> None: ... + @overload def configure( self, @@ -2276,6 +2364,7 @@ class Frame(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Label(Widget): @@ -2317,6 +2406,7 @@ class Label(Widget): width: float | str = 0, wraplength: float | str = 0, ) -> None: ... + @overload def configure( self, @@ -2356,6 +2446,7 @@ class Label(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Listbox(Widget, XView, YView): @@ -2410,6 +2501,7 @@ class Listbox(Widget, XView, YView): xscrollcommand: str | Callable[[float, float], object] = "", yscrollcommand: str | Callable[[float, float], object] = "", ) -> None: ... + @overload def configure( self, @@ -2447,6 +2539,7 @@ class Listbox(Widget, XView, YView): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def activate(self, index: str | int) -> None: ... def bbox(self, index: str | int) -> tuple[int, int, int, int] | None: ... # type: ignore[override] @@ -2504,6 +2597,7 @@ class Menu(Widget): title: str = "", type: Literal["menubar", "tearoff", "normal"] = "normal", ) -> None: ... + @overload def configure( self, @@ -2533,6 +2627,7 @@ class Menu(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def tk_popup(self, x: int, y: int, entry: str | int = "") -> None: ... def activate(self, index: str | int) -> None: ... @@ -2784,6 +2879,7 @@ class Menubutton(Widget): width: float | str = 0, wraplength: float | str = 0, ) -> None: ... + @overload def configure( self, @@ -2826,6 +2922,7 @@ class Menubutton(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Message(Widget): @@ -2859,6 +2956,7 @@ class Message(Widget): # there's width but no height width: float | str = 0, ) -> None: ... + @overload def configure( self, @@ -2889,6 +2987,7 @@ class Message(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Radiobutton(Widget): @@ -2940,6 +3039,7 @@ class Radiobutton(Widget): width: float | str = 0, wraplength: float | str = 0, ) -> None: ... + @overload def configure( self, @@ -2989,6 +3089,7 @@ class Radiobutton(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def deselect(self) -> None: ... def flash(self) -> None: ... @@ -3038,6 +3139,7 @@ class Scale(Widget): variable: IntVar | DoubleVar = ..., width: float | str = 15, ) -> None: ... + @overload def configure( self, @@ -3080,6 +3182,7 @@ class Scale(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def get(self) -> float: ... def set(self, value) -> None: ... @@ -3119,6 +3222,7 @@ class Scrollbar(Widget): troughcolor: str = ..., width: float | str = ..., ) -> None: ... + @overload def configure( self, @@ -3148,6 +3252,7 @@ class Scrollbar(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def activate(self, index=None): ... def delta(self, deltax: int, deltay: int) -> float: ... @@ -3217,6 +3322,7 @@ class Text(Widget, XView, YView): xscrollcommand: str | Callable[[float, float], object] = "", yscrollcommand: str | Callable[[float, float], object] = "", ) -> None: ... + @overload def configure( self, @@ -3270,6 +3376,7 @@ class Text(Widget, XView, YView): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def bbox(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> tuple[int, int, int, int] | None: ... # type: ignore[override] def compare( @@ -3278,6 +3385,7 @@ class Text(Widget, XView, YView): op: Literal["<", "<=", "==", ">=", ">", "!="], index2: str | float | _tkinter.Tcl_Obj | Widget, ) -> bool: ... + if sys.version_info >= (3, 13): @overload def count( @@ -3461,10 +3569,12 @@ class Text(Widget, XView, YView): def debug(self, boolean: None = None) -> bool: ... @overload def debug(self, boolean: bool) -> None: ... + def delete( self, index1: str | float | _tkinter.Tcl_Obj | Widget, index2: str | float | _tkinter.Tcl_Obj | Widget | None = None ) -> None: ... def dlineinfo(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> tuple[int, int, int, int, int] | None: ... + @overload def dump( self, @@ -3507,11 +3617,14 @@ class Text(Widget, XView, YView): text: bool = ..., window: bool = ..., ) -> None: ... + def edit(self, *args): ... # docstring says "Internal method" + @overload def edit_modified(self, arg: None = None) -> bool: ... # actually returns Literal[0, 1] @overload def edit_modified(self, arg: bool) -> None: ... # actually returns empty string + def edit_redo(self) -> None: ... # actually returns empty string def edit_reset(self) -> None: ... # actually returns empty string def edit_separator(self) -> None: ... # actually returns empty string @@ -3519,6 +3632,7 @@ class Text(Widget, XView, YView): def get( self, index1: str | float | _tkinter.Tcl_Obj | Widget, index2: str | float | _tkinter.Tcl_Obj | Widget | None = None ) -> str: ... + @overload def image_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["image", "name"]) -> str: ... @overload @@ -3529,6 +3643,7 @@ class Text(Widget, XView, YView): ) -> Literal["baseline", "bottom", "center", "top"]: ... @overload def image_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: str) -> Any: ... + @overload def image_configure( self, index: str | float | _tkinter.Tcl_Obj | Widget, cnf: str @@ -3545,6 +3660,7 @@ class Text(Widget, XView, YView): padx: float | str = ..., pady: float | str = ..., ) -> dict[str, tuple[str, str, str, str, str | int]] | None: ... + def image_create( self, index: str | float | _tkinter.Tcl_Obj | Widget, @@ -3561,10 +3677,12 @@ class Text(Widget, XView, YView): def insert( self, index: str | float | _tkinter.Tcl_Obj | Widget, chars: str, *args: str | list[str] | tuple[str, ...] ) -> None: ... + @overload def mark_gravity(self, markName: str, direction: None = None) -> Literal["left", "right"]: ... @overload def mark_gravity(self, markName: str, direction: Literal["left", "right"]) -> None: ... # actually returns empty string + def mark_names(self) -> tuple[str, ...]: ... def mark_set(self, markName: str, index: str | float | _tkinter.Tcl_Obj | Widget) -> None: ... def mark_unset(self, *markNames: str) -> None: ... @@ -3582,23 +3700,60 @@ class Text(Widget, XView, YView): ) -> None: ... def scan_mark(self, x: int, y: int) -> None: ... def scan_dragto(self, x: int, y: int) -> None: ... - def search( - self, - pattern: str, - index: str | float | _tkinter.Tcl_Obj | Widget, - stopindex: str | float | _tkinter.Tcl_Obj | Widget | None = None, - forwards: bool | None = None, - backwards: bool | None = None, - exact: bool | None = None, - regexp: bool | None = None, - nocase: bool | None = None, - count: Variable | None = None, - elide: bool | None = None, - ) -> str: ... # returns empty string for not found + if sys.version_info >= (3, 15): + def search( + self, + pattern: str, + index: str | float | _tkinter.Tcl_Obj | Widget, + stopindex: str | float | _tkinter.Tcl_Obj | Widget | None = None, + forwards: bool | None = None, + backwards: bool | None = None, + exact: bool | None = None, + regexp: bool | None = None, + nocase: bool | None = None, + count: Variable | None = None, + elide: bool | None = None, + *, + nolinestop: bool | None = None, + strictlimits: bool | None = None, + ) -> str: ... # returns empty string for not found + def search_all( + self, + pattern: str, + index: str | float | _tkinter.Tcl_Obj | Widget, + stopindex: str | float | _tkinter.Tcl_Obj | Widget | None = None, + *, + forwards: bool | None = None, + backwards: bool | None = None, + exact: bool | None = None, + regexp: bool | None = None, + nocase: bool | None = None, + count: Variable | None = None, + elide: bool | None = None, + nolinestop: bool | None = None, + overlap: bool | None = None, + strictlimits: bool | None = None, + ) -> tuple[_tkinter.Tcl_Obj, ...]: ... + else: + def search( + self, + pattern: str, + index: str | float | _tkinter.Tcl_Obj | Widget, + stopindex: str | float | _tkinter.Tcl_Obj | Widget | None = None, + forwards: bool | None = None, + backwards: bool | None = None, + exact: bool | None = None, + regexp: bool | None = None, + nocase: bool | None = None, + count: Variable | None = None, + elide: bool | None = None, + ) -> str: ... # returns empty string for not found + def see(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> None: ... def tag_add( self, tagName: str, index1: str | float | _tkinter.Tcl_Obj | Widget, *args: str | float | _tkinter.Tcl_Obj | Widget ) -> None: ... + # tag_bind stuff is very similar to Canvas @overload def tag_bind( @@ -3610,9 +3765,11 @@ class Text(Widget, XView, YView): ) -> str: ... @overload def tag_bind(self, tagName: str, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = None) -> None: ... + def tag_unbind(self, tagName: str, sequence: str, funcid: str | None = None) -> None: ... # allowing any string for cget instead of just Literals because there's no other way to look up tag options def tag_cget(self, tagName: str, option: str): ... + @overload def tag_configure( self, @@ -3650,6 +3807,7 @@ class Text(Widget, XView, YView): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def tag_configure(self, tagName: str, cnf: str) -> tuple[str, str, str, Any, Any]: ... + tag_config = tag_configure def tag_delete(self, first_tag_name: str, /, *tagNames: str) -> None: ... # error if no tag names given def tag_lower(self, tagName: str, belowThis: str | None = None) -> None: ... @@ -3675,6 +3833,7 @@ class Text(Widget, XView, YView): index1: str | float | _tkinter.Tcl_Obj | Widget, index2: str | float | _tkinter.Tcl_Obj | Widget | None = None, ) -> None: ... + @overload def window_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["padx", "pady"]) -> int: ... @overload @@ -3689,6 +3848,7 @@ class Text(Widget, XView, YView): def window_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal["create", "window"]) -> str: ... @overload def window_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: str) -> Any: ... + @overload def window_configure( self, index: str | float | _tkinter.Tcl_Obj | Widget, cnf: str @@ -3706,6 +3866,7 @@ class Text(Widget, XView, YView): stretch: bool | Literal[0, 1] = ..., window: Misc | str = ..., ) -> dict[str, tuple[str, str, str, str, str | int]] | None: ... + window_config = window_configure def window_create( self, @@ -3729,16 +3890,27 @@ class _setit: # manual page: tk_optionMenu class OptionMenu(Menubutton): menuname: Incomplete - def __init__( - # differs from other widgets - self, - master: Misc | None, - variable: StringVar, - value: str, - *values: str, - # kwarg only from now on - command: Callable[[StringVar], object] | None = ..., - ) -> None: ... + if sys.version_info >= (3, 14): + def __init__( + # differs from other widgets + self, + master: Misc | None, + variable: StringVar, + value: str, + *values: str, + command: Callable[[StringVar], object] | None = ..., + name: str | None = None, + ) -> None: ... + else: + def __init__( + # differs from other widgets + self, + master: Misc | None, + variable: StringVar, + value: str, + *values: str, + command: Callable[[StringVar], object] | None = ..., + ) -> None: ... # configure, config, cget are inherited from Menubutton # destroy and __getitem__ are overridden, signature does not change @@ -3860,6 +4032,7 @@ class PhotoImage(Image, _PhotoImageLike): background: str | None = None, grayscale: bool = False, ) -> None: ... + @overload def data( self, format: str, *, from_coords: Iterable[int] | None = None, background: str | None = None, grayscale: bool = False @@ -3960,6 +4133,7 @@ class Spinbox(Widget, XView): wrap: bool = False, xscrollcommand: str | Callable[[float, float], object] = "", ) -> None: ... + @overload def configure( self, @@ -4018,6 +4192,7 @@ class Spinbox(Widget, XView): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def bbox(self, index) -> tuple[int, int, int, int] | None: ... # type: ignore[override] def delete(self, first, last=None) -> Literal[""]: ... @@ -4074,6 +4249,7 @@ class LabelFrame(Widget): visual: str | tuple[str, int] = "", # can't be changed with configure() width: float | str = 0, ) -> None: ... + @overload def configure( self, @@ -4103,6 +4279,7 @@ class LabelFrame(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class PanedWindow(Widget): @@ -4134,6 +4311,7 @@ class PanedWindow(Widget): showhandle: bool = False, width: float | str = "", ) -> None: ... + @overload def configure( self, @@ -4163,6 +4341,7 @@ class PanedWindow(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def add(self, child: Widget, **kw) -> None: ... def remove(self, child) -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/font.pyi b/mypy/typeshed/stdlib/tkinter/font.pyi index 327ba7a2432e0..d9e0b13155909 100644 --- a/mypy/typeshed/stdlib/tkinter/font.pyi +++ b/mypy/typeshed/stdlib/tkinter/font.pyi @@ -1,9 +1,8 @@ import _tkinter import itertools -import sys import tkinter -from typing import Any, ClassVar, Final, Literal, TypedDict, overload, type_check_only -from typing_extensions import TypeAlias, Unpack +from typing import Any, ClassVar, Final, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Unpack __all__ = ["NORMAL", "ROMAN", "BOLD", "ITALIC", "nametofont", "Font", "families", "names"] @@ -61,6 +60,7 @@ class Font: ) -> None: ... __hash__: ClassVar[None] # type: ignore[assignment] def __setitem__(self, key: str, value: Any) -> None: ... + @overload def cget(self, option: Literal["family"]) -> str: ... @overload @@ -73,7 +73,9 @@ class Font: def cget(self, option: Literal["underline", "overstrike"]) -> bool: ... @overload def cget(self, option: str) -> Any: ... + __getitem__ = cget + @overload def actual(self, option: Literal["family"], displayof: tkinter.Misc | None = None) -> str: ... @overload @@ -88,6 +90,7 @@ class Font: def actual(self, option: None, displayof: tkinter.Misc | None = None) -> _FontDict: ... @overload def actual(self, *, displayof: tkinter.Misc | None = None) -> _FontDict: ... + def config( self, *, @@ -100,21 +103,18 @@ class Font: ) -> _FontDict | None: ... configure = config def copy(self) -> Font: ... + @overload def metrics(self, option: Literal["ascent", "descent", "linespace"], /, *, displayof: tkinter.Misc | None = ...) -> int: ... @overload def metrics(self, option: Literal["fixed"], /, *, displayof: tkinter.Misc | None = ...) -> bool: ... @overload def metrics(self, *, displayof: tkinter.Misc | None = ...) -> _MetricsDict: ... + def measure(self, text: str, displayof: tkinter.Misc | None = None) -> int: ... def __eq__(self, other: object) -> bool: ... def __del__(self) -> None: ... def families(root: tkinter.Misc | None = None, displayof: tkinter.Misc | None = None) -> tuple[str, ...]: ... def names(root: tkinter.Misc | None = None) -> tuple[str, ...]: ... - -if sys.version_info >= (3, 10): - def nametofont(name: str, root: tkinter.Misc | None = None) -> Font: ... - -else: - def nametofont(name: str) -> Font: ... +def nametofont(name: str, root: tkinter.Misc | None = None) -> Font: ... diff --git a/mypy/typeshed/stdlib/tkinter/simpledialog.pyi b/mypy/typeshed/stdlib/tkinter/simpledialog.pyi index 45dce21a6b1c3..6f66f0237b458 100644 --- a/mypy/typeshed/stdlib/tkinter/simpledialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/simpledialog.pyi @@ -1,5 +1,9 @@ +import sys from tkinter import Event, Frame, Misc, Toplevel +if sys.version_info >= (3, 15): + __all__ = ["SimpleDialog", "Dialog", "askinteger", "askfloat", "askstring"] + class Dialog(Toplevel): def __init__(self, parent: Misc | None, title: str | None = None) -> None: ... def body(self, master: Frame) -> Misc | None: ... diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index 0a6837201035c..06d2be13dc283 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -4,8 +4,8 @@ import tkinter from _typeshed import MaybeNone from collections.abc import Callable, Iterable, Sequence from tkinter.font import _FontDescription -from typing import Any, Literal, TypedDict, TypeVar, overload, type_check_only -from typing_extensions import Never, ParamSpec, TypeAlias, Unpack +from typing import Any, Literal, ParamSpec, TypeAlias, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Never, Unpack __all__ = [ "Button", @@ -123,6 +123,7 @@ class Style: master: tkinter.Misc tk: _tkinter.TkappType def __init__(self, master: tkinter.Misc | None = None) -> None: ... + # For these methods, values given vary between options. Returned values # seem to be str, but this might not always be the case. @overload @@ -131,15 +132,19 @@ class Style: def configure(self, style: str, query_opt: str, **kw: Any) -> Any: ... @overload def configure(self, style: str, query_opt: None = None, **kw: Any) -> None: ... + @overload def map(self, style: str, query_opt: str) -> _Statespec: ... @overload def map(self, style: str, query_opt: None = None, **kw: Iterable[_Statespec]) -> dict[str, _Statespec]: ... + def lookup(self, style: str, option: str, state: Iterable[str] | None = None, default: Any | None = None) -> Any: ... + @overload def layout(self, style: str, layoutspec: _LayoutSpec) -> list[Never]: ... # Always seems to return an empty list @overload def layout(self, style: str, layoutspec: None = None) -> _LayoutSpec: ... + @overload def element_create( self, @@ -203,6 +208,7 @@ class Style: def theme_create(self, themename: str, parent: str | None = None, settings: _ThemeSettings | None = None) -> None: ... def theme_settings(self, themename: str, settings: _ThemeSettings) -> None: ... def theme_names(self) -> tuple[str, ...]: ... + @overload def theme_use(self, themename: str) -> None: ... @overload @@ -211,12 +217,14 @@ class Style: class Widget(tkinter.Widget): def __init__(self, master: tkinter.Misc | None, widgetname: str | None, kw: dict[str, Any] | None = None) -> None: ... def identify(self, x: int, y: int) -> str: ... + @overload def instate(self, statespec: Sequence[str], callback: None = None) -> bool: ... @overload def instate( self, statespec: Sequence[str], callback: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs ) -> Literal[False] | _T: ... + def state(self, statespec: Sequence[str] | None = None) -> tuple[str, ...]: ... class Button(Widget): @@ -240,6 +248,7 @@ class Button(Widget): underline: int = -1, width: int | Literal[""] = "", ) -> None: ... + @overload def configure( self, @@ -261,6 +270,7 @@ class Button(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def invoke(self) -> Any: ... @@ -290,6 +300,7 @@ class Checkbutton(Widget): variable: tkinter.Variable = ..., width: int | Literal[""] = "", ) -> None: ... + @overload def configure( self, @@ -313,6 +324,7 @@ class Checkbutton(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def invoke(self) -> Any: ... @@ -341,6 +353,7 @@ class Entry(Widget, tkinter.Entry): width: int = 20, xscrollcommand: str | Callable[[float, float], object] = "", ) -> None: ... + @overload # type: ignore[override] def configure( self, @@ -365,6 +378,7 @@ class Entry(Widget, tkinter.Entry): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Entry().config is mypy error (don't know why) @overload # type: ignore[override] def config( @@ -390,6 +404,7 @@ class Entry(Widget, tkinter.Entry): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + def bbox(self, index) -> tuple[int, int, int, int]: ... # type: ignore[override] def identify(self, x: int, y: int) -> str: ... def validate(self): ... @@ -421,6 +436,7 @@ class Combobox(Entry): width: int = 20, xscrollcommand: str | Callable[[float, float], object] = ..., # undocumented ) -> None: ... + @overload # type: ignore[override] def configure( self, @@ -448,6 +464,7 @@ class Combobox(Entry): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Combobox().config is mypy error (don't know why) @overload # type: ignore[override] def config( @@ -476,6 +493,7 @@ class Combobox(Entry): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + def current(self, newindex: int | None = None) -> int: ... def set(self, value: Any) -> None: ... @@ -498,6 +516,7 @@ class Frame(Widget): takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", width: float | str = 0, ) -> None: ... + @overload def configure( self, @@ -515,6 +534,7 @@ class Frame(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Label(Widget): @@ -545,6 +565,7 @@ class Label(Widget): width: int | Literal[""] = "", wraplength: float | str = ..., ) -> None: ... + @overload def configure( self, @@ -573,6 +594,7 @@ class Label(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Labelframe(Widget): @@ -596,6 +618,7 @@ class Labelframe(Widget): underline: int = -1, width: float | str = 0, ) -> None: ... + @overload def configure( self, @@ -617,6 +640,7 @@ class Labelframe(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure LabelFrame = Labelframe @@ -642,6 +666,7 @@ class Menubutton(Widget): underline: int = -1, width: int | Literal[""] = "", ) -> None: ... + @overload def configure( self, @@ -663,6 +688,7 @@ class Menubutton(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Notebook(Widget): @@ -679,6 +705,7 @@ class Notebook(Widget): takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = ..., width: int = 0, ) -> None: ... + @overload def configure( self, @@ -693,6 +720,7 @@ class Notebook(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def add( self, @@ -734,6 +762,7 @@ class Panedwindow(Widget, tkinter.PanedWindow): width: int = 0, ) -> None: ... def add(self, child: tkinter.Widget, *, weight: int = ..., **kw) -> None: ... + @overload # type: ignore[override] def configure( self, @@ -747,6 +776,7 @@ class Panedwindow(Widget, tkinter.PanedWindow): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Panedwindow().config is mypy error (don't know why) @overload # type: ignore[override] def config( @@ -761,6 +791,7 @@ class Panedwindow(Widget, tkinter.PanedWindow): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + forget = tkinter.PanedWindow.forget def insert(self, pos, child, **kw) -> None: ... def pane(self, pane, option=None, **kw): ... @@ -786,6 +817,7 @@ class Progressbar(Widget): value: float = 0.0, variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> None: ... + @overload def configure( self, @@ -804,6 +836,7 @@ class Progressbar(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def start(self, interval: Literal["idle"] | int | None = None) -> None: ... def step(self, amount: float | None = None) -> None: ... @@ -831,6 +864,7 @@ class Radiobutton(Widget): variable: tkinter.Variable | Literal[""] = ..., width: int | Literal[""] = "", ) -> None: ... + @overload def configure( self, @@ -853,6 +887,7 @@ class Radiobutton(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def invoke(self) -> Any: ... @@ -876,6 +911,7 @@ class Scale(Widget, tkinter.Scale): # type: ignore[misc] value: float = 0, variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> None: ... + @overload # type: ignore[override] def configure( self, @@ -895,6 +931,7 @@ class Scale(Widget, tkinter.Scale): # type: ignore[misc] ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Scale().config is mypy error (don't know why) @overload # type: ignore[override] def config( @@ -915,6 +952,7 @@ class Scale(Widget, tkinter.Scale): # type: ignore[misc] ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + def get(self, x: int | None = None, y: int | None = None) -> float: ... # type ignore, because identify() methods of Widget and tkinter.Scale are incompatible @@ -931,6 +969,7 @@ class Scrollbar(Widget, tkinter.Scrollbar): # type: ignore[misc] style: str = "", takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", ) -> None: ... + @overload # type: ignore[override] def configure( self, @@ -944,6 +983,7 @@ class Scrollbar(Widget, tkinter.Scrollbar): # type: ignore[misc] ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + # config must be copy/pasted, otherwise ttk.Scrollbar().config is mypy error (don't know why) @overload # type: ignore[override] def config( @@ -971,6 +1011,7 @@ class Separator(Widget): style: str = "", takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", ) -> None: ... + @overload def configure( self, @@ -983,6 +1024,7 @@ class Separator(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Sizegrip(Widget): @@ -996,6 +1038,7 @@ class Sizegrip(Widget): style: str = "", takefocus: bool | Literal[0, 1, ""] | Callable[[str], bool | None] = "", ) -> None: ... + @overload def configure( self, @@ -1007,6 +1050,7 @@ class Sizegrip(Widget): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure class Spinbox(Entry): @@ -1040,6 +1084,7 @@ class Spinbox(Entry): wrap: bool = False, xscrollcommand: str | Callable[[float, float], object] = "", ) -> None: ... + @overload # type: ignore[override] def configure( self, @@ -1071,6 +1116,7 @@ class Spinbox(Entry): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure # type: ignore[assignment] def set(self, value: Any) -> None: ... @@ -1129,6 +1175,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): xscrollcommand: str | Callable[[float, float], object] = "", yscrollcommand: str | Callable[[float, float], object] = "", ) -> None: ... + @overload def configure( self, @@ -1148,10 +1195,12 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... + config = configure def bbox(self, item: str | int, column: str | int | None = None) -> tuple[int, int, int, int] | Literal[""]: ... # type: ignore[override] def get_children(self, item: str | int | None = None) -> tuple[str, ...]: ... def set_children(self, item: str | int, *newchildren: str | int) -> None: ... + @overload def column(self, column: str | int, option: Literal["width", "minwidth"]) -> int: ... @overload @@ -1174,13 +1223,16 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., # id is read-only ) -> _TreeviewColumnDict | None: ... + def delete(self, *items: str | int) -> None: ... def detach(self, *items: str | int) -> None: ... def exists(self, item: str | int) -> bool: ... + @overload # type: ignore[override] def focus(self, item: None = None) -> str: ... # can return empty string @overload def focus(self, item: str | int) -> Literal[""]: ... + @overload def heading(self, column: str | int, option: Literal["text"]) -> str: ... @overload @@ -1204,6 +1256,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): anchor: Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] = ..., command: str | Callable[[], object] = ..., ) -> None: ... + # Internal Method. Leave untyped: def identify(self, component, x, y): ... # type: ignore[override] def identify_row(self, y: int) -> str: ... @@ -1224,6 +1277,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): open: bool = ..., tags: str | list[str] | tuple[str, ...] = ..., ) -> str: ... + @overload def item(self, item: str | int, option: Literal["text"]) -> str: ... @overload @@ -1250,6 +1304,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): open: bool = ..., tags: str | list[str] | tuple[str, ...] = ..., ) -> None: ... + def move(self, item: str | int, parent: str, index: int | Literal["end"]) -> None: ... reattach = move def next(self, item: str | int) -> str: ... # returning empty string means last item @@ -1257,28 +1312,34 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def prev(self, item: str | int) -> str: ... # returning empty string means first item def see(self, item: str | int) -> None: ... def selection(self) -> tuple[str, ...]: ... + @overload def selection_set(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... @overload def selection_set(self, *items: str | int) -> None: ... + @overload def selection_add(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... @overload def selection_add(self, *items: str | int) -> None: ... + @overload def selection_remove(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... @overload def selection_remove(self, *items: str | int) -> None: ... + @overload def selection_toggle(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ... @overload def selection_toggle(self, *items: str | int) -> None: ... + @overload def set(self, item: str | int, column: None = None, value: None = None) -> dict[str, Any]: ... @overload def set(self, item: str | int, column: str | int, value: None = None) -> Any: ... @overload def set(self, item: str | int, column: str | int, value: Any) -> Literal[""]: ... + # There's no tag_unbind() or 'add' argument for whatever reason. # Also, it's 'callback' instead of 'func' here. @overload @@ -1289,6 +1350,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def tag_bind(self, tagname: str, sequence: str | None, callback: str) -> None: ... @overload def tag_bind(self, tagname: str, *, callback: str) -> None: ... + @overload def tag_configure(self, tagname: str, option: Literal["foreground", "background"]) -> str: ... @overload @@ -1307,6 +1369,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): font: _FontDescription = ..., image: tkinter._Image | str = ..., ) -> _TreeviewTagDict | MaybeNone: ... # can be None but annoying to check + @overload def tag_has(self, tagname: str, item: None = None) -> tuple[str, ...]: ... @overload @@ -1341,17 +1404,31 @@ class LabeledScale(Frame): value: Any class OptionMenu(Menubutton): - def __init__( - self, - master: tkinter.Misc | None, - variable: tkinter.StringVar, - default: str | None = None, - *values: str, - # rest of these are keyword-only because *args syntax used above - style: str = "", - direction: Literal["above", "below", "left", "right", "flush"] = "below", - command: Callable[[tkinter.StringVar], object] | None = None, - ) -> None: ... + if sys.version_info >= (3, 14): + def __init__( + self, + master: tkinter.Misc | None, + variable: tkinter.StringVar, + default: str | None = None, + *values: str, + # rest of these are keyword-only because *args syntax used above + style: str = "", + direction: Literal["above", "below", "left", "right", "flush"] = "below", + command: Callable[[tkinter.StringVar], object] | None = None, + name: str | None = None, + ) -> None: ... + else: + def __init__( + self, + master: tkinter.Misc | None, + variable: tkinter.StringVar, + default: str | None = None, + *values: str, + # rest of these are keyword-only because *args syntax used above + style: str = "", + direction: Literal["above", "below", "left", "right", "flush"] = "below", + command: Callable[[tkinter.StringVar], object] | None = None, + ) -> None: ... # configure, config, cget, destroy are inherited from Menubutton # destroy and __setitem__ are overridden, signature does not change def set_menu(self, default: str | None = None, *values: str) -> None: ... diff --git a/mypy/typeshed/stdlib/token.pyi b/mypy/typeshed/stdlib/token.pyi index fd1b10da1d12e..23b43250d60fe 100644 --- a/mypy/typeshed/stdlib/token.pyi +++ b/mypy/typeshed/stdlib/token.pyi @@ -57,6 +57,7 @@ __all__ = [ "SEMI", "SLASH", "SLASHEQUAL", + "SOFT_KEYWORD", "STAR", "STAREQUAL", "STRING", @@ -73,9 +74,6 @@ __all__ = [ if sys.version_info < (3, 13): __all__ += ["ASYNC", "AWAIT"] -if sys.version_info >= (3, 10): - __all__ += ["SOFT_KEYWORD"] - if sys.version_info >= (3, 12): __all__ += ["EXCLAMATION", "FSTRING_END", "FSTRING_MIDDLE", "FSTRING_START", "EXACT_TOKEN_TYPES"] @@ -150,8 +148,7 @@ TYPE_COMMENT: Final[int] TYPE_IGNORE: Final[int] COLONEQUAL: Final[int] EXACT_TOKEN_TYPES: Final[dict[str, int]] -if sys.version_info >= (3, 10): - SOFT_KEYWORD: Final[int] +SOFT_KEYWORD: Final[int] if sys.version_info >= (3, 12): EXCLAMATION: Final[int] diff --git a/mypy/typeshed/stdlib/tokenize.pyi b/mypy/typeshed/stdlib/tokenize.pyi index 0df8062d56891..0aa3947a178d5 100644 --- a/mypy/typeshed/stdlib/tokenize.pyi +++ b/mypy/typeshed/stdlib/tokenize.pyi @@ -3,8 +3,8 @@ from _typeshed import FileDescriptorOrPath from collections.abc import Callable, Generator, Iterable, Sequence from re import Pattern from token import * -from typing import Any, Final, NamedTuple, TextIO, type_check_only -from typing_extensions import TypeAlias, disjoint_base +from typing import Any, Final, NamedTuple, TextIO, TypeAlias, type_check_only +from typing_extensions import disjoint_base if sys.version_info < (3, 12): # Avoid double assignment to Final name by imports, which pyright objects to. @@ -71,6 +71,7 @@ __all__ = [ "SEMI", "SLASH", "SLASHEQUAL", + "SOFT_KEYWORD", "STAR", "STAREQUAL", "STRING", @@ -89,9 +90,6 @@ __all__ = [ if sys.version_info < (3, 13): __all__ += ["ASYNC", "AWAIT"] -if sys.version_info >= (3, 10): - __all__ += ["SOFT_KEYWORD"] - if sys.version_info >= (3, 12): __all__ += ["EXCLAMATION", "FSTRING_END", "FSTRING_MIDDLE", "FSTRING_START", "EXACT_TOKEN_TYPES"] diff --git a/mypy/typeshed/stdlib/tomllib.pyi b/mypy/typeshed/stdlib/tomllib.pyi index 4ff4097f8313a..7f6df1d9380ca 100644 --- a/mypy/typeshed/stdlib/tomllib.pyi +++ b/mypy/typeshed/stdlib/tomllib.pyi @@ -13,6 +13,7 @@ if sys.version_info >= (3, 14): pos: int lineno: int colno: int + @overload def __init__(self, msg: str, doc: str, pos: int) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/trace.pyi b/mypy/typeshed/stdlib/trace.pyi index 7e7cc1e9ac54a..708233efe3e6a 100644 --- a/mypy/typeshed/stdlib/trace.pyi +++ b/mypy/typeshed/stdlib/trace.pyi @@ -2,8 +2,7 @@ import sys import types from _typeshed import Incomplete, StrPath, TraceFunction from collections.abc import Callable, Iterable, Mapping, Sequence -from typing import Any, TypeVar -from typing_extensions import ParamSpec, TypeAlias +from typing import Any, ParamSpec, TypeAlias, TypeVar __all__ = ["Trace", "CoverageResults"] diff --git a/mypy/typeshed/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi index f9d88f25afd97..e5b410afdcbc0 100644 --- a/mypy/typeshed/stdlib/traceback.pyi +++ b/mypy/typeshed/stdlib/traceback.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import SupportsWrite, Unused from collections.abc import Generator, Iterable, Iterator, Mapping from types import FrameType, TracebackType -from typing import Any, ClassVar, Literal, SupportsIndex, overload -from typing_extensions import Self, TypeAlias, deprecated +from typing import Any, ClassVar, Literal, SupportsIndex, TypeAlias, overload +from typing_extensions import Self, deprecated __all__ = [ "extract_stack", @@ -34,49 +34,32 @@ _FrameSummaryTuple: TypeAlias = tuple[str, int, str, str | None] def print_tb(tb: TracebackType | None, limit: int | None = None, file: SupportsWrite[str] | None = None) -> None: ... -if sys.version_info >= (3, 10): - @overload - def print_exception( - exc: type[BaseException] | None, - /, - value: BaseException | None = ..., - tb: TracebackType | None = ..., - limit: int | None = None, - file: SupportsWrite[str] | None = None, - chain: bool = True, - ) -> None: ... - @overload - def print_exception( - exc: BaseException, /, *, limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True - ) -> None: ... - @overload - def format_exception( - exc: type[BaseException] | None, - /, - value: BaseException | None = ..., - tb: TracebackType | None = ..., - limit: int | None = None, - chain: bool = True, - ) -> list[str]: ... - @overload - def format_exception(exc: BaseException, /, *, limit: int | None = None, chain: bool = True) -> list[str]: ... +@overload +def print_exception( + exc: type[BaseException] | None, + /, + value: BaseException | None = ..., + tb: TracebackType | None = ..., + limit: int | None = None, + file: SupportsWrite[str] | None = None, + chain: bool = True, +) -> None: ... +@overload +def print_exception( + exc: BaseException, /, *, limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True +) -> None: ... -else: - def print_exception( - etype: type[BaseException] | None, - value: BaseException | None, - tb: TracebackType | None, - limit: int | None = None, - file: SupportsWrite[str] | None = None, - chain: bool = True, - ) -> None: ... - def format_exception( - etype: type[BaseException] | None, - value: BaseException | None, - tb: TracebackType | None, - limit: int | None = None, - chain: bool = True, - ) -> list[str]: ... +@overload +def format_exception( + exc: type[BaseException] | None, + /, + value: BaseException | None = ..., + tb: TracebackType | None = ..., + limit: int | None = None, + chain: bool = True, +) -> list[str]: ... +@overload +def format_exception(exc: BaseException, /, *, limit: int | None = None, chain: bool = True) -> list[str]: ... def print_exc(limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: ... def print_last(limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: ... @@ -91,16 +74,12 @@ if sys.version_info >= (3, 13): def format_exception_only(exc: BaseException | None, /, *, show_group: bool = False) -> list[str]: ... @overload def format_exception_only(exc: Unused, /, value: BaseException | None, *, show_group: bool = False) -> list[str]: ... - -elif sys.version_info >= (3, 10): +else: @overload def format_exception_only(exc: BaseException | None, /) -> list[str]: ... @overload def format_exception_only(exc: Unused, /, value: BaseException | None) -> list[str]: ... -else: - def format_exception_only(etype: type[BaseException] | None, value: BaseException | None) -> list[str]: ... - def format_exc(limit: int | None = None, chain: bool = True) -> str: ... def format_tb(tb: TracebackType | None, limit: int | None = None) -> list[str]: ... def format_stack(f: FrameType | None = None, limit: int | None = None) -> list[str]: ... @@ -126,12 +105,10 @@ class TracebackException: # These fields only exist for `SyntaxError`s, but there is no way to express that in the type system. filename: str lineno: str | None - if sys.version_info >= (3, 10): - end_lineno: str | None + end_lineno: str | None text: str offset: int - if sys.version_info >= (3, 10): - end_offset: int | None + end_offset: int | None msg: str if sys.version_info >= (3, 13): @@ -173,19 +150,6 @@ class TracebackException: max_group_depth: int = 10, _seen: set[int] | None = None, ) -> None: ... - elif sys.version_info >= (3, 10): - def __init__( - self, - exc_type: type[BaseException], - exc_value: BaseException, - exc_traceback: TracebackType | None, - *, - limit: int | None = None, - lookup_lines: bool = True, - capture_locals: bool = False, - compact: bool = False, - _seen: set[int] | None = None, - ) -> None: ... else: def __init__( self, @@ -196,6 +160,7 @@ class TracebackException: limit: int | None = None, lookup_lines: bool = True, capture_locals: bool = False, + compact: bool = False, _seen: set[int] | None = None, ) -> None: ... @@ -212,7 +177,7 @@ class TracebackException: max_group_width: int = 15, max_group_depth: int = 10, ) -> Self: ... - elif sys.version_info >= (3, 10): + else: @classmethod def from_exception( cls, @@ -223,11 +188,6 @@ class TracebackException: capture_locals: bool = False, compact: bool = False, ) -> Self: ... - else: - @classmethod - def from_exception( - cls, exc: BaseException, *, limit: int | None = None, lookup_lines: bool = True, capture_locals: bool = False - ) -> Self: ... def __eq__(self, other: object) -> bool: ... __hash__: ClassVar[None] # type: ignore[assignment] @@ -296,6 +256,7 @@ class FrameSummary: locals: dict[str, str] | None @property def line(self) -> str | None: ... + @overload def __getitem__(self, pos: Literal[0]) -> str: ... @overload @@ -308,6 +269,7 @@ class FrameSummary: def __getitem__(self, pos: SupportsIndex) -> Any: ... @overload def __getitem__(self, pos: slice[SupportsIndex | None]) -> tuple[Any, ...]: ... + def __iter__(self) -> Iterator[Any]: ... def __eq__(self, other: object) -> bool: ... def __len__(self) -> Literal[4]: ... diff --git a/mypy/typeshed/stdlib/tracemalloc.pyi b/mypy/typeshed/stdlib/tracemalloc.pyi index 2a7ee0051af9c..e56aa19240fda 100644 --- a/mypy/typeshed/stdlib/tracemalloc.pyi +++ b/mypy/typeshed/stdlib/tracemalloc.pyi @@ -1,8 +1,7 @@ import sys from _tracemalloc import * from collections.abc import Sequence -from typing import Any, SupportsIndex, overload -from typing_extensions import TypeAlias +from typing import Any, SupportsIndex, TypeAlias, overload def get_object_traceback(obj: object) -> Traceback | None: ... def take_snapshot() -> Snapshot: ... @@ -92,10 +91,12 @@ class Traceback(Sequence[Frame]): def total_nframe(self) -> int | None: ... def __init__(self, frames: Sequence[_FrameTuple], total_nframe: int | None = None) -> None: ... def format(self, limit: int | None = None, most_recent_first: bool = False) -> list[str]: ... + @overload def __getitem__(self, index: SupportsIndex) -> Frame: ... @overload def __getitem__(self, index: slice[SupportsIndex | None]) -> Sequence[Frame]: ... + def __contains__(self, frame: Frame) -> bool: ... # type: ignore[override] def __len__(self) -> int: ... def __eq__(self, other: object) -> bool: ... diff --git a/mypy/typeshed/stdlib/tty.pyi b/mypy/typeshed/stdlib/tty.pyi index ca3f0013b20ec..a0478335a3f32 100644 --- a/mypy/typeshed/stdlib/tty.pyi +++ b/mypy/typeshed/stdlib/tty.pyi @@ -1,7 +1,6 @@ import sys import termios -from typing import IO, Final -from typing_extensions import TypeAlias +from typing import IO, Final, TypeAlias if sys.platform != "win32": __all__ = ["setraw", "setcbreak"] diff --git a/mypy/typeshed/stdlib/turtle.pyi b/mypy/typeshed/stdlib/turtle.pyi index b5f536d0e28e5..b1f5198a89c06 100644 --- a/mypy/typeshed/stdlib/turtle.pyi +++ b/mypy/typeshed/stdlib/turtle.pyi @@ -3,8 +3,8 @@ from _typeshed import StrPath from collections.abc import Callable, Generator, Sequence from contextlib import contextmanager from tkinter import Canvas, Frame, Misc, PhotoImage, Scrollbar -from typing import Any, ClassVar, Literal, TypedDict, overload, type_check_only -from typing_extensions import Self, TypeAlias, deprecated, disjoint_base +from typing import Any, ClassVar, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Self, deprecated, disjoint_base __all__ = [ "ScrolledCanvas", @@ -167,10 +167,12 @@ if sys.version_info >= (3, 12): class Vec2D(tuple[float, float]): def __new__(cls, x: float, y: float) -> Self: ... def __add__(self, other: tuple[float, float]) -> Vec2D: ... # type: ignore[override] + @overload # type: ignore[override] def __mul__(self, other: Vec2D) -> float: ... @overload def __mul__(self, other: float) -> Vec2D: ... + def __rmul__(self, other: float) -> Vec2D: ... # type: ignore[override] def __sub__(self, other: tuple[float, float]) -> Vec2D: ... def __neg__(self) -> Vec2D: ... @@ -182,10 +184,12 @@ else: class Vec2D(tuple[float, float]): def __new__(cls, x: float, y: float) -> Self: ... def __add__(self, other: tuple[float, float]) -> Vec2D: ... # type: ignore[override] + @overload # type: ignore[override] def __mul__(self, other: Vec2D) -> float: ... @overload def __mul__(self, other: float) -> Vec2D: ... + def __rmul__(self, other: float) -> Vec2D: ... # type: ignore[override] def __sub__(self, other: tuple[float, float]) -> Vec2D: ... def __neg__(self) -> Vec2D: ... @@ -231,32 +235,40 @@ class TurtleScreen(TurtleScreenBase): self, cv: Canvas, mode: Literal["standard", "logo", "world"] = "standard", colormode: float = 1.0, delay: int = 10 ) -> None: ... def clear(self) -> None: ... + @overload def mode(self, mode: None = None) -> str: ... @overload def mode(self, mode: Literal["standard", "logo", "world"]) -> None: ... + def setworldcoordinates(self, llx: float, lly: float, urx: float, ury: float) -> None: ... def register_shape(self, name: str, shape: _PolygonCoords | Shape | None = None) -> None: ... + @overload def colormode(self, cmode: None = None) -> float: ... @overload def colormode(self, cmode: float) -> None: ... + def reset(self) -> None: ... def turtles(self) -> list[Turtle]: ... + @overload def bgcolor(self) -> _AnyColor: ... @overload def bgcolor(self, color: _Color) -> None: ... @overload def bgcolor(self, r: float, g: float, b: float) -> None: ... + @overload def tracer(self, n: None = None) -> int: ... @overload def tracer(self, n: int, delay: int | None = None) -> None: ... + @overload def delay(self, delay: None = None) -> int: ... @overload def delay(self, delay: int) -> None: ... + if sys.version_info >= (3, 14): @contextmanager def no_animation(self) -> Generator[None]: ... @@ -270,15 +282,18 @@ class TurtleScreen(TurtleScreenBase): def onkey(self, fun: Callable[[], object], key: str) -> None: ... def listen(self, xdummy: float | None = None, ydummy: float | None = None) -> None: ... def ontimer(self, fun: Callable[[], object], t: int = 0) -> None: ... + @overload def bgpic(self, picname: None = None) -> str: ... @overload def bgpic(self, picname: str) -> None: ... + @overload def screensize(self, canvwidth: None = None, canvheight: None = None, bg: None = None) -> tuple[int, int]: ... # Looks like if self.cv is not a ScrolledCanvas, this could return a tuple as well @overload def screensize(self, canvwidth: int, canvheight: int, bg: _Color | None = None) -> None: ... + if sys.version_info >= (3, 14): def save(self, filename: StrPath, *, overwrite: bool = False) -> None: ... onscreenclick = onclick @@ -307,21 +322,26 @@ class TNavigator: def pos(self) -> Vec2D: ... def xcor(self) -> float: ... def ycor(self) -> float: ... + @overload def goto(self, x: tuple[float, float], y: None = None) -> None: ... @overload def goto(self, x: float, y: float) -> None: ... + def home(self) -> None: ... def setx(self, x: float) -> None: ... def sety(self, y: float) -> None: ... + @overload def distance(self, x: TNavigator | tuple[float, float], y: None = None) -> float: ... @overload def distance(self, x: float, y: float) -> float: ... + @overload def towards(self, x: TNavigator | tuple[float, float], y: None = None) -> float: ... @overload def towards(self, x: float, y: float) -> float: ... + def heading(self) -> float: ... def setheading(self, to_angle: float) -> None: ... def circle(self, radius: float, extent: float | None = None, steps: int | None = None) -> None: ... @@ -338,33 +358,40 @@ class TNavigator: class TPen: def __init__(self, resizemode: Literal["auto", "user", "noresize"] = "noresize") -> None: ... + @overload def resizemode(self, rmode: None = None) -> str: ... @overload def resizemode(self, rmode: Literal["auto", "user", "noresize"]) -> None: ... + @overload def pensize(self, width: None = None) -> int: ... @overload def pensize(self, width: int) -> None: ... + def penup(self) -> None: ... def pendown(self) -> None: ... def isdown(self) -> bool: ... + @overload def speed(self, speed: None = None) -> int: ... @overload def speed(self, speed: _Speed) -> None: ... + @overload def pencolor(self) -> _AnyColor: ... @overload def pencolor(self, color: _Color) -> None: ... @overload def pencolor(self, r: float, g: float, b: float) -> None: ... + @overload def fillcolor(self) -> _AnyColor: ... @overload def fillcolor(self, color: _Color) -> None: ... @overload def fillcolor(self, r: float, g: float, b: float) -> None: ... + @overload def color(self) -> tuple[_AnyColor, _AnyColor]: ... @overload @@ -373,12 +400,14 @@ class TPen: def color(self, r: float, g: float, b: float) -> None: ... @overload def color(self, color1: _Color, color2: _Color) -> None: ... + if sys.version_info >= (3, 12): def teleport(self, x: float | None = None, y: float | None = None, *, fill_gap: bool = False) -> None: ... def showturtle(self) -> None: ... def hideturtle(self) -> None: ... def isvisible(self) -> bool: ... + # Note: signatures 1 and 2 overlap unsafely when no arguments are provided @overload def pen(self) -> _PenState: ... @@ -398,6 +427,7 @@ class TPen: outline: int = ..., tilt: float = ..., ) -> None: ... + width = pensize up = penup pu = penup @@ -421,10 +451,12 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods def undobufferentries(self) -> int: ... def clear(self) -> None: ... def clone(self) -> Self: ... + @overload def shape(self, name: None = None) -> str: ... @overload def shape(self, name: str) -> None: ... + # Unsafely overlaps when no arguments are provided @overload def shapesize(self) -> tuple[float, float, float]: ... @@ -432,10 +464,12 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods def shapesize( self, stretch_wid: float | None = None, stretch_len: float | None = None, outline: float | None = None ) -> None: ... + @overload def shearfactor(self, shear: None = None) -> float: ... @overload def shearfactor(self, shear: float) -> None: ... + # Unsafely overlaps when no arguments are provided @overload def shapetransform(self) -> tuple[float, float, float, float]: ... @@ -443,6 +477,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods def shapetransform( self, t11: float | None = None, t12: float | None = None, t21: float | None = None, t22: float | None = None ) -> None: ... + def get_shapepoly(self) -> _PolygonCoords | None: ... if sys.version_info < (3, 13): @@ -453,6 +488,7 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods def tiltangle(self, angle: None = None) -> float: ... @overload def tiltangle(self, angle: float) -> None: ... + def tilt(self, angle: float) -> None: ... # Can return either 'int' or Tuple[int, ...] based on if the stamp is # a compound stamp or not. So, as per the "no Union return" policy, @@ -467,12 +503,14 @@ class RawTurtle(TPen, TNavigator): # type: ignore[misc] # Conflicting methods def begin_fill(self) -> None: ... def end_fill(self) -> None: ... + @overload def dot(self, size: int | _Color | None = None) -> None: ... @overload def dot(self, size: int | None, color: _Color, /) -> None: ... @overload def dot(self, size: int | None, r: float, g: float, b: float, /) -> None: ... + def write( self, arg: object, move: bool = False, align: str = "left", font: tuple[str, int, str] = ("Arial", 8, "normal") ) -> None: ... @@ -525,28 +563,35 @@ def numinput( # Functions copied from TurtleScreen: def clear() -> None: ... + @overload def mode(mode: None = None) -> str: ... @overload def mode(mode: Literal["standard", "logo", "world"]) -> None: ... + def setworldcoordinates(llx: float, lly: float, urx: float, ury: float) -> None: ... def register_shape(name: str, shape: _PolygonCoords | Shape | None = None) -> None: ... + @overload def colormode(cmode: None = None) -> float: ... @overload def colormode(cmode: float) -> None: ... + def reset() -> None: ... def turtles() -> list[Turtle]: ... + @overload def bgcolor() -> _AnyColor: ... @overload def bgcolor(color: _Color) -> None: ... @overload def bgcolor(r: float, g: float, b: float) -> None: ... + @overload def tracer(n: None = None) -> int: ... @overload def tracer(n: int, delay: int | None = None) -> None: ... + @overload def delay(delay: None = None) -> int: ... @overload @@ -565,10 +610,12 @@ def onclick(fun: Callable[[float, float], object], btn: int = 1, add: bool | Non def onkey(fun: Callable[[], object], key: str) -> None: ... def listen(xdummy: float | None = None, ydummy: float | None = None) -> None: ... def ontimer(fun: Callable[[], object], t: int = 0) -> None: ... + @overload def bgpic(picname: None = None) -> str: ... @overload def bgpic(picname: str) -> None: ... + @overload def screensize(canvwidth: None = None, canvheight: None = None, bg: None = None) -> tuple[int, int]: ... @overload @@ -605,21 +652,26 @@ def left(angle: float) -> None: ... def pos() -> Vec2D: ... def xcor() -> float: ... def ycor() -> float: ... + @overload def goto(x: tuple[float, float], y: None = None) -> None: ... @overload def goto(x: float, y: float) -> None: ... + def home() -> None: ... def setx(x: float) -> None: ... def sety(y: float) -> None: ... + @overload def distance(x: TNavigator | tuple[float, float], y: None = None) -> float: ... @overload def distance(x: float, y: float) -> float: ... + @overload def towards(x: TNavigator | tuple[float, float], y: None = None) -> float: ... @overload def towards(x: float, y: float) -> float: ... + def heading() -> float: ... def setheading(to_angle: float) -> None: ... def circle(radius: float, extent: float | None = None, steps: int | None = None) -> None: ... @@ -639,29 +691,35 @@ seth = setheading def resizemode(rmode: None = None) -> str: ... @overload def resizemode(rmode: Literal["auto", "user", "noresize"]) -> None: ... + @overload def pensize(width: None = None) -> int: ... @overload def pensize(width: int) -> None: ... + def penup() -> None: ... def pendown() -> None: ... def isdown() -> bool: ... + @overload def speed(speed: None = None) -> int: ... @overload def speed(speed: _Speed) -> None: ... + @overload def pencolor() -> _AnyColor: ... @overload def pencolor(color: _Color) -> None: ... @overload def pencolor(r: float, g: float, b: float) -> None: ... + @overload def fillcolor() -> _AnyColor: ... @overload def fillcolor(color: _Color) -> None: ... @overload def fillcolor(r: float, g: float, b: float) -> None: ... + @overload def color() -> tuple[_AnyColor, _AnyColor]: ... @overload @@ -670,6 +728,7 @@ def color(color: _Color) -> None: ... def color(r: float, g: float, b: float) -> None: ... @overload def color(color1: _Color, color2: _Color) -> None: ... + def showturtle() -> None: ... def hideturtle() -> None: ... def isvisible() -> bool: ... @@ -705,6 +764,7 @@ ht = hideturtle def setundobuffer(size: int | None) -> None: ... def undobufferentries() -> int: ... + @overload def shape(name: None = None) -> str: ... @overload @@ -718,6 +778,7 @@ if sys.version_info >= (3, 12): def shapesize() -> tuple[float, float, float]: ... @overload def shapesize(stretch_wid: float | None = None, stretch_len: float | None = None, outline: float | None = None) -> None: ... + @overload def shearfactor(shear: None = None) -> float: ... @overload @@ -730,6 +791,7 @@ def shapetransform() -> tuple[float, float, float, float]: ... def shapetransform( t11: float | None = None, t12: float | None = None, t21: float | None = None, t22: float | None = None ) -> None: ... + def get_shapepoly() -> _PolygonCoords | None: ... if sys.version_info < (3, 13): @@ -740,6 +802,7 @@ if sys.version_info < (3, 13): def tiltangle(angle: None = None) -> float: ... @overload def tiltangle(angle: float) -> None: ... + def tilt(angle: float) -> None: ... # Can return either 'int' or Tuple[int, ...] based on if the stamp is @@ -756,12 +819,14 @@ if sys.version_info >= (3, 14): def begin_fill() -> None: ... def end_fill() -> None: ... + @overload def dot(size: int | _Color | None = None) -> None: ... @overload def dot(size: int | None, color: _Color, /) -> None: ... @overload def dot(size: int | None, r: float, g: float, b: float, /) -> None: ... + def write(arg: object, move: bool = False, align: str = "left", font: tuple[str, int, str] = ("Arial", 8, "normal")) -> None: ... if sys.version_info >= (3, 14): diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index e26c9447d2f75..b9771ffc72dad 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -12,12 +12,13 @@ from collections.abc import ( Iterator, KeysView, Mapping, + MutableMapping, MutableSequence, ValuesView, ) from importlib.machinery import ModuleSpec -from typing import Any, ClassVar, Literal, TypeVar, final, overload -from typing_extensions import ParamSpec, Self, TypeAliasType, TypeVarTuple, deprecated, disjoint_base +from typing import Any, ClassVar, Literal, ParamSpec, TypeVar, final, overload +from typing_extensions import Self, TypeAliasType, TypeVarTuple, deprecated, disjoint_base if sys.version_info >= (3, 14): from _typeshed import AnnotateFunc @@ -50,17 +51,21 @@ __all__ = [ "resolve_bases", "CellType", "GenericAlias", + "EllipsisType", + "NoneType", + "NotImplementedType", + "UnionType", ] -if sys.version_info >= (3, 10): - __all__ += ["EllipsisType", "NoneType", "NotImplementedType", "UnionType"] - if sys.version_info >= (3, 12): __all__ += ["get_original_bases"] if sys.version_info >= (3, 13): __all__ += ["CapsuleType"] +if sys.version_info >= (3, 15): + __all__ += ["FrameLocalsProxyType", "LazyImportType"] + # Note, all classes "defined" here require special handling. _T1 = TypeVar("_T1") @@ -84,9 +89,8 @@ class FunctionType: if sys.version_info >= (3, 14): __annotate__: AnnotateFunc | None __kwdefaults__: dict[str, Any] | None - if sys.version_info >= (3, 10): - @property - def __builtins__(self) -> dict[str, Any]: ... + @property + def __builtins__(self) -> dict[str, Any]: ... if sys.version_info >= (3, 12): __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] @@ -112,6 +116,7 @@ class FunctionType: ) -> Self: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + @overload def __get__(self, instance: None, owner: type, /) -> FunctionType: ... @overload @@ -149,22 +154,18 @@ class CodeType: def co_name(self) -> str: ... @property def co_firstlineno(self) -> int: ... - if sys.version_info >= (3, 10): + if sys.version_info < (3, 15): @property @deprecated("Deprecated since Python 3.10; will be removed in Python 3.15. Use `CodeType.co_lines()` instead.") def co_lnotab(self) -> bytes: ... - else: - @property - def co_lnotab(self) -> bytes: ... @property def co_freevars(self) -> tuple[str, ...]: ... @property def co_cellvars(self) -> tuple[str, ...]: ... - if sys.version_info >= (3, 10): - @property - def co_linetable(self) -> bytes: ... - def co_lines(self) -> Iterator[tuple[int, int, int | None]]: ... + @property + def co_linetable(self) -> bytes: ... + def co_lines(self) -> Iterator[tuple[int, int, int | None]]: ... if sys.version_info >= (3, 11): @property def co_exceptiontable(self) -> bytes: ... @@ -197,27 +198,6 @@ class CodeType: cellvars: tuple[str, ...] = ..., /, ) -> Self: ... - elif sys.version_info >= (3, 10): - def __new__( - cls, - argcount: int, - posonlyargcount: int, - kwonlyargcount: int, - nlocals: int, - stacksize: int, - flags: int, - codestring: bytes, - constants: tuple[object, ...], - names: tuple[str, ...], - varnames: tuple[str, ...], - filename: str, - name: str, - firstlineno: int, - linetable: bytes, - freevars: tuple[str, ...] = ..., - cellvars: tuple[str, ...] = ..., - /, - ) -> Self: ... else: def __new__( cls, @@ -234,7 +214,7 @@ class CodeType: filename: str, name: str, firstlineno: int, - lnotab: bytes, + linetable: bytes, freevars: tuple[str, ...] = ..., cellvars: tuple[str, ...] = ..., /, @@ -262,27 +242,6 @@ class CodeType: co_linetable: bytes = ..., co_exceptiontable: bytes = ..., ) -> Self: ... - elif sys.version_info >= (3, 10): - def replace( - self, - *, - co_argcount: int = -1, - co_posonlyargcount: int = -1, - co_kwonlyargcount: int = -1, - co_nlocals: int = -1, - co_stacksize: int = -1, - co_flags: int = -1, - co_firstlineno: int = -1, - co_code: bytes = ..., - co_consts: tuple[object, ...] = ..., - co_names: tuple[str, ...] = ..., - co_varnames: tuple[str, ...] = ..., - co_freevars: tuple[str, ...] = ..., - co_cellvars: tuple[str, ...] = ..., - co_filename: str = ..., - co_name: str = ..., - co_linetable: bytes = ..., - ) -> Self: ... else: def replace( self, @@ -302,7 +261,7 @@ class CodeType: co_cellvars: tuple[str, ...] = ..., co_filename: str = ..., co_name: str = ..., - co_lnotab: bytes = ..., + co_linetable: bytes = ..., ) -> Self: ... if sys.version_info >= (3, 13): @@ -320,12 +279,14 @@ class MappingProxyType(Mapping[_KT_co, _VT_co]): # type: ignore[type-var] # py def keys(self) -> KeysView[_KT_co]: ... def values(self) -> ValuesView[_VT_co]: ... def items(self) -> ItemsView[_KT_co, _VT_co]: ... + @overload def get(self, key: _KT_co, /) -> _VT_co | None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter @overload def get(self, key: _KT_co, default: _VT_co, /) -> _VT_co: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter @overload def get(self, key: _KT_co, default: _T2, /) -> _VT_co | _T2: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... def __reversed__(self) -> Iterator[_KT_co]: ... def __or__(self, value: Mapping[_T1, _T2], /) -> dict[_KT_co | _T1, _VT_co | _T2]: ... @@ -408,17 +369,22 @@ class GeneratorType(Generator[_YieldT_co, _SendT_contra, _ReturnT_co]): if sys.version_info >= (3, 11): @property def gi_suspended(self) -> bool: ... + if sys.version_info >= (3, 15): + @property + def gi_state(self) -> Literal["GEN_CREATED", "GEN_SUSPENDED", "GEN_RUNNING", "GEN_CLOSED"]: ... __name__: str __qualname__: str def __iter__(self) -> Self: ... def __next__(self) -> _YieldT_co: ... def send(self, arg: _SendT_contra, /) -> _YieldT_co: ... + @overload def throw( self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., / ) -> _YieldT_co: ... @overload def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... + if sys.version_info >= (3, 13): def __class_getitem__(cls, item: Any, /) -> Any: ... @@ -437,16 +403,21 @@ class AsyncGeneratorType(AsyncGenerator[_YieldT_co, _SendT_contra]): if sys.version_info >= (3, 12): @property def ag_suspended(self) -> bool: ... + if sys.version_info >= (3, 15): + @property + def ag_state(self) -> Literal["AGEN_CREATED", "AGEN_SUSPENDED", "AGEN_RUNNING", "AGEN_CLOSED"]: ... def __aiter__(self) -> Self: ... def __anext__(self) -> Coroutine[Any, Any, _YieldT_co]: ... def asend(self, val: _SendT_contra, /) -> Coroutine[Any, Any, _YieldT_co]: ... + @overload async def athrow( self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., / ) -> _YieldT_co: ... @overload async def athrow(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... + def aclose(self) -> Coroutine[Any, Any, None]: ... def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @@ -471,16 +442,21 @@ class CoroutineType(Coroutine[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co]): if sys.version_info >= (3, 11): @property def cr_suspended(self) -> bool: ... + if sys.version_info >= (3, 15): + @property + def cr_state(self) -> Literal["CORO_CREATED", "CORO_SUSPENDED", "CORO_RUNNING", "CORO_CLOSED"]: ... def close(self) -> None: ... def __await__(self) -> Generator[Any, None, _ReturnT_nd_co]: ... def send(self, arg: _SendT_nd_contra, /) -> _YieldT_co: ... + @overload def throw( self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., / ) -> _YieldT_co: ... @overload def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... + if sys.version_info >= (3, 13): def __class_getitem__(cls, item: Any, /) -> Any: ... @@ -600,8 +576,14 @@ class FrameType: # An `int | None` annotation here causes too many false-positive errors, so applying `int | Any`. @property def f_lineno(self) -> int | MaybeNone: ... - @property - def f_locals(self) -> dict[str, Any]: ... + + if sys.version_info >= (3, 15): + @property + def f_locals(self) -> FrameLocalsProxyType | dict[str, Any]: ... + else: + @property + def f_locals(self) -> dict[str, Any]: ... + f_trace: Callable[[FrameType, str, Any], Any] | None f_trace_lines: bool f_trace_opcodes: bool @@ -610,6 +592,28 @@ class FrameType: @property def f_generator(self) -> GeneratorType[Any, Any, Any] | CoroutineType[Any, Any, Any] | None: ... +if sys.version_info >= (3, 15): + @final + class FrameLocalsProxyType(MutableMapping[str, Any]): + def __new__(cls, frame: FrameType, /) -> Self: ... + def __getitem__(self, key: str, /) -> Any: ... + def __setitem__(self, key: str, value: Any, /) -> None: ... + def __delitem__(self, key: str, /) -> None: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __contains__(self, key: object, /) -> bool: ... + def __reversed__(self) -> Iterator[str]: ... + def copy(self) -> dict[str, Any]: ... + def pop(self, key: str, default: Any = ..., /) -> Any: ... + def setdefault(self, key: str, default: Any = ..., /) -> Any: ... + def update(self, object: SupportsKeysAndGetItem[str, Any] | Iterable[tuple[str, Any]], /) -> None: ... # type: ignore[override] + + @final + class LazyImportType: + @property + def __name__(self) -> str: ... + def resolve(self) -> Any: ... + @final class GetSetDescriptorType: @property @@ -679,6 +683,7 @@ _P = ParamSpec("_P") def coroutine(func: Callable[_P, Generator[Any, Any, _R]]) -> Callable[_P, Awaitable[_R]]: ... @overload def coroutine(func: _Fn) -> _Fn: ... + @disjoint_base class GenericAlias: @property @@ -697,43 +702,42 @@ class GenericAlias: def __unpacked__(self) -> bool: ... @property def __typing_unpacked_tuple_args__(self) -> tuple[Any, ...] | None: ... - if sys.version_info >= (3, 10): - def __or__(self, value: Any, /) -> UnionType: ... - def __ror__(self, value: Any, /) -> UnionType: ... + + def __or__(self, value: Any, /) -> UnionType: ... + def __ror__(self, value: Any, /) -> UnionType: ... # GenericAlias delegates attr access to `__origin__` def __getattr__(self, name: str) -> Any: ... -if sys.version_info >= (3, 10): - @final - class NoneType: - def __bool__(self) -> Literal[False]: ... +@final +class NoneType: + def __bool__(self) -> Literal[False]: ... - @final - class EllipsisType: ... +@final +class EllipsisType: ... - @final - class NotImplementedType(Any): ... +@final +class NotImplementedType(Any): ... - @final - class UnionType: - @property - def __args__(self) -> tuple[Any, ...]: ... - @property - def __parameters__(self) -> tuple[Any, ...]: ... - # `(int | str) | Literal["foo"]` returns a generic alias to an instance of `_SpecialForm` (`Union`). - # Normally we'd express this using the return type of `_SpecialForm.__ror__`, - # but because `UnionType.__or__` accepts `Any`, type checkers will use - # the return type of `UnionType.__or__` to infer the result of this operation - # rather than `_SpecialForm.__ror__`. To mitigate this, we use `| Any` - # in the return type of `UnionType.__(r)or__`. - def __or__(self, value: Any, /) -> UnionType | Any: ... - def __ror__(self, value: Any, /) -> UnionType | Any: ... - def __eq__(self, value: object, /) -> bool: ... - def __hash__(self) -> int: ... - # you can only subscript a `UnionType` instance if at least one of the elements - # in the union is a generic alias instance that has a non-empty `__parameters__` - def __getitem__(self, parameters: Any, /) -> object: ... +@final +class UnionType: + @property + def __args__(self) -> tuple[Any, ...]: ... + @property + def __parameters__(self) -> tuple[Any, ...]: ... + # `(int | str) | Literal["foo"]` returns a generic alias to an instance of `_SpecialForm` (`Union`). + # Normally we'd express this using the return type of `_SpecialForm.__ror__`, + # but because `UnionType.__or__` accepts `Any`, type checkers will use + # the return type of `UnionType.__or__` to infer the result of this operation + # rather than `_SpecialForm.__ror__`. To mitigate this, we use `| Any` + # in the return type of `UnionType.__(r)or__`. + def __or__(self, value: Any, /) -> UnionType | Any: ... + def __ror__(self, value: Any, /) -> UnionType | Any: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + # you can only subscript a `UnionType` instance if at least one of the elements + # in the union is a generic alias instance that has a non-empty `__parameters__` + def __getitem__(self, parameters: Any, /) -> object: ... if sys.version_info >= (3, 13): @final diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 0bced03866439..2379bec348a82 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -18,18 +18,16 @@ from types import ( MethodWrapperType, ModuleType, TracebackType, + UnionType, WrapperDescriptorType, ) -from typing_extensions import Never as _Never, ParamSpec as _ParamSpec, deprecated +from typing_extensions import Never as _Never, deprecated if sys.version_info >= (3, 14): from _typeshed import EvaluateFunc from annotationlib import Format -if sys.version_info >= (3, 10): - from types import UnionType - __all__ = [ "AbstractSet", "Annotated", @@ -41,11 +39,11 @@ __all__ = [ "AsyncIterator", "Awaitable", "BinaryIO", - "ByteString", "Callable", "ChainMap", "ClassVar", "Collection", + "Concatenate", "Container", "ContextManager", "Coroutine", @@ -77,6 +75,9 @@ __all__ = [ "NoReturn", "Optional", "OrderedDict", + "ParamSpec", + "ParamSpecArgs", + "ParamSpecKwargs", "Pattern", "Protocol", "Reversible", @@ -94,6 +95,8 @@ __all__ = [ "TextIO", "Tuple", "Type", + "TypeAlias", + "TypeGuard", "TypeVar", "TypedDict", "Union", @@ -104,17 +107,20 @@ __all__ = [ "get_args", "get_origin", "get_type_hints", + "is_typeddict", "no_type_check", - "no_type_check_decorator", "overload", "runtime_checkable", ] +if sys.version_info < (3, 15): + __all__ += ["ByteString", "no_type_check_decorator"] + if sys.version_info >= (3, 14): __all__ += ["evaluate_forward_ref"] -if sys.version_info >= (3, 10): - __all__ += ["Concatenate", "ParamSpec", "ParamSpecArgs", "ParamSpecKwargs", "TypeAlias", "TypeGuard", "is_typeddict"] +if sys.version_info >= (3, 15): + __all__ += ["NoExtraItems", "TypeForm", "disjoint_base"] if sys.version_info >= (3, 11): __all__ += [ @@ -149,6 +155,7 @@ class _Final: __slots__ = ("__weakref__",) def final(f: _T) -> _T: ... + @final class TypeVar: @property @@ -206,9 +213,9 @@ class TypeVar: covariant: bool = False, contravariant: bool = False, ) -> None: ... - if sys.version_info >= (3, 10): - def __or__(self, right: Any, /) -> _SpecialForm: ... # AnnotationForm - def __ror__(self, left: Any, /) -> _SpecialForm: ... # AnnotationForm + + def __or__(self, right: Any, /) -> _SpecialForm: ... # AnnotationForm + def __ror__(self, left: Any, /) -> _SpecialForm: ... # AnnotationForm if sys.version_info >= (3, 11): def __typing_subst__(self, arg: Any, /) -> Any: ... if sys.version_info >= (3, 13): @@ -227,9 +234,8 @@ class TypeVar: class _SpecialForm(_Final): __slots__ = ("_name", "__doc__", "_getitem") def __getitem__(self, parameters: Any) -> object: ... - if sys.version_info >= (3, 10): - def __or__(self, other: Any) -> _SpecialForm: ... - def __ror__(self, other: Any) -> _SpecialForm: ... + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... Union: _SpecialForm Protocol: _SpecialForm @@ -257,11 +263,31 @@ if sys.version_info >= (3, 11): class TypeVarTuple: @property def __name__(self) -> str: ... + if sys.version_info >= (3, 15): + @property + def __bound__(self) -> Any | None: ... # AnnotationForm + @property + def __covariant__(self) -> bool: ... + @property + def __contravariant__(self) -> bool: ... + @property + def __infer_variance__(self) -> bool: ... if sys.version_info >= (3, 13): @property def __default__(self) -> Any: ... # AnnotationForm def has_default(self) -> bool: ... - if sys.version_info >= (3, 13): + if sys.version_info >= (3, 15): + def __new__( + cls, + name: str, + *, + bound: Any | None = None, # AnnotationForm + covariant: bool = False, + contravariant: bool = False, + default: Any = ..., # AnnotationForm + infer_variance: bool = False, + ) -> Self: ... + elif sys.version_info >= (3, 13): def __new__(cls, name: str, *, default: Any = ...) -> Self: ... # AnnotationForm elif sys.version_info >= (3, 12): def __new__(cls, name: str) -> Self: ... @@ -275,125 +301,111 @@ if sys.version_info >= (3, 11): @property def evaluate_default(self) -> EvaluateFunc | None: ... -if sys.version_info >= (3, 10): - @final - class ParamSpecArgs: - @property - def __origin__(self) -> ParamSpec: ... - if sys.version_info >= (3, 12): - def __new__(cls, origin: ParamSpec) -> Self: ... - else: - def __init__(self, origin: ParamSpec) -> None: ... - - def __eq__(self, other: object, /) -> bool: ... - __hash__: ClassVar[None] # type: ignore[assignment] +@final +class ParamSpecArgs: + @property + def __origin__(self) -> ParamSpec: ... + if sys.version_info >= (3, 12): + def __new__(cls, origin: ParamSpec) -> Self: ... + else: + def __init__(self, origin: ParamSpec) -> None: ... - @final - class ParamSpecKwargs: - @property - def __origin__(self) -> ParamSpec: ... - if sys.version_info >= (3, 12): - def __new__(cls, origin: ParamSpec) -> Self: ... - else: - def __init__(self, origin: ParamSpec) -> None: ... + def __eq__(self, other: object, /) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] - def __eq__(self, other: object, /) -> bool: ... - __hash__: ClassVar[None] # type: ignore[assignment] +@final +class ParamSpecKwargs: + @property + def __origin__(self) -> ParamSpec: ... + if sys.version_info >= (3, 12): + def __new__(cls, origin: ParamSpec) -> Self: ... + else: + def __init__(self, origin: ParamSpec) -> None: ... - @final - class ParamSpec: - @property - def __name__(self) -> str: ... - @property - def __bound__(self) -> Any | None: ... # AnnotationForm - @property - def __covariant__(self) -> bool: ... - @property - def __contravariant__(self) -> bool: ... - if sys.version_info >= (3, 12): - @property - def __infer_variance__(self) -> bool: ... - if sys.version_info >= (3, 13): - @property - def __default__(self) -> Any: ... # AnnotationForm - if sys.version_info >= (3, 13): - def __new__( - cls, - name: str, - *, - bound: Any | None = None, # AnnotationForm - contravariant: bool = False, - covariant: bool = False, - infer_variance: bool = False, - default: Any = ..., # AnnotationForm - ) -> Self: ... - elif sys.version_info >= (3, 12): - def __new__( - cls, - name: str, - *, - bound: Any | None = None, # AnnotationForm - contravariant: bool = False, - covariant: bool = False, - infer_variance: bool = False, - ) -> Self: ... - elif sys.version_info >= (3, 11): - def __new__( - cls, - name: str, - *, - bound: Any | None = None, # AnnotationForm - contravariant: bool = False, - covariant: bool = False, - ) -> Self: ... - else: - def __init__( - self, - name: str, - *, - bound: Any | None = None, # AnnotationForm - contravariant: bool = False, - covariant: bool = False, - ) -> None: ... + def __eq__(self, other: object, /) -> bool: ... + __hash__: ClassVar[None] # type: ignore[assignment] +@final +class ParamSpec: + @property + def __name__(self) -> str: ... + @property + def __bound__(self) -> Any | None: ... # AnnotationForm + @property + def __covariant__(self) -> bool: ... + @property + def __contravariant__(self) -> bool: ... + if sys.version_info >= (3, 12): @property - def args(self) -> ParamSpecArgs: ... + def __infer_variance__(self) -> bool: ... + if sys.version_info >= (3, 13): @property - def kwargs(self) -> ParamSpecKwargs: ... - if sys.version_info >= (3, 11): - def __typing_subst__(self, arg: Any, /) -> Any: ... - def __typing_prepare_subst__(self, alias: Any, args: Any, /) -> tuple[Any, ...]: ... + def __default__(self) -> Any: ... # AnnotationForm + if sys.version_info >= (3, 13): + def __new__( + cls, + name: str, + *, + bound: Any | None = None, # AnnotationForm + contravariant: bool = False, + covariant: bool = False, + infer_variance: bool = False, + default: Any = ..., # AnnotationForm + ) -> Self: ... + elif sys.version_info >= (3, 12): + def __new__( + cls, + name: str, + *, + bound: Any | None = None, # AnnotationForm + contravariant: bool = False, + covariant: bool = False, + infer_variance: bool = False, + ) -> Self: ... + elif sys.version_info >= (3, 11): + def __new__( + cls, name: str, *, bound: Any | None = None, contravariant: bool = False, covariant: bool = False # AnnotationForm + ) -> Self: ... + else: + def __init__( + self, name: str, *, bound: Any | None = None, contravariant: bool = False, covariant: bool = False # AnnotationForm + ) -> None: ... - def __or__(self, right: Any, /) -> _SpecialForm: ... - def __ror__(self, left: Any, /) -> _SpecialForm: ... - if sys.version_info >= (3, 13): - def has_default(self) -> bool: ... - if sys.version_info >= (3, 14): - @property - def evaluate_default(self) -> EvaluateFunc | None: ... + @property + def args(self) -> ParamSpecArgs: ... + @property + def kwargs(self) -> ParamSpecKwargs: ... + if sys.version_info >= (3, 11): + def __typing_subst__(self, arg: Any, /) -> Any: ... + def __typing_prepare_subst__(self, alias: Any, args: Any, /) -> tuple[Any, ...]: ... - Concatenate: _SpecialForm - TypeAlias: _SpecialForm - TypeGuard: _SpecialForm + def __or__(self, right: Any, /) -> _SpecialForm: ... + def __ror__(self, left: Any, /) -> _SpecialForm: ... + if sys.version_info >= (3, 13): + def has_default(self) -> bool: ... + if sys.version_info >= (3, 14): + @property + def evaluate_default(self) -> EvaluateFunc | None: ... - class NewType: - def __init__(self, name: str, tp: Any) -> None: ... # AnnotationForm - if sys.version_info >= (3, 11): - @staticmethod - def __call__(x: _T, /) -> _T: ... - else: - def __call__(self, x: _T) -> _T: ... +Concatenate: _SpecialForm +TypeAlias: _SpecialForm +TypeGuard: _SpecialForm - def __or__(self, other: Any) -> _SpecialForm: ... - def __ror__(self, other: Any) -> _SpecialForm: ... - __supertype__: type | NewType - __name__: str +class NewType: + def __init__(self, name: str, tp: Any) -> None: ... # AnnotationForm + if sys.version_info >= (3, 11): + @staticmethod + def __call__(x: _T, /) -> _T: ... + else: + def __call__(self, x: _T) -> _T: ... -else: - def NewType(name: str, tp: Any) -> Any: ... + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... + __supertype__: type | NewType + __name__: str _F = TypeVar("_F", bound=Callable[..., Any]) -_P = _ParamSpec("_P") +_P = ParamSpec("_P") _T = TypeVar("_T") _FT = TypeVar("_FT", bound=Callable[..., Any] | type) @@ -410,12 +422,12 @@ _TC = TypeVar("_TC", bound=type[object]) def overload(func: _F) -> _F: ... def no_type_check(arg: _F) -> _F: ... -if sys.version_info >= (3, 13): +if sys.version_info < (3, 15): @deprecated("Deprecated since Python 3.13; removed in Python 3.15.") def no_type_check_decorator(decorator: Callable[_P, _T]) -> Callable[_P, _T]: ... -else: - def no_type_check_decorator(decorator: Callable[_P, _T]) -> Callable[_P, _T]: ... +if sys.version_info >= (3, 15): + def disjoint_base(cls: _TC) -> _TC: ... # This itself is only available during type checking def type_check_only(func_or_cls: _FT) -> _FT: ... @@ -439,6 +451,13 @@ ChainMap = _Alias() OrderedDict = _Alias() Annotated: _SpecialForm +if sys.version_info >= (3, 15): + @type_check_only + class _NoExtraItemsType: ... + + NoExtraItems: _NoExtraItemsType + + TypeForm: _SpecialForm # Predefined type variables. AnyStr = TypeVar("AnyStr", str, bytes) # noqa: Y001 @@ -448,12 +467,8 @@ class _Generic: if sys.version_info < (3, 12): __slots__ = () - if sys.version_info >= (3, 10): - @classmethod - def __class_getitem__(cls, args: TypeVar | ParamSpec | tuple[TypeVar | ParamSpec, ...]) -> _Final: ... - else: - @classmethod - def __class_getitem__(cls, args: TypeVar | tuple[TypeVar, ...]) -> _Final: ... + @classmethod + def __class_getitem__(cls, args: TypeVar | ParamSpec | tuple[TypeVar | ParamSpec, ...]) -> _Final: ... Generic: type[_Generic] @@ -464,6 +479,7 @@ class _ProtocolMeta(ABCMeta): # Abstract base classes. def runtime_checkable(cls: _TC) -> _TC: ... + @runtime_checkable class SupportsInt(Protocol, metaclass=ABCMeta): __slots__ = () @@ -503,6 +519,7 @@ class SupportsAbs(Protocol[_T_co]): @runtime_checkable class SupportsRound(Protocol[_T_co]): __slots__ = () + @overload @abstractmethod def __round__(self) -> int: ... @@ -548,6 +565,7 @@ class Generator(Iterator[_YieldT_co], Protocol[_YieldT_co, _SendT_contra, _Retur def __next__(self) -> _YieldT_co: ... @abstractmethod def send(self, value: _SendT_contra, /) -> _YieldT_co: ... + @overload @abstractmethod def throw( @@ -556,6 +574,7 @@ class Generator(Iterator[_YieldT_co], Protocol[_YieldT_co, _SendT_contra, _Retur @overload @abstractmethod def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co: ... + if sys.version_info >= (3, 13): def close(self) -> _ReturnT_co | None: ... else: @@ -590,6 +609,7 @@ class Coroutine(Awaitable[_ReturnT_nd_co], Generic[_YieldT_co, _SendT_nd_contra, @abstractmethod def send(self, value: _SendT_nd_contra, /) -> _YieldT_co: ... + @overload @abstractmethod def throw( @@ -598,6 +618,7 @@ class Coroutine(Awaitable[_ReturnT_nd_co], Generic[_YieldT_co, _SendT_nd_contra, @overload @abstractmethod def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co: ... + @abstractmethod def close(self) -> None: ... @@ -628,6 +649,7 @@ class AsyncGenerator(AsyncIterator[_YieldT_co], Protocol[_YieldT_co, _SendT_cont def __anext__(self) -> Coroutine[Any, Any, _YieldT_co]: ... @abstractmethod def asend(self, value: _SendT_contra, /) -> Coroutine[Any, Any, _YieldT_co]: ... + @overload @abstractmethod def athrow( @@ -638,6 +660,7 @@ class AsyncGenerator(AsyncIterator[_YieldT_co], Protocol[_YieldT_co, _SendT_cont def athrow( self, typ: BaseException, val: None = None, tb: TracebackType | None = None, / ) -> Coroutine[Any, Any, _YieldT_co]: ... + def aclose(self) -> Coroutine[Any, Any, None]: ... @runtime_checkable @@ -659,6 +682,7 @@ class Sequence(Reversible[_T_co], Collection[_T_co]): @overload @abstractmethod def __getitem__(self, index: slice[int | None], /) -> Sequence[_T_co]: ... + # Mixin methods def index(self, value: Any, start: int = 0, stop: int = ..., /) -> int: ... def count(self, value: Any, /) -> int: ... @@ -669,24 +693,28 @@ class Sequence(Reversible[_T_co], Collection[_T_co]): class MutableSequence(Sequence[_T]): @abstractmethod def insert(self, index: int, value: _T, /) -> None: ... + @overload @abstractmethod def __getitem__(self, index: int, /) -> _T: ... @overload @abstractmethod def __getitem__(self, index: slice[int | None], /) -> MutableSequence[_T]: ... + @overload @abstractmethod def __setitem__(self, index: int, value: _T, /) -> None: ... @overload @abstractmethod def __setitem__(self, index: slice[int | None], value: Iterable[_T], /) -> None: ... + @overload @abstractmethod def __delitem__(self, index: int, /) -> None: ... @overload @abstractmethod def __delitem__(self, index: slice[int | None], /) -> None: ... + # Mixin methods def append(self, value: _T, /) -> None: ... def clear(self) -> None: ... @@ -778,6 +806,7 @@ class Mapping(Collection[_KT], Generic[_KT, _VT_co]): # see discussion in https://github.com/python/typing/pull/273. @abstractmethod def __getitem__(self, key: _KT, /) -> _VT_co: ... + # Mixin methods @overload def get(self, key: _KT, /) -> _VT_co | None: ... @@ -785,6 +814,7 @@ class Mapping(Collection[_KT], Generic[_KT, _VT_co]): def get(self, key: _KT, default: _VT_co, /) -> _VT_co: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter @overload def get(self, key: _KT, default: _T, /) -> _VT_co | _T: ... + def items(self) -> ItemsView[_KT, _VT_co]: ... def keys(self) -> KeysView[_KT]: ... def values(self) -> ValuesView[_VT_co]: ... @@ -797,13 +827,16 @@ class MutableMapping(Mapping[_KT, _VT]): @abstractmethod def __delitem__(self, key: _KT, /) -> None: ... def clear(self) -> None: ... + @overload def pop(self, key: _KT, /) -> _VT: ... @overload def pop(self, key: _KT, default: _VT, /) -> _VT: ... @overload def pop(self, key: _KT, default: _T, /) -> _VT | _T: ... + def popitem(self) -> tuple[_KT, _VT]: ... + # This overload should be allowed only if the value type is compatible with None. # # Keep the following methods in line with MutableMapping.setdefault, modulo positional-only differences: @@ -814,6 +847,7 @@ class MutableMapping(Mapping[_KT, _VT]): def setdefault(self: MutableMapping[_KT, _T | None], key: _KT, default: None = None, /) -> _T | None: ... @overload def setdefault(self, key: _KT, default: _VT, /) -> _VT: ... + # 'update' used to take a Union, but using overloading is better. # The second overloaded type here is a bit too general, because # Mapping[tuple[_KT, _VT], W] is a subclass of Iterable[tuple[_KT, _VT]], @@ -891,18 +925,21 @@ class IO(Generic[AnyStr]): def truncate(self, size: int | None = None, /) -> int: ... @abstractmethod def writable(self) -> bool: ... + @abstractmethod @overload def write(self: IO[bytes], s: ReadableBuffer, /) -> int: ... @abstractmethod @overload def write(self, s: AnyStr, /) -> int: ... + @abstractmethod @overload def writelines(self: IO[bytes], lines: Iterable[ReadableBuffer], /) -> None: ... @abstractmethod @overload def writelines(self, lines: Iterable[AnyStr], /) -> None: ... + @abstractmethod def __next__(self) -> AnyStr: ... @abstractmethod @@ -971,16 +1008,15 @@ else: def get_args(tp: Any) -> tuple[Any, ...]: ... # AnnotationForm -if sys.version_info >= (3, 10): - @overload - def get_origin(tp: ParamSpecArgs | ParamSpecKwargs) -> ParamSpec: ... - @overload - def get_origin(tp: UnionType) -> type[UnionType]: ... - +@overload +def get_origin(tp: ParamSpecArgs | ParamSpecKwargs) -> ParamSpec: ... +@overload +def get_origin(tp: UnionType) -> type[UnionType]: ... @overload def get_origin(tp: GenericAlias) -> type: ... @overload def get_origin(tp: Any) -> Any | None: ... # AnnotationForm + @overload def cast(typ: type[_T], val: Any) -> _T: ... @overload @@ -1020,6 +1056,7 @@ class NamedTuple(tuple[Any, ...]): @overload @deprecated("Creating a typing.NamedTuple using keyword arguments is deprecated and support will be removed in Python 3.15") def __init__(self, typename: str, fields: None = None, /, **kwargs: Any) -> None: ... + @classmethod def _make(cls, iterable: Iterable[Any]) -> typing_extensions.Self: ... def _asdict(self) -> dict[str, Any]: ... @@ -1054,14 +1091,17 @@ class _TypedDict(Mapping[str, object], metaclass=ABCMeta): def items(self) -> dict_items[str, object]: ... def keys(self) -> dict_keys[str, object]: ... def values(self) -> dict_values[str, object]: ... + @overload def __or__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... @overload def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... + @overload def __ror__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... @overload def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... + # supposedly incompatible definitions of __or__ and __ior__ def __ior__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ... # type: ignore[misc] @@ -1139,9 +1179,7 @@ else: def __or__(self, other: Any) -> _SpecialForm: ... def __ror__(self, other: Any) -> _SpecialForm: ... -if sys.version_info >= (3, 10): - def is_typeddict(tp: object) -> bool: ... - +def is_typeddict(tp: object) -> bool: ... def _type_repr(obj: object) -> str: ... if sys.version_info >= (3, 12): @@ -1155,6 +1193,7 @@ if sys.version_info >= (3, 12): ) def override(method: _F, /) -> _F: ... + @final class TypeAliasType: def __new__(cls, name: str, value: Any, *, type_params: tuple[_TypeParameter, ...] = ()) -> Self: ... @@ -1166,6 +1205,9 @@ if sys.version_info >= (3, 12): def __parameters__(self) -> tuple[Any, ...]: ... # AnnotationForm @property def __name__(self) -> str: ... + if sys.version_info >= (3, 15): + @property + def __qualname__(self) -> str: ... # It's writable on types, but not on instances of TypeAliasType. @property def __module__(self) -> str | None: ... # type: ignore[override] @@ -1173,12 +1215,14 @@ if sys.version_info >= (3, 12): def __or__(self, right: Any, /) -> _SpecialForm: ... def __ror__(self, left: Any, /) -> _SpecialForm: ... if sys.version_info >= (3, 14): + def __iter__(self) -> Any: ... # Unpack[Self] @property def evaluate_value(self) -> EvaluateFunc: ... if sys.version_info >= (3, 13): def is_protocol(tp: type, /) -> bool: ... def get_protocol_members(tp: type, /) -> frozenset[str]: ... + @final @type_check_only class _NoDefaultType: ... diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index 406005cc4c561..fdbba495c579f 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -29,8 +29,8 @@ from collections.abc import ( ) from contextlib import AbstractAsyncContextManager as AsyncContextManager, AbstractContextManager as ContextManager from re import Match as Match, Pattern as Pattern -from types import GenericAlias, ModuleType -from typing import ( # noqa: Y022,Y037,Y038,Y039,UP035,RUF100 +from types import GenericAlias, ModuleType, UnionType +from typing import ( # noqa: Y022,Y037,Y038,Y039,UP035 IO as IO, TYPE_CHECKING as TYPE_CHECKING, AbstractSet as AbstractSet, @@ -40,6 +40,7 @@ from typing import ( # noqa: Y022,Y037,Y038,Y039,UP035,RUF100 Callable as Callable, ChainMap as ChainMap, ClassVar as ClassVar, + Concatenate as Concatenate, Counter as Counter, DefaultDict as DefaultDict, Deque as Deque, @@ -50,26 +51,27 @@ from typing import ( # noqa: Y022,Y037,Y038,Y039,UP035,RUF100 List as List, NoReturn as NoReturn, Optional as Optional, + ParamSpecArgs as ParamSpecArgs, + ParamSpecKwargs as ParamSpecKwargs, Set as Set, Text as Text, TextIO as TextIO, Tuple as Tuple, Type as Type, + TypeAlias as TypeAlias, TypedDict as TypedDict, + TypeGuard as TypeGuard, TypeVar as _TypeVar, Union as Union, _Alias, _SpecialForm, cast as cast, + is_typeddict as is_typeddict, no_type_check as no_type_check, - no_type_check_decorator as no_type_check_decorator, overload as overload, type_check_only, ) -if sys.version_info >= (3, 10): - from types import UnionType - # Please keep order the same as at runtime. __all__ = [ # Super-special typing primitives. @@ -207,6 +209,9 @@ _TC = _TypeVar("_TC", bound=type[object]) _T_co = _TypeVar("_T_co", covariant=True) # Any type covariant containers. _T_contra = _TypeVar("_T_contra", contravariant=True) +if sys.version_info < (3, 15): + def no_type_check_decorator(decorator: _F) -> _F: ... + # Do not import (and re-export) Protocol or runtime_checkable from # typing module because type checkers need to be able to distinguish # typing.Protocol and typing_extensions.Protocol so they can properly @@ -252,14 +257,17 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): def keys(self) -> dict_keys[str, object]: ... def values(self) -> dict_values[str, object]: ... def __delitem__(self, k: Never) -> None: ... + @overload def __or__(self, value: Self, /) -> Self: ... @overload def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ... + @overload def __ror__(self, value: Self, /) -> Self: ... @overload def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ... + # supposedly incompatible definitions of `__ior__` and `__or__`: # Since this module defines "Self" it is not recognized by Ruff as typing_extensions.Self def __ior__(self, value: Self, /) -> Self: ... # type: ignore[misc] @@ -275,10 +283,8 @@ else: def get_args(tp: AnnotationForm) -> tuple[AnnotationForm, ...]: ... -if sys.version_info >= (3, 10): - @overload - def get_origin(tp: UnionType) -> type[UnionType]: ... - +@overload +def get_origin(tp: UnionType) -> type[UnionType]: ... @overload def get_origin(tp: GenericAlias) -> type: ... @overload @@ -289,34 +295,6 @@ def get_origin(tp: AnnotationForm) -> AnnotationForm | None: ... Annotated: _SpecialForm _AnnotatedAlias: Any # undocumented -# New and changed things in 3.10 -if sys.version_info >= (3, 10): - from typing import ( - Concatenate as Concatenate, - ParamSpecArgs as ParamSpecArgs, - ParamSpecKwargs as ParamSpecKwargs, - TypeAlias as TypeAlias, - TypeGuard as TypeGuard, - is_typeddict as is_typeddict, - ) -else: - @final - class ParamSpecArgs: - @property - def __origin__(self) -> ParamSpec: ... - def __init__(self, origin: ParamSpec) -> None: ... - - @final - class ParamSpecKwargs: - @property - def __origin__(self) -> ParamSpec: ... - def __init__(self, origin: ParamSpec) -> None: ... - - Concatenate: _SpecialForm - TypeAlias: _SpecialForm - TypeGuard: _SpecialForm - def is_typeddict(tp: object) -> bool: ... - # New and changed things in 3.11 if sys.version_info >= (3, 11): from typing import ( @@ -363,10 +341,12 @@ else: _field_defaults: ClassVar[dict[str, Any]] _fields: ClassVar[tuple[str, ...]] __orig_bases__: ClassVar[tuple[Any, ...]] + @overload def __init__(self, typename: str, fields: Iterable[tuple[str, Any]] = ...) -> None: ... @overload def __init__(self, typename: str, fields: None = None, **kwargs: Any) -> None: ... + @classmethod def _make(cls, iterable: Iterable[Any]) -> Self: ... def _asdict(self) -> dict[str, Any]: ... @@ -375,11 +355,10 @@ else: class NewType: def __init__(self, name: str, tp: AnnotationForm) -> None: ... def __call__(self, obj: _T, /) -> _T: ... + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... __supertype__: type | NewType __name__: str - if sys.version_info >= (3, 10): - def __or__(self, other: Any) -> _SpecialForm: ... - def __ror__(self, other: Any) -> _SpecialForm: ... if sys.version_info >= (3, 12): from collections.abc import Buffer as Buffer @@ -446,6 +425,7 @@ else: @runtime_checkable class SupportsRound(Protocol[_T_co]): __slots__ = () + @overload @abc.abstractmethod def __round__(self) -> int: ... @@ -484,6 +464,7 @@ if sys.version_info >= (3, 13): else: def is_protocol(tp: type, /) -> bool: ... def get_protocol_members(tp: type, /) -> frozenset[str]: ... + @final @type_check_only class _NoDefaultType: ... @@ -527,9 +508,8 @@ else: ) -> None: ... def has_default(self) -> bool: ... def __typing_prepare_subst__(self, alias: Any, args: Any) -> tuple[Any, ...]: ... - if sys.version_info >= (3, 10): - def __or__(self, right: Any) -> _SpecialForm: ... - def __ror__(self, left: Any) -> _SpecialForm: ... + def __or__(self, right: Any) -> _SpecialForm: ... + def __ror__(self, left: Any) -> _SpecialForm: ... if sys.version_info >= (3, 11): def __typing_subst__(self, arg: Any) -> Any: ... @@ -556,15 +536,14 @@ else: covariant: bool = False, default: AnnotationForm = ..., ) -> None: ... + def __or__(self, right: Any) -> _SpecialForm: ... + def __ror__(self, left: Any) -> _SpecialForm: ... @property def args(self) -> ParamSpecArgs: ... @property def kwargs(self) -> ParamSpecKwargs: ... def has_default(self) -> bool: ... def __typing_prepare_subst__(self, alias: Any, args: Any) -> tuple[Any, ...]: ... - if sys.version_info >= (3, 10): - def __or__(self, right: Any) -> _SpecialForm: ... - def __ror__(self, left: Any) -> _SpecialForm: ... @final class TypeVarTuple: @@ -605,9 +584,8 @@ else: # Returns typing._GenericAlias, which isn't stubbed. def __getitem__(self, parameters: Incomplete | tuple[Incomplete, ...]) -> AnnotationForm: ... def __init_subclass__(cls, *args: Unused, **kwargs: Unused) -> NoReturn: ... - if sys.version_info >= (3, 10): - def __or__(self, right: Any, /) -> _SpecialForm: ... - def __ror__(self, left: Any, /) -> _SpecialForm: ... + def __or__(self, right: Any, /) -> _SpecialForm: ... + def __ror__(self, left: Any, /) -> _SpecialForm: ... # PEP 727 class Doc: @@ -664,6 +642,7 @@ else: eval_str: bool = False, format: Format = Format.VALUE, # noqa: Y011 ) -> dict[str, AnnotationForm]: ... + @overload def evaluate_forward_ref( forward_ref: ForwardRef, @@ -697,6 +676,7 @@ else: format: Format | None = None, _recursive_guard: Container[str] = ..., ) -> AnnotationForm: ... + def type_repr(value: object) -> str: ... # PEP 661 @@ -705,6 +685,6 @@ class Sentinel: if sys.version_info >= (3, 14): def __or__(self, other: Any) -> UnionType: ... # other can be any type form legal for unions def __ror__(self, other: Any) -> UnionType: ... # other can be any type form legal for unions - elif sys.version_info >= (3, 10): + else: def __or__(self, other: Any) -> _SpecialForm: ... # other can be any type form legal for unions def __ror__(self, other: Any) -> _SpecialForm: ... # other can be any type form legal for unions diff --git a/mypy/typeshed/stdlib/unicodedata.pyi b/mypy/typeshed/stdlib/unicodedata.pyi index 9fff042f0b964..82a73181eed3b 100644 --- a/mypy/typeshed/stdlib/unicodedata.pyi +++ b/mypy/typeshed/stdlib/unicodedata.pyi @@ -1,14 +1,11 @@ import sys from _typeshed import ReadOnlyBuffer -from typing import Any, Final, Literal, TypeVar, final, overload -from typing_extensions import TypeAlias +from collections.abc import Iterator +from typing import Final, Literal, TypeAlias, TypeVar, final, overload ucd_3_2_0: UCD unidata_version: Final[str] -if sys.version_info < (3, 10): - ucnhash_CAPI: Any - _T = TypeVar("_T") _NormalizationForm: TypeAlias = Literal["NFC", "NFD", "NFKC", "NFKD"] @@ -16,11 +13,14 @@ _NormalizationForm: TypeAlias = Literal["NFC", "NFD", "NFKC", "NFKD"] def bidirectional(chr: str, /) -> str: ... def category(chr: str, /) -> str: ... def combining(chr: str, /) -> int: ... + @overload def decimal(chr: str, /) -> int: ... @overload def decimal(chr: str, default: _T, /) -> int | _T: ... + def decomposition(chr: str, /) -> str: ... + @overload def digit(chr: str, /) -> int: ... @overload @@ -30,17 +30,31 @@ _EastAsianWidth: TypeAlias = Literal["F", "H", "W", "Na", "A", "N"] def east_asian_width(chr: str, /) -> _EastAsianWidth: ... def is_normalized(form: _NormalizationForm, unistr: str, /) -> bool: ... + +if sys.version_info >= (3, 15): + def block(chr: str, /) -> str: ... + def extended_pictographic(chr: str, /) -> bool: ... + def grapheme_cluster_break(chr: str, /) -> str: ... + def indic_conjunct_break(chr: str, /) -> str: ... + def isxidstart(chr: str, /) -> bool: ... + def isxidcontinue(chr: str, /) -> bool: ... + def iter_graphemes(unistr: str, start: int = 0, end: int = sys.maxsize, /) -> Iterator[str]: ... + def lookup(name: str | ReadOnlyBuffer, /) -> str: ... def mirrored(chr: str, /) -> int: ... + @overload def name(chr: str, /) -> str: ... @overload def name(chr: str, default: _T, /) -> str | _T: ... + def normalize(form: _NormalizationForm, unistr: str, /) -> str: ... + @overload def numeric(chr: str, /) -> float: ... @overload def numeric(chr: str, default: _T, /) -> float | _T: ... + @final class UCD: # The methods below are constructed from the same array in C @@ -49,24 +63,31 @@ class UCD: def bidirectional(self, chr: str, /) -> str: ... def category(self, chr: str, /) -> str: ... def combining(self, chr: str, /) -> int: ... + @overload def decimal(self, chr: str, /) -> int: ... @overload def decimal(self, chr: str, default: _T, /) -> int | _T: ... + def decomposition(self, chr: str, /) -> str: ... + @overload def digit(self, chr: str, /) -> int: ... @overload def digit(self, chr: str, default: _T, /) -> int | _T: ... + def east_asian_width(self, chr: str, /) -> _EastAsianWidth: ... def is_normalized(self, form: _NormalizationForm, unistr: str, /) -> bool: ... def lookup(self, name: str | ReadOnlyBuffer, /) -> str: ... def mirrored(self, chr: str, /) -> int: ... + @overload def name(self, chr: str, /) -> str: ... @overload def name(self, chr: str, default: _T, /) -> str | _T: ... + def normalize(self, form: _NormalizationForm, unistr: str, /) -> str: ... + @overload def numeric(self, chr: str, /) -> float: ... @overload diff --git a/mypy/typeshed/stdlib/unittest/_log.pyi b/mypy/typeshed/stdlib/unittest/_log.pyi index 011a970d8bbce..da6ce5a5ac7ae 100644 --- a/mypy/typeshed/stdlib/unittest/_log.pyi +++ b/mypy/typeshed/stdlib/unittest/_log.pyi @@ -15,11 +15,13 @@ class _AssertLogsContext(_BaseTestCaseContext, Generic[_L]): logger_name: str level: int msg: None - if sys.version_info >= (3, 10): - def __init__(self, test_case: TestCase, logger_name: str, level: int, no_logs: bool) -> None: ... - no_logs: bool + no_logs: bool + if sys.version_info >= (3, 15): + def __init__( + self, test_case: TestCase, logger_name: str, level: int, no_logs: bool, formatter: logging.Formatter | None = None + ) -> None: ... else: - def __init__(self, test_case: TestCase, logger_name: str, level: int) -> None: ... + def __init__(self, test_case: TestCase, logger_name: str, level: int, no_logs: bool) -> None: ... def __enter__(self) -> _L: ... def __exit__( diff --git a/mypy/typeshed/stdlib/unittest/async_case.pyi b/mypy/typeshed/stdlib/unittest/async_case.pyi index 0b3fb9122c7b9..77627a85ef197 100644 --- a/mypy/typeshed/stdlib/unittest/async_case.pyi +++ b/mypy/typeshed/stdlib/unittest/async_case.pyi @@ -1,8 +1,7 @@ import sys from asyncio.events import AbstractEventLoop from collections.abc import Awaitable, Callable -from typing import TypeVar -from typing_extensions import ParamSpec +from typing import ParamSpec, TypeVar from .case import TestCase diff --git a/mypy/typeshed/stdlib/unittest/case.pyi b/mypy/typeshed/stdlib/unittest/case.pyi index a602196e73c64..942154ea53aea 100644 --- a/mypy/typeshed/stdlib/unittest/case.pyi +++ b/mypy/typeshed/stdlib/unittest/case.pyi @@ -7,8 +7,21 @@ from collections.abc import Callable, Container, Iterable, Mapping, Sequence, Se from contextlib import AbstractContextManager from re import Pattern from types import GenericAlias, TracebackType -from typing import Any, AnyStr, Final, Generic, NoReturn, Protocol, SupportsAbs, SupportsRound, TypeVar, overload, type_check_only -from typing_extensions import Never, ParamSpec, Self +from typing import ( + Any, + AnyStr, + Final, + Generic, + NoReturn, + ParamSpec, + Protocol, + SupportsAbs, + SupportsRound, + TypeVar, + overload, + type_check_only, +) +from typing_extensions import Never, Self from unittest._log import _AssertLogsContext, _LoggingWatcher from warnings import WarningMessage @@ -54,7 +67,7 @@ def skipIf(condition: object, reason: str) -> Callable[[_FT], _FT]: ... def skipUnless(condition: object, reason: str) -> Callable[[_FT], _FT]: ... class SkipTest(Exception): - def __init__(self, reason: str) -> None: ... + def __init__(self, reason: str, /) -> None: ... @type_check_only class _SupportsAbsAndDunderGE(SupportsDunderGE[Any], SupportsAbs[Any], Protocol): ... @@ -96,22 +109,27 @@ class TestCase: def assertNotIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None: ... def assertIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None: ... def assertNotIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None: ... + @overload def assertGreater(self, a: SupportsDunderGT[_T], b: _T, msg: Any = None) -> None: ... @overload def assertGreater(self, a: _T, b: SupportsDunderLT[_T], msg: Any = None) -> None: ... + @overload def assertGreaterEqual(self, a: SupportsDunderGE[_T], b: _T, msg: Any = None) -> None: ... @overload def assertGreaterEqual(self, a: _T, b: SupportsDunderLE[_T], msg: Any = None) -> None: ... + @overload def assertLess(self, a: SupportsDunderLT[_T], b: _T, msg: Any = None) -> None: ... @overload def assertLess(self, a: _T, b: SupportsDunderGT[_T], msg: Any = None) -> None: ... + @overload def assertLessEqual(self, a: SupportsDunderLE[_T], b: _T, msg: Any = None) -> None: ... @overload def assertLessEqual(self, a: _T, b: SupportsDunderGE[_T], msg: Any = None) -> None: ... + # `assertRaises`, `assertRaisesRegex`, and `assertRaisesRegexp` # are not using `ParamSpec` intentionally, # because they might be used with explicitly wrong arg types to raise some error in tests. @@ -127,6 +145,7 @@ class TestCase: def assertRaises( self, expected_exception: type[_E] | tuple[type[_E], ...], *, msg: Any = ... ) -> _AssertRaisesContext[_E]: ... + @overload def assertRaisesRegex( self, @@ -140,6 +159,7 @@ class TestCase: def assertRaisesRegex( self, expected_exception: type[_E] | tuple[type[_E], ...], expected_regex: str | Pattern[str], *, msg: Any = ... ) -> _AssertRaisesContext[_E]: ... + @overload def assertWarns( self, @@ -152,6 +172,7 @@ class TestCase: def assertWarns( self, expected_warning: type[Warning] | tuple[type[Warning], ...], *, msg: Any = ... ) -> _AssertWarnsContext: ... + @overload def assertWarnsRegex( self, @@ -165,13 +186,22 @@ class TestCase: def assertWarnsRegex( self, expected_warning: type[Warning] | tuple[type[Warning], ...], expected_regex: str | Pattern[str], *, msg: Any = ... ) -> _AssertWarnsContext: ... - def assertLogs( - self, logger: str | logging.Logger | None = None, level: int | str | None = None - ) -> _AssertLogsContext[_LoggingWatcher]: ... - if sys.version_info >= (3, 10): - def assertNoLogs( + + if sys.version_info >= (3, 15): + def assertLogs( + self, + logger: str | logging.Logger | None = None, + level: int | str | None = None, + formatter: logging.Formatter | None = None, + ) -> _AssertLogsContext[_LoggingWatcher]: ... + else: + def assertLogs( self, logger: str | logging.Logger | None = None, level: int | str | None = None - ) -> _AssertLogsContext[None]: ... + ) -> _AssertLogsContext[_LoggingWatcher]: ... + + def assertNoLogs( + self, logger: str | logging.Logger | None = None, level: int | str | None = None + ) -> _AssertLogsContext[None]: ... @overload def assertAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: ... @@ -197,6 +227,7 @@ class TestCase: msg: Any = None, delta: None = None, ) -> None: ... + @overload def assertNotAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: ... @overload @@ -221,6 +252,7 @@ class TestCase: msg: Any = None, delta: None = None, ) -> None: ... + def assertRegex(self, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None: ... def assertNotRegex(self, text: AnyStr, unexpected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None: ... def assertCountEqual(self, first: Iterable[Any], second: Iterable[Any], msg: Any = None) -> None: ... @@ -277,9 +309,8 @@ class TestCase: self, subset: Mapping[Any, Any], dictionary: Mapping[Any, Any], msg: object = None ) -> None: ... - if sys.version_info >= (3, 10): - # Runtime has *args, **kwargs, but will error if any are supplied - def __init_subclass__(cls, *args: Never, **kwargs: Never) -> None: ... + # Runtime has *args, **kwargs, but will error if any are supplied + def __init_subclass__(cls, *args: Never, **kwargs: Never) -> None: ... if sys.version_info >= (3, 14): def assertIsSubclass(self, cls: type, superclass: type | tuple[type, ...], msg: Any = None) -> None: ... diff --git a/mypy/typeshed/stdlib/unittest/loader.pyi b/mypy/typeshed/stdlib/unittest/loader.pyi index 81de40c898496..0d92b78f3461d 100644 --- a/mypy/typeshed/stdlib/unittest/loader.pyi +++ b/mypy/typeshed/stdlib/unittest/loader.pyi @@ -4,8 +4,8 @@ import unittest.suite from collections.abc import Callable, Sequence from re import Pattern from types import ModuleType -from typing import Any, Final -from typing_extensions import TypeAlias, deprecated +from typing import Any, Final, TypeAlias +from typing_extensions import deprecated _SortComparisonMethod: TypeAlias = Callable[[str, str], int] _SuiteClass: TypeAlias = Callable[[list[unittest.case.TestCase]], unittest.suite.TestSuite] @@ -35,38 +35,21 @@ class TestLoader: defaultTestLoader: TestLoader if sys.version_info < (3, 13): - if sys.version_info >= (3, 11): - @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") - def getTestCaseNames( - testCaseClass: type[unittest.case.TestCase], - prefix: str, - sortUsing: _SortComparisonMethod = ..., - testNamePatterns: list[str] | None = None, - ) -> Sequence[str]: ... - @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") - def makeSuite( - testCaseClass: type[unittest.case.TestCase], - prefix: str = "test", - sortUsing: _SortComparisonMethod = ..., - suiteClass: _SuiteClass = ..., - ) -> unittest.suite.TestSuite: ... - @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") - def findTestCases( - module: ModuleType, prefix: str = "test", sortUsing: _SortComparisonMethod = ..., suiteClass: _SuiteClass = ... - ) -> unittest.suite.TestSuite: ... - else: - def getTestCaseNames( - testCaseClass: type[unittest.case.TestCase], - prefix: str, - sortUsing: _SortComparisonMethod = ..., - testNamePatterns: list[str] | None = None, - ) -> Sequence[str]: ... - def makeSuite( - testCaseClass: type[unittest.case.TestCase], - prefix: str = "test", - sortUsing: _SortComparisonMethod = ..., - suiteClass: _SuiteClass = ..., - ) -> unittest.suite.TestSuite: ... - def findTestCases( - module: ModuleType, prefix: str = "test", sortUsing: _SortComparisonMethod = ..., suiteClass: _SuiteClass = ... - ) -> unittest.suite.TestSuite: ... + @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") + def getTestCaseNames( + testCaseClass: type[unittest.case.TestCase], + prefix: str, + sortUsing: _SortComparisonMethod = ..., + testNamePatterns: list[str] | None = None, + ) -> Sequence[str]: ... + @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") + def makeSuite( + testCaseClass: type[unittest.case.TestCase], + prefix: str = "test", + sortUsing: _SortComparisonMethod = ..., + suiteClass: _SuiteClass = ..., + ) -> unittest.suite.TestSuite: ... + @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") + def findTestCases( + module: ModuleType, prefix: str = "test", sortUsing: _SortComparisonMethod = ..., suiteClass: _SuiteClass = ... + ) -> unittest.suite.TestSuite: ... diff --git a/mypy/typeshed/stdlib/unittest/main.pyi b/mypy/typeshed/stdlib/unittest/main.pyi index e1aeac32c5910..f48347c16ec39 100644 --- a/mypy/typeshed/stdlib/unittest/main.pyi +++ b/mypy/typeshed/stdlib/unittest/main.pyi @@ -64,11 +64,8 @@ class TestProgram: ) -> None: ... if sys.version_info < (3, 13): - if sys.version_info >= (3, 11): - @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") - def usageExit(self, msg: Any = None) -> None: ... - else: - def usageExit(self, msg: Any = None) -> None: ... + @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") + def usageExit(self, msg: Any = None) -> None: ... def parseArgs(self, argv: list[str]) -> None: ... def createTests(self, from_discovery: bool = False, Loader: unittest.loader.TestLoader | None = None) -> None: ... diff --git a/mypy/typeshed/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi index ef51d721297a1..1b6ab756d2533 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -3,8 +3,8 @@ from _typeshed import MaybeNone from collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping, Sequence from contextlib import _GeneratorContextManager from types import TracebackType -from typing import Any, ClassVar, Final, Generic, Literal, TypeVar, overload, type_check_only -from typing_extensions import ParamSpec, Self, TypeAlias, disjoint_base +from typing import Any, ClassVar, Final, Generic, Literal, ParamSpec, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self, disjoint_base _T = TypeVar("_T") _TT = TypeVar("_TT", bound=type[Any]) @@ -244,42 +244,29 @@ class _patch(Generic[_T]): additional_patchers: Any # If new==DEFAULT, self is _patch[Any]. Ideally we'd be able to add an overload for it so that self is _patch[MagicMock], # but that's impossible with the current type system. - if sys.version_info >= (3, 10): - def __init__( - self: _patch[_T], # pyright: ignore[reportInvalidTypeVarUse] #11780 - getter: Callable[[], Any], - attribute: str, - new: _T, - spec: Any | None, - create: bool, - spec_set: Any | None, - autospec: Any | None, - new_callable: Any | None, - kwargs: Mapping[str, Any], - *, - unsafe: bool = False, - ) -> None: ... - else: - def __init__( - self: _patch[_T], # pyright: ignore[reportInvalidTypeVarUse] #11780 - getter: Callable[[], Any], - attribute: str, - new: _T, - spec: Any | None, - create: bool, - spec_set: Any | None, - autospec: Any | None, - new_callable: Any | None, - kwargs: Mapping[str, Any], - ) -> None: ... - + def __init__( + self: _patch[_T], # pyright: ignore[reportInvalidTypeVarUse] #11780 + getter: Callable[[], Any], + attribute: str, + new: _T, + spec: Any | None, + create: bool, + spec_set: Any | None, + autospec: Any | None, + new_callable: Any | None, + kwargs: Mapping[str, Any], + *, + unsafe: bool = False, + ) -> None: ... def copy(self) -> _patch[_T]: ... + @overload def __call__(self, func: _TT) -> _TT: ... # If new==DEFAULT, this should add a MagicMock parameter to the function # arguments. See the _patch_default_new class below for this functionality. @overload def __call__(self, func: Callable[_P, _R]) -> Callable[_P, _R]: ... + def decoration_helper( self, patched: _patch[Any], args: Sequence[Any], keywargs: Any ) -> _GeneratorContextManager[tuple[Sequence[Any], Any]]: ... @@ -315,13 +302,11 @@ class _patch_dict: clear: Any def __init__(self, in_dict: Any, values: Any = (), clear: Any = False, **kwargs: Any) -> None: ... def __call__(self, f: Any) -> Any: ... - if sys.version_info >= (3, 10): - def decorate_callable(self, f: _F) -> _F: ... - def decorate_async_callable(self, f: _AF) -> _AF: ... - - def decorate_class(self, klass: Any) -> Any: ... def __enter__(self) -> Any: ... def __exit__(self, *args: object) -> Any: ... + def decorate_callable(self, f: _F) -> _F: ... + def decorate_async_callable(self, f: _AF) -> _AF: ... + def decorate_class(self, klass: Any) -> Any: ... start: Any stop: Any @@ -331,6 +316,7 @@ class _patch_dict: class _patcher: TEST_PREFIX: str dict: type[_patch_dict] + # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], # but that's impossible with the current type system. @@ -377,6 +363,7 @@ class _patcher: # kwargs are passed to the MagicMock/AsyncMock constructor **kwargs: Any, ) -> _patch_pass_arg[MagicMock | AsyncMock]: ... + # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], # but that's impossible with the current type system. @@ -426,6 +413,7 @@ class _patcher: # kwargs are passed to the MagicMock/AsyncMock constructor **kwargs: Any, ) -> _patch_pass_arg[MagicMock | AsyncMock]: ... + @overload @staticmethod def multiple( @@ -467,6 +455,7 @@ class _patcher: # The kwargs are the mock objects or DEFAULT **kwargs: Any, ) -> _patch[Any]: ... + @staticmethod def stopall() -> None: ... @@ -517,27 +506,16 @@ class _ANY(Any): ANY: _ANY -if sys.version_info >= (3, 10): - def create_autospec( - spec: Any, - spec_set: Any = False, - instance: Any = False, - _parent: Any | None = None, - _name: Any | None = None, - *, - unsafe: bool = False, - **kwargs: Any, - ) -> Any: ... - -else: - def create_autospec( - spec: Any, - spec_set: Any = False, - instance: Any = False, - _parent: Any | None = None, - _name: Any | None = None, - **kwargs: Any, - ) -> Any: ... +def create_autospec( + spec: Any, + spec_set: Any = False, + instance: Any = False, + _parent: Any | None = None, + _name: Any | None = None, + *, + unsafe: bool = False, + **kwargs: Any, +) -> Any: ... class _SpecState: spec: Any diff --git a/mypy/typeshed/stdlib/unittest/result.pyi b/mypy/typeshed/stdlib/unittest/result.pyi index 0761baaa2830b..081f6e1328e47 100644 --- a/mypy/typeshed/stdlib/unittest/result.pyi +++ b/mypy/typeshed/stdlib/unittest/result.pyi @@ -2,8 +2,7 @@ import sys import unittest.case from _typeshed import OptExcInfo from collections.abc import Callable -from typing import Any, Final, TextIO, TypeVar -from typing_extensions import TypeAlias +from typing import Any, Final, TextIO, TypeAlias, TypeVar _F = TypeVar("_F", bound=Callable[..., Any]) _DurationsType: TypeAlias = list[tuple[str, float]] diff --git a/mypy/typeshed/stdlib/unittest/runner.pyi b/mypy/typeshed/stdlib/unittest/runner.pyi index f76771f55e131..3a2e08749e9b6 100644 --- a/mypy/typeshed/stdlib/unittest/runner.pyi +++ b/mypy/typeshed/stdlib/unittest/runner.pyi @@ -4,8 +4,8 @@ import unittest.result import unittest.suite from _typeshed import SupportsFlush, SupportsWrite from collections.abc import Callable, Iterable -from typing import Any, Generic, Protocol, TypeVar, type_check_only -from typing_extensions import Never, TypeAlias +from typing import Any, Generic, Protocol, TypeAlias, TypeVar, type_check_only +from typing_extensions import Never from warnings import _ActionKind _ResultClassType: TypeAlias = Callable[[_TextTestStream, bool, int], TextTestResult[Any]] diff --git a/mypy/typeshed/stdlib/unittest/signals.pyi b/mypy/typeshed/stdlib/unittest/signals.pyi index a60133ada9d95..928ab68ae65d1 100644 --- a/mypy/typeshed/stdlib/unittest/signals.pyi +++ b/mypy/typeshed/stdlib/unittest/signals.pyi @@ -1,7 +1,6 @@ import unittest.result from collections.abc import Callable -from typing import TypeVar, overload -from typing_extensions import ParamSpec +from typing import ParamSpec, TypeVar, overload _P = ParamSpec("_P") _T = TypeVar("_T") @@ -9,6 +8,7 @@ _T = TypeVar("_T") def installHandler() -> None: ... def registerResult(result: unittest.result.TestResult) -> None: ... def removeResult(result: unittest.result.TestResult) -> bool: ... + @overload def removeHandler(method: None = None) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/unittest/suite.pyi b/mypy/typeshed/stdlib/unittest/suite.pyi index 443396164b6fe..b7cf75c682712 100644 --- a/mypy/typeshed/stdlib/unittest/suite.pyi +++ b/mypy/typeshed/stdlib/unittest/suite.pyi @@ -1,8 +1,7 @@ import unittest.case import unittest.result from collections.abc import Iterable, Iterator -from typing import ClassVar -from typing_extensions import TypeAlias +from typing import ClassVar, TypeAlias _TestType: TypeAlias = unittest.case.TestCase | TestSuite diff --git a/mypy/typeshed/stdlib/unittest/util.pyi b/mypy/typeshed/stdlib/unittest/util.pyi index 763c1478f5e6d..11a6f903932fb 100644 --- a/mypy/typeshed/stdlib/unittest/util.pyi +++ b/mypy/typeshed/stdlib/unittest/util.pyi @@ -1,6 +1,5 @@ from collections.abc import MutableSequence, Sequence -from typing import Any, Final, Literal, Protocol, TypeVar, type_check_only -from typing_extensions import TypeAlias +from typing import Any, Final, Literal, Protocol, TypeAlias, TypeVar, type_check_only @type_check_only class _SupportsDunderLT(Protocol): diff --git a/mypy/typeshed/stdlib/urllib/error.pyi b/mypy/typeshed/stdlib/urllib/error.pyi index 2173d7e6efaa5..6255f1ae7db0d 100644 --- a/mypy/typeshed/stdlib/urllib/error.pyi +++ b/mypy/typeshed/stdlib/urllib/error.pyi @@ -15,6 +15,7 @@ class HTTPError(URLError, addinfourl): def headers(self) -> Message: ... @headers.setter def headers(self, headers: Message) -> None: ... + @property def reason(self) -> str: ... # type: ignore[override] code: int diff --git a/mypy/typeshed/stdlib/urllib/parse.pyi b/mypy/typeshed/stdlib/urllib/parse.pyi index 364892ecdf698..b83a0f4e8678c 100644 --- a/mypy/typeshed/stdlib/urllib/parse.pyi +++ b/mypy/typeshed/stdlib/urllib/parse.pyi @@ -1,8 +1,8 @@ import sys from collections.abc import Iterable, Mapping, Sequence from types import GenericAlias -from typing import Any, AnyStr, Final, Generic, Literal, NamedTuple, Protocol, overload, type_check_only -from typing_extensions import TypeAlias +from typing import Any, AnyStr, Final, Generic, Literal, NamedTuple, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import TypeVar __all__ = [ "urlparse", @@ -38,6 +38,11 @@ scheme_chars: Final[str] if sys.version_info < (3, 11): MAX_CACHE_SIZE: Final[int] +_ResultStrT = TypeVar("_ResultStrT", str, bytes) +_ResultComponentT = TypeVar("_ResultComponentT", str, bytes, str | None, bytes | None) +_StrComponentT = TypeVar("_StrComponentT", str, str | None, default=str) +_BytesComponentT = TypeVar("_BytesComponentT", bytes, bytes | None, default=bytes) + class _ResultMixinStr: __slots__ = () def encode(self, encoding: str = "ascii", errors: str = "strict") -> _ResultMixinBytes: ... @@ -64,44 +69,88 @@ class _NetlocResultMixinStr(_NetlocResultMixinBase[str], _ResultMixinStr): class _NetlocResultMixinBytes(_NetlocResultMixinBase[bytes], _ResultMixinBytes): __slots__ = () -class _DefragResultBase(NamedTuple, Generic[AnyStr]): - url: AnyStr - fragment: AnyStr +# Need to duplicate the whole class because mypy rejects version-specific +# branches in namedtuple bodies. +if sys.version_info >= (3, 15): + class _DefragResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + url: _ResultStrT + fragment: _ResultComponentT + # Ignore needed due to mypy#21453. + def geturl(self) -> _ResultStrT: ... # type: ignore[misc] + +else: + class _DefragResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + url: _ResultStrT + fragment: _ResultComponentT + +if sys.version_info >= (3, 15): + class _SplitResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + scheme: _ResultComponentT + netloc: _ResultComponentT + path: _ResultStrT + query: _ResultComponentT + fragment: _ResultComponentT + # Ignore needed due to mypy#21453. + def geturl(self) -> _ResultStrT: ... # type: ignore[misc] + +else: + class _SplitResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + scheme: _ResultComponentT + netloc: _ResultComponentT + path: _ResultStrT + query: _ResultComponentT + fragment: _ResultComponentT + +if sys.version_info >= (3, 15): + class _ParseResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + scheme: _ResultComponentT + netloc: _ResultComponentT + path: _ResultStrT + params: _ResultComponentT + query: _ResultComponentT + fragment: _ResultComponentT + # Ignore needed due to mypy#21453. + def geturl(self) -> _ResultStrT: ... # type: ignore[misc] -class _SplitResultBase(NamedTuple, Generic[AnyStr]): - scheme: AnyStr - netloc: AnyStr - path: AnyStr - query: AnyStr - fragment: AnyStr +else: + class _ParseResultBase(NamedTuple, Generic[_ResultStrT, _ResultComponentT]): + scheme: _ResultComponentT + netloc: _ResultComponentT + path: _ResultStrT + params: _ResultComponentT + query: _ResultComponentT + fragment: _ResultComponentT -class _ParseResultBase(NamedTuple, Generic[AnyStr]): - scheme: AnyStr - netloc: AnyStr - path: AnyStr - params: AnyStr - query: AnyStr - fragment: AnyStr +if sys.version_info >= (3, 15): + # Structured result objects for string data + class DefragResult(_DefragResultBase[str, _StrComponentT], _ResultMixinStr, Generic[_StrComponentT]): ... + class SplitResult(_SplitResultBase[str, _StrComponentT], _NetlocResultMixinStr, Generic[_StrComponentT]): ... + class ParseResult(_ParseResultBase[str, _StrComponentT], _NetlocResultMixinStr, Generic[_StrComponentT]): ... + # Structured result objects for bytes data + class DefragResultBytes(_DefragResultBase[bytes, _BytesComponentT], _ResultMixinBytes, Generic[_BytesComponentT]): ... + class SplitResultBytes(_SplitResultBase[bytes, _BytesComponentT], _NetlocResultMixinBytes, Generic[_BytesComponentT]): ... + class ParseResultBytes(_ParseResultBase[bytes, _BytesComponentT], _NetlocResultMixinBytes, Generic[_BytesComponentT]): ... -# Structured result objects for string data -class DefragResult(_DefragResultBase[str], _ResultMixinStr): - def geturl(self) -> str: ... +else: + # Structured result objects for string data + class DefragResult(_DefragResultBase[str, str], _ResultMixinStr): + def geturl(self) -> str: ... -class SplitResult(_SplitResultBase[str], _NetlocResultMixinStr): - def geturl(self) -> str: ... + class SplitResult(_SplitResultBase[str, str], _NetlocResultMixinStr): + def geturl(self) -> str: ... -class ParseResult(_ParseResultBase[str], _NetlocResultMixinStr): - def geturl(self) -> str: ... + class ParseResult(_ParseResultBase[str, str], _NetlocResultMixinStr): + def geturl(self) -> str: ... -# Structured result objects for bytes data -class DefragResultBytes(_DefragResultBase[bytes], _ResultMixinBytes): - def geturl(self) -> bytes: ... + # Structured result objects for bytes data + class DefragResultBytes(_DefragResultBase[bytes, bytes], _ResultMixinBytes): + def geturl(self) -> bytes: ... -class SplitResultBytes(_SplitResultBase[bytes], _NetlocResultMixinBytes): - def geturl(self) -> bytes: ... + class SplitResultBytes(_SplitResultBase[bytes, bytes], _NetlocResultMixinBytes): + def geturl(self) -> bytes: ... -class ParseResultBytes(_ParseResultBase[bytes], _NetlocResultMixinBytes): - def geturl(self) -> bytes: ... + class ParseResultBytes(_ParseResultBase[bytes, bytes], _NetlocResultMixinBytes): + def geturl(self) -> bytes: ... def parse_qs( qs: AnyStr | None, @@ -121,22 +170,40 @@ def parse_qsl( max_num_fields: int | None = None, separator: str = "&", ) -> list[tuple[AnyStr, AnyStr]]: ... + @overload def quote(string: str, safe: str | Iterable[int] = "/", encoding: str | None = None, errors: str | None = None) -> str: ... @overload def quote(string: bytes | bytearray, safe: str | Iterable[int] = "/") -> str: ... + def quote_from_bytes(bs: bytes | bytearray, safe: str | Iterable[int] = "/") -> str: ... + @overload def quote_plus(string: str, safe: str | Iterable[int] = "", encoding: str | None = None, errors: str | None = None) -> str: ... @overload def quote_plus(string: bytes | bytearray, safe: str | Iterable[int] = "") -> str: ... + def unquote(string: str | bytes, encoding: str = "utf-8", errors: str = "replace") -> str: ... def unquote_to_bytes(string: str | bytes | bytearray) -> bytes: ... def unquote_plus(string: str, encoding: str = "utf-8", errors: str = "replace") -> str: ... + @overload def urldefrag(url: str) -> DefragResult: ... @overload def urldefrag(url: bytes | bytearray | None) -> DefragResultBytes: ... +if sys.version_info >= (3, 15): + @overload + def urldefrag(url: str, *, missing_as_none: Literal[True]) -> DefragResult[str | None]: ... + @overload + def urldefrag(url: str, *, missing_as_none: Literal[False] = False) -> DefragResult[str]: ... + @overload + def urldefrag(url: bytes | bytearray | None, *, missing_as_none: Literal[True]) -> DefragResultBytes[bytes | None]: ... + @overload + def urldefrag(url: bytes | bytearray | None, *, missing_as_none: Literal[False] = False) -> DefragResultBytes[bytes]: ... + @overload + def urldefrag(url: str, *, missing_as_none: bool) -> DefragResult[str | None]: ... + @overload + def urldefrag(url: bytes | bytearray | None, *, missing_as_none: bool) -> DefragResultBytes[bytes | None]: ... # The values are passed through `str()` (unless they are bytes), so anything is valid. _QueryType: TypeAlias = ( @@ -166,12 +233,51 @@ def urlencode( quote_via: _QuoteVia = ..., ) -> str: ... def urljoin(base: AnyStr, url: AnyStr | None, allow_fragments: bool = True) -> AnyStr: ... + @overload def urlparse(url: str, scheme: str = "", allow_fragments: bool = True) -> ParseResult: ... @overload def urlparse( url: bytes | bytearray | None, scheme: bytes | bytearray | None | Literal[""] = "", allow_fragments: bool = True ) -> ParseResultBytes: ... +if sys.version_info >= (3, 15): + @overload + def urlparse( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: Literal[True] + ) -> ParseResult[str | None]: ... + @overload + def urlparse( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: Literal[False] = False + ) -> ParseResult[str]: ... + @overload + def urlparse( + url: bytes | bytearray | None, + scheme: bytes | bytearray | None | Literal[""] = "", + allow_fragments: bool = True, + *, + missing_as_none: Literal[True], + ) -> ParseResultBytes[bytes | None]: ... + @overload + def urlparse( + url: bytes | bytearray | None, + scheme: bytes | bytearray | None | Literal[""] = "", + allow_fragments: bool = True, + *, + missing_as_none: Literal[False] = False, + ) -> ParseResultBytes[bytes]: ... + @overload + def urlparse( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: bool + ) -> ParseResult[str | None]: ... + @overload + def urlparse( + url: bytes | bytearray | None, + scheme: bytes | bytearray | None | Literal[""] = "", + allow_fragments: bool = True, + *, + missing_as_none: bool, + ) -> ParseResultBytes[bytes | None]: ... + @overload def urlsplit(url: str, scheme: str = "", allow_fragments: bool = True) -> SplitResult: ... @@ -180,22 +286,69 @@ if sys.version_info >= (3, 11): def urlsplit( url: bytes | None, scheme: bytes | None | Literal[""] = "", allow_fragments: bool = True ) -> SplitResultBytes: ... - else: @overload def urlsplit( url: bytes | bytearray | None, scheme: bytes | bytearray | None | Literal[""] = "", allow_fragments: bool = True ) -> SplitResultBytes: ... +if sys.version_info >= (3, 15): + @overload + def urlsplit( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: Literal[True] + ) -> SplitResult[str | None]: ... + @overload + def urlsplit( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: Literal[False] = False + ) -> SplitResult[str]: ... + @overload + def urlsplit( + url: bytes | None, + scheme: bytes | None | Literal[""] = "", + allow_fragments: bool = True, + *, + missing_as_none: Literal[True], + ) -> SplitResultBytes[bytes | None]: ... + @overload + def urlsplit( + url: bytes | None, + scheme: bytes | None | Literal[""] = "", + allow_fragments: bool = True, + *, + missing_as_none: Literal[False] = False, + ) -> SplitResultBytes[bytes]: ... + @overload + def urlsplit( + url: str, scheme: str = "", allow_fragments: bool = True, *, missing_as_none: bool + ) -> SplitResult[str | None]: ... + @overload + def urlsplit( + url: bytes | None, scheme: bytes | None | Literal[""] = "", allow_fragments: bool = True, *, missing_as_none: bool + ) -> SplitResultBytes[bytes | None]: ... -# Requires an iterable of length 6 -@overload -def urlunparse(components: Iterable[None]) -> Literal[b""]: ... # type: ignore[overload-overlap] -@overload -def urlunparse(components: Iterable[AnyStr | None]) -> AnyStr: ... +if sys.version_info >= (3, 15): + # Requires an iterable of length 6 + @overload + def urlunparse(components: Iterable[None], *, keep_empty: bool = ...) -> Literal[b""]: ... # type: ignore[overload-overlap] + @overload + def urlunparse(components: Iterable[AnyStr | None], *, keep_empty: bool = ...) -> AnyStr: ... +else: + # Requires an iterable of length 6 + @overload + def urlunparse(components: Iterable[None]) -> Literal[b""]: ... # type: ignore[overload-overlap] + @overload + def urlunparse(components: Iterable[AnyStr | None]) -> AnyStr: ... + +if sys.version_info >= (3, 15): + # Requires an iterable of length 5 + @overload + def urlunsplit(components: Iterable[None], *, keep_empty: bool = ...) -> Literal[b""]: ... # type: ignore[overload-overlap] + @overload + def urlunsplit(components: Iterable[AnyStr | None], *, keep_empty: bool = ...) -> AnyStr: ... +else: + # Requires an iterable of length 5 + @overload + def urlunsplit(components: Iterable[None]) -> Literal[b""]: ... # type: ignore[overload-overlap] + @overload + def urlunsplit(components: Iterable[AnyStr | None]) -> AnyStr: ... -# Requires an iterable of length 5 -@overload -def urlunsplit(components: Iterable[None]) -> Literal[b""]: ... # type: ignore[overload-overlap] -@overload -def urlunsplit(components: Iterable[AnyStr | None]) -> AnyStr: ... def unwrap(url: str) -> str: ... diff --git a/mypy/typeshed/stdlib/urllib/request.pyi b/mypy/typeshed/stdlib/urllib/request.pyi index d6bb2f9647824..0ec26052b23c6 100644 --- a/mypy/typeshed/stdlib/urllib/request.pyi +++ b/mypy/typeshed/stdlib/urllib/request.pyi @@ -6,8 +6,8 @@ from email.message import Message from http.client import HTTPConnection, HTTPMessage, HTTPResponse from http.cookiejar import CookieJar from re import Pattern -from typing import IO, Any, ClassVar, Literal, NoReturn, Protocol, TypeVar, overload, type_check_only -from typing_extensions import TypeAlias, deprecated +from typing import IO, Any, ClassVar, Literal, NoReturn, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import deprecated from urllib.error import HTTPError as HTTPError from urllib.response import addclosehook, addinfourl @@ -124,6 +124,7 @@ class Request: def full_url(self, value: str) -> None: ... @full_url.deleter def full_url(self) -> None: ... + type: str host: str origin_req_host: str @@ -150,10 +151,12 @@ class Request: def remove_header(self, header_name: str) -> None: ... def get_full_url(self) -> str: ... def set_proxy(self, host: str, type: str) -> None: ... + @overload def get_header(self, header_name: str) -> str | None: ... @overload def get_header(self, header_name: str, default: _T) -> str | _T: ... + def header_items(self) -> list[tuple[str, str]]: ... def has_proxy(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/uu.pyi b/mypy/typeshed/stdlib/uu.pyi index 324053e04337c..62bf6cb05f59d 100644 --- a/mypy/typeshed/stdlib/uu.pyi +++ b/mypy/typeshed/stdlib/uu.pyi @@ -1,5 +1,4 @@ -from typing import BinaryIO -from typing_extensions import TypeAlias +from typing import BinaryIO, TypeAlias __all__ = ["Error", "encode", "decode"] diff --git a/mypy/typeshed/stdlib/uuid.pyi b/mypy/typeshed/stdlib/uuid.pyi index 055f4def311cd..06285e03aea7e 100644 --- a/mypy/typeshed/stdlib/uuid.pyi +++ b/mypy/typeshed/stdlib/uuid.pyi @@ -2,8 +2,8 @@ import builtins import sys from _typeshed import Unused from enum import Enum -from typing import Final, NoReturn -from typing_extensions import LiteralString, TypeAlias +from typing import Final, NoReturn, TypeAlias +from typing_extensions import LiteralString _FieldsType: TypeAlias = tuple[int, int, int, int, int, int] diff --git a/mypy/typeshed/stdlib/warnings.pyi b/mypy/typeshed/stdlib/warnings.pyi index 49c98cb07540e..da281e38ddd0b 100644 --- a/mypy/typeshed/stdlib/warnings.pyi +++ b/mypy/typeshed/stdlib/warnings.pyi @@ -3,8 +3,8 @@ import sys from _warnings import warn as warn, warn_explicit as warn_explicit from collections.abc import Sequence from types import ModuleType, TracebackType -from typing import Any, Generic, Literal, TextIO, overload -from typing_extensions import LiteralString, TypeAlias, TypeVar +from typing import Any, Generic, Literal, TextIO, TypeAlias, overload +from typing_extensions import LiteralString, TypeVar __all__ = [ "warn", @@ -56,16 +56,32 @@ class WarningMessage: file: TextIO | None line: str | None source: Any | None - def __init__( - self, - message: Warning | str, - category: type[Warning], - filename: str, - lineno: int, - file: TextIO | None = None, - line: str | None = None, - source: Any | None = None, - ) -> None: ... + if sys.version_info >= (3, 15): + module: str | None + if sys.version_info >= (3, 15): + def __init__( + self, + message: Warning | str, + category: type[Warning], + filename: str, + lineno: int, + file: TextIO | None = None, + line: str | None = None, + source: Any | None = None, + module: str | None = None, + ) -> None: ... + + else: + def __init__( + self, + message: Warning | str, + category: type[Warning], + filename: str, + lineno: int, + file: TextIO | None = None, + line: str | None = None, + source: Any | None = None, + ) -> None: ... class catch_warnings(Generic[_W_co]): if sys.version_info >= (3, 11): diff --git a/mypy/typeshed/stdlib/wave.pyi b/mypy/typeshed/stdlib/wave.pyi index fd7dbfade884b..6ed91b097dbab 100644 --- a/mypy/typeshed/stdlib/wave.pyi +++ b/mypy/typeshed/stdlib/wave.pyi @@ -1,15 +1,20 @@ import sys from _typeshed import ReadableBuffer, Unused -from typing import IO, Any, BinaryIO, Final, Literal, NamedTuple, NoReturn, overload -from typing_extensions import Self, TypeAlias, deprecated +from typing import IO, Any, BinaryIO, Final, Literal, NamedTuple, NoReturn, TypeAlias, overload +from typing_extensions import Self, deprecated __all__ = ["open", "Error", "Wave_read", "Wave_write"] +if sys.version_info >= (3, 15): + __all__ += ["WAVE_FORMAT_PCM", "WAVE_FORMAT_IEEE_FLOAT", "WAVE_FORMAT_EXTENSIBLE"] _File: TypeAlias = str | IO[bytes] class Error(Exception): ... WAVE_FORMAT_PCM: Final = 0x0001 +if sys.version_info >= (3, 15): + WAVE_FORMAT_IEEE_FLOAT: Final = 0x0003 + WAVE_FORMAT_EXTENSIBLE: Final = 0xFFFE class _wave_params(NamedTuple): nchannels: int @@ -32,17 +37,17 @@ class Wave_read: def getnframes(self) -> int: ... def getsampwidth(self) -> int: ... def getframerate(self) -> int: ... + if sys.version_info >= (3, 15): + def getformat(self) -> int: ... + def getcomptype(self) -> str: ... def getcompname(self) -> str: ... def getparams(self) -> _wave_params: ... - if sys.version_info >= (3, 13): + if sys.version_info < (3, 15): @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") def getmarkers(self) -> None: ... @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") def getmark(self, id: Any) -> NoReturn: ... - else: - def getmarkers(self) -> None: ... - def getmark(self, id: Any) -> NoReturn: ... def setpos(self, pos: int) -> None: ... def readframes(self, nframes: int) -> bytes: ... @@ -58,24 +63,31 @@ class Wave_write: def getsampwidth(self) -> int: ... def setframerate(self, framerate: float) -> None: ... def getframerate(self) -> int: ... + if sys.version_info >= (3, 15): + def setformat(self, format: int) -> None: ... + def getformat(self) -> int: ... + def setnframes(self, nframes: int) -> None: ... def getnframes(self) -> int: ... def setcomptype(self, comptype: str, compname: str) -> None: ... def getcomptype(self) -> str: ... def getcompname(self) -> str: ... - def setparams(self, params: _wave_params | tuple[int, int, int, int, str, str]) -> None: ... + if sys.version_info >= (3, 15): + def setparams( + self, params: _wave_params | tuple[int, int, int, int, str, str] | tuple[int, int, int, int, str, str, int] + ) -> None: ... + else: + def setparams(self, params: _wave_params | tuple[int, int, int, int, str, str]) -> None: ... + def getparams(self) -> _wave_params: ... - if sys.version_info >= (3, 13): + + if sys.version_info < (3, 15): @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") def setmark(self, id: Any, pos: Any, name: Any) -> NoReturn: ... @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") def getmark(self, id: Any) -> NoReturn: ... @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") def getmarkers(self) -> None: ... - else: - def setmark(self, id: Any, pos: Any, name: Any) -> NoReturn: ... - def getmark(self, id: Any) -> NoReturn: ... - def getmarkers(self) -> None: ... def tell(self) -> int: ... def writeframesraw(self, data: ReadableBuffer) -> None: ... diff --git a/mypy/typeshed/stdlib/weakref.pyi b/mypy/typeshed/stdlib/weakref.pyi index 76ab86b957a13..3308ae42e1cfb 100644 --- a/mypy/typeshed/stdlib/weakref.pyi +++ b/mypy/typeshed/stdlib/weakref.pyi @@ -3,8 +3,8 @@ from _weakref import getweakrefcount as getweakrefcount, getweakrefs as getweakr from _weakrefset import WeakSet as WeakSet from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping from types import GenericAlias -from typing import Any, ClassVar, Generic, TypeVar, final, overload -from typing_extensions import ParamSpec, Self, disjoint_base +from typing import Any, ClassVar, Generic, ParamSpec, TypeVar, final, overload +from typing_extensions import Self, disjoint_base __all__ = [ "ref", @@ -89,6 +89,7 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): /, **kwargs: _VT, ) -> None: ... + def __len__(self) -> int: ... def __getitem__(self, key: _KT) -> _VT: ... def __setitem__(self, key: _KT, value: _VT) -> None: ... @@ -98,12 +99,14 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): def copy(self) -> WeakValueDictionary[_KT, _VT]: ... __copy__ = copy def __deepcopy__(self, memo: Any) -> Self: ... + @overload def get(self, key: _KT, default: None = None) -> _VT | None: ... @overload def get(self, key: _KT, default: _VT) -> _VT: ... @overload def get(self, key: _KT, default: _T) -> _VT | _T: ... + # These are incompatible with Mapping def keys(self) -> Iterator[_KT]: ... # type: ignore[override] def values(self) -> Iterator[_VT]: ... # type: ignore[override] @@ -111,20 +114,24 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): def itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: ... def valuerefs(self) -> list[KeyedRef[_KT, _VT]]: ... def setdefault(self, key: _KT, default: _VT) -> _VT: ... + @overload def pop(self, key: _KT) -> _VT: ... @overload def pop(self, key: _KT, default: _VT) -> _VT: ... @overload def pop(self, key: _KT, default: _T) -> _VT | _T: ... + @overload def update(self, other: SupportsKeysAndGetItem[_KT, _VT], /, **kwargs: _VT) -> None: ... @overload def update(self, other: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None: ... @overload def update(self, other: None = None, /, **kwargs: _VT) -> None: ... + def __or__(self, other: Mapping[_T1, _T2]) -> WeakValueDictionary[_KT | _T1, _VT | _T2]: ... def __ror__(self, other: Mapping[_T1, _T2]) -> WeakValueDictionary[_KT | _T1, _VT | _T2]: ... + # WeakValueDictionary.__ior__ should be kept roughly in line with MutableMapping.update() @overload # type: ignore[misc] def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... @@ -142,6 +149,7 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def __init__(self, dict: None = None) -> None: ... @overload def __init__(self, dict: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]]) -> None: ... + def __len__(self) -> int: ... def __getitem__(self, key: _KT) -> _VT: ... def __setitem__(self, key: _KT, value: _VT) -> None: ... @@ -151,36 +159,43 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def copy(self) -> WeakKeyDictionary[_KT, _VT]: ... __copy__ = copy def __deepcopy__(self, memo: Any) -> Self: ... + @overload def get(self, key: _KT, default: None = None) -> _VT | None: ... @overload def get(self, key: _KT, default: _VT) -> _VT: ... @overload def get(self, key: _KT, default: _T) -> _VT | _T: ... + # These are incompatible with Mapping def keys(self) -> Iterator[_KT]: ... # type: ignore[override] def values(self) -> Iterator[_VT]: ... # type: ignore[override] def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override] def keyrefs(self) -> list[ref[_KT]]: ... + # Keep WeakKeyDictionary.setdefault in line with MutableMapping.setdefault, modulo positional-only differences @overload def setdefault(self: WeakKeyDictionary[_KT, _VT | None], key: _KT, default: None = None) -> _VT: ... @overload def setdefault(self, key: _KT, default: _VT) -> _VT: ... + @overload def pop(self, key: _KT) -> _VT: ... @overload def pop(self, key: _KT, default: _VT) -> _VT: ... @overload def pop(self, key: _KT, default: _T) -> _VT | _T: ... + @overload def update(self, dict: SupportsKeysAndGetItem[_KT, _VT], /, **kwargs: _VT) -> None: ... @overload def update(self, dict: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None: ... @overload def update(self, dict: None = None, /, **kwargs: _VT) -> None: ... + def __or__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ... def __ror__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ... + # WeakKeyDictionary.__ior__ should be kept roughly in line with MutableMapping.update() @overload # type: ignore[misc] def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... diff --git a/mypy/typeshed/stdlib/webbrowser.pyi b/mypy/typeshed/stdlib/webbrowser.pyi index 56c30f8727277..40b57c3c6a097 100644 --- a/mypy/typeshed/stdlib/webbrowser.pyi +++ b/mypy/typeshed/stdlib/webbrowser.pyi @@ -64,16 +64,10 @@ if sys.platform == "win32": if sys.platform == "darwin": if sys.version_info < (3, 13): - if sys.version_info >= (3, 11): - @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") - class MacOSX(BaseBrowser): - def __init__(self, name: str) -> None: ... - def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... - - else: - class MacOSX(BaseBrowser): - def __init__(self, name: str) -> None: ... - def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... + @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") + class MacOSX(BaseBrowser): + def __init__(self, name: str) -> None: ... + def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... class MacOSXOSAScript(BaseBrowser): # In runtime this class does not have `name` and `basename` if sys.version_info >= (3, 11): diff --git a/mypy/typeshed/stdlib/winreg.pyi b/mypy/typeshed/stdlib/winreg.pyi index a654bbcdfb615..8a886112f8a14 100644 --- a/mypy/typeshed/stdlib/winreg.pyi +++ b/mypy/typeshed/stdlib/winreg.pyi @@ -1,8 +1,8 @@ import sys from _typeshed import ReadableBuffer, Unused from types import TracebackType -from typing import Any, Final, Literal, final, overload -from typing_extensions import Self, TypeAlias +from typing import Any, Final, Literal, TypeAlias, final, overload +from typing_extensions import Self if sys.platform == "win32": _KeyType: TypeAlias = HKEYType | int @@ -12,6 +12,9 @@ if sys.platform == "win32": def CreateKeyEx(key: _KeyType, sub_key: str | None, reserved: int = 0, access: int = 131078) -> HKEYType: ... def DeleteKey(key: _KeyType, sub_key: str, /) -> None: ... def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = 256, reserved: int = 0) -> None: ... + if sys.version_info >= (3, 15): + def DeleteTree(key: _KeyType, sub_key: str | None = None, /) -> None: ... + def DeleteValue(key: _KeyType, value: str, /) -> None: ... def EnumKey(key: _KeyType, index: int, /) -> str: ... def EnumValue(key: _KeyType, index: int, /) -> tuple[str, Any, int]: ... @@ -25,6 +28,7 @@ if sys.platform == "win32": def QueryValueEx(key: _KeyType, name: str, /) -> tuple[Any, int]: ... def SaveKey(key: _KeyType, file_name: str, /) -> None: ... def SetValue(key: _KeyType, sub_key: str | None, type: int, value: str, /) -> None: ... + @overload # type=REG_DWORD|REG_QWORD def SetValueEx( key: _KeyType, value_name: str | None, reserved: Unused, type: Literal[4, 5], value: int | None, / @@ -55,6 +59,7 @@ if sys.platform == "win32": value: int | str | list[str] | ReadableBuffer | None, /, ) -> None: ... + def DisableReflectionKey(key: _KeyType, /) -> None: ... def EnableReflectionKey(key: _KeyType, /) -> None: ... def QueryReflectionKey(key: _KeyType, /) -> bool: ... diff --git a/mypy/typeshed/stdlib/winsound.pyi b/mypy/typeshed/stdlib/winsound.pyi index 39dfa7b8b9c42..9c7f314fd6ca4 100644 --- a/mypy/typeshed/stdlib/winsound.pyi +++ b/mypy/typeshed/stdlib/winsound.pyi @@ -30,9 +30,11 @@ if sys.platform == "win32": MB_ICONWARNING: Final = 48 def Beep(frequency: int, duration: int) -> None: ... + # Can actually accept anything ORed with 4, and if not it's definitely str, but that's inexpressible @overload def PlaySound(sound: ReadableBuffer | None, flags: Literal[4]) -> None: ... @overload def PlaySound(sound: str | ReadableBuffer | None, flags: int) -> None: ... + def MessageBeep(type: int = 0) -> None: ... diff --git a/mypy/typeshed/stdlib/wsgiref/headers.pyi b/mypy/typeshed/stdlib/wsgiref/headers.pyi index 9febad4b32775..6a0fb571a0d08 100644 --- a/mypy/typeshed/stdlib/wsgiref/headers.pyi +++ b/mypy/typeshed/stdlib/wsgiref/headers.pyi @@ -1,6 +1,5 @@ from re import Pattern -from typing import Final, overload -from typing_extensions import TypeAlias +from typing import Final, TypeAlias, overload _HeaderList: TypeAlias = list[tuple[str, str]] @@ -14,10 +13,12 @@ class Headers: def __getitem__(self, name: str) -> str | None: ... def __contains__(self, name: str) -> bool: ... def get_all(self, name: str) -> list[str]: ... + @overload def get(self, name: str, default: str) -> str: ... @overload def get(self, name: str, default: str | None = None) -> str | None: ... + def keys(self) -> list[str]: ... def values(self) -> list[str]: ... def items(self) -> _HeaderList: ... diff --git a/mypy/typeshed/stdlib/wsgiref/types.pyi b/mypy/typeshed/stdlib/wsgiref/types.pyi index 57276fd05ea84..b7fd998098568 100644 --- a/mypy/typeshed/stdlib/wsgiref/types.pyi +++ b/mypy/typeshed/stdlib/wsgiref/types.pyi @@ -1,7 +1,6 @@ from _typeshed import OptExcInfo from collections.abc import Callable, Iterable, Iterator -from typing import Any, Protocol -from typing_extensions import TypeAlias +from typing import Any, Protocol, TypeAlias __all__ = ["StartResponse", "WSGIEnvironment", "WSGIApplication", "InputStream", "ErrorStream", "FileWrapper"] diff --git a/mypy/typeshed/stdlib/wsgiref/validate.pyi b/mypy/typeshed/stdlib/wsgiref/validate.pyi index fa8a6bbb8d039..498e03aa36731 100644 --- a/mypy/typeshed/stdlib/wsgiref/validate.pyi +++ b/mypy/typeshed/stdlib/wsgiref/validate.pyi @@ -1,7 +1,6 @@ from _typeshed.wsgi import ErrorStream, InputStream, WSGIApplication from collections.abc import Callable, Iterable, Iterator -from typing import Any, NoReturn -from typing_extensions import TypeAlias +from typing import Any, NoReturn, TypeAlias __all__ = ["validator"] diff --git a/mypy/typeshed/stdlib/xml/__init__.pyi b/mypy/typeshed/stdlib/xml/__init__.pyi index 7a240965136e5..555d9b8f90a95 100644 --- a/mypy/typeshed/stdlib/xml/__init__.pyi +++ b/mypy/typeshed/stdlib/xml/__init__.pyi @@ -1,3 +1,9 @@ # At runtime, listing submodules in __all__ without them being imported is # valid, and causes them to be included in a star import. See #6523 +import sys + __all__ = ["dom", "parsers", "sax", "etree"] # noqa: F822 # pyright: ignore[reportUnsupportedDunderAll] + +if sys.version_info >= (3, 15): + __all__ += ["is_valid_name"] # pyright: ignore[reportUnsupportedDunderAll] + from xml.utils import is_valid_name as is_valid_name, is_valid_text as is_valid_text diff --git a/mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi b/mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi index 2b9ac88769700..e410671829358 100644 --- a/mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi +++ b/mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi @@ -1,6 +1,5 @@ from _typeshed import ReadableBuffer, SupportsRead -from typing import Any, Final, NoReturn -from typing_extensions import TypeAlias +from typing import Any, Final, NoReturn, TypeAlias from xml.dom.minidom import Document, DocumentFragment, DOMImplementation, Element, Node, TypeInfo from xml.dom.xmlbuilder import DOMBuilderFilter, Options from xml.parsers.expat import XMLParserType diff --git a/mypy/typeshed/stdlib/xml/dom/minidom.pyi b/mypy/typeshed/stdlib/xml/dom/minidom.pyi index e0431417aa3c0..c54b0de86e556 100644 --- a/mypy/typeshed/stdlib/xml/dom/minidom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/minidom.pyi @@ -3,8 +3,8 @@ from _collections_abc import dict_keys, dict_values from _typeshed import Incomplete, ReadableBuffer, SupportsRead, SupportsWrite from collections.abc import Iterable, Sequence from types import TracebackType -from typing import Any, ClassVar, Generic, Literal, NoReturn, Protocol, TypeVar, overload, type_check_only -from typing_extensions import Self, TypeAlias +from typing import Any, ClassVar, Generic, Literal, NoReturn, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Self from xml.dom.minicompat import EmptyNodeList, NodeList from xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS from xml.sax.xmlreader import XMLReader @@ -52,6 +52,7 @@ def parse( file: str | SupportsRead[ReadableBuffer | str], parser: XMLReader | None = None, bufsize: int | None = None ) -> Document: ... def parseString(string: str | ReadableBuffer, parser: XMLReader | None = None) -> Document: ... + @overload def getDOMImplementation(features: None = None) -> DOMImplementation: ... @overload @@ -89,10 +90,12 @@ class Node(xml.dom.Node): @property def localName(self) -> str | None: ... # non-null only for Element and Attr def __bool__(self) -> Literal[True]: ... + @overload def toxml(self, encoding: str, standalone: bool | None = None) -> bytes: ... @overload def toxml(self, encoding: None = None, standalone: bool | None = None) -> str: ... + @overload def toprettyxml( self, @@ -122,6 +125,7 @@ class Node(xml.dom.Node): encoding: str, standalone: bool | None = None, ) -> bytes: ... + def hasChildNodes(self) -> bool: ... def insertBefore( # type: ignore[misc] self: _NodesWithChildren, # pyright: ignore[reportGeneralTypeIssues] @@ -131,6 +135,7 @@ class Node(xml.dom.Node): def appendChild( # type: ignore[misc] self: _NodesWithChildren, node: _ChildNodePlusFragmentVar # pyright: ignore[reportGeneralTypeIssues] ) -> _ChildNodePlusFragmentVar: ... + @overload def replaceChild( # type: ignore[misc] self: _NodesWithChildren, newChild: DocumentFragment, oldChild: _ChildNodeVar @@ -139,6 +144,7 @@ class Node(xml.dom.Node): def replaceChild( # type: ignore[misc] self: _NodesWithChildren, newChild: _NodesThatAreChildren, oldChild: _ChildNodeVar ) -> _ChildNodeVar | None: ... + def removeChild(self: _NodesWithChildren, oldChild: _ChildNodeVar) -> _ChildNodeVar: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] def normalize(self: _NodesWithChildren) -> None: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] def cloneNode(self, deep: bool) -> Self | None: ... @@ -178,10 +184,12 @@ class DocumentFragment(Node): self, newChild: _DFChildrenPlusFragment, refChild: _DocumentFragmentChildren | None ) -> _DFChildrenPlusFragment: ... def appendChild(self, node: _DFChildrenPlusFragment) -> _DFChildrenPlusFragment: ... # type: ignore[override] + @overload # type: ignore[override] def replaceChild(self, newChild: DocumentFragment, oldChild: _DFChildrenVar) -> _DFChildrenVar | DocumentFragment: ... @overload def replaceChild(self, newChild: _DocumentFragmentChildren, oldChild: _DFChildrenVar) -> _DFChildrenVar | None: ... # type: ignore[override] + def removeChild(self, oldChild: _DFChildrenVar) -> _DFChildrenVar: ... # type: ignore[override] _AttrChildrenVar = TypeVar("_AttrChildrenVar", bound=_AttrChildren) @@ -223,10 +231,12 @@ class Attr(Node): def schemaType(self) -> TypeInfo: ... def insertBefore(self, newChild: _AttrChildrenPlusFragment, refChild: _AttrChildren | None) -> _AttrChildrenPlusFragment: ... # type: ignore[override] def appendChild(self, node: _AttrChildrenPlusFragment) -> _AttrChildrenPlusFragment: ... # type: ignore[override] + @overload # type: ignore[override] def replaceChild(self, newChild: DocumentFragment, oldChild: _AttrChildrenVar) -> _AttrChildrenVar | DocumentFragment: ... @overload def replaceChild(self, newChild: _AttrChildren, oldChild: _AttrChildrenVar) -> _AttrChildrenVar | None: ... # type: ignore[override] + def removeChild(self, oldChild: _AttrChildrenVar) -> _AttrChildrenVar: ... # type: ignore[override] # In the DOM, this interface isn't specific to Attr, but our implementation is @@ -339,12 +349,14 @@ class Element(Node): self, newChild: _ElementChildrenPlusFragment, refChild: _ElementChildren | None ) -> _ElementChildrenPlusFragment: ... def appendChild(self, node: _ElementChildrenPlusFragment) -> _ElementChildrenPlusFragment: ... # type: ignore[override] + @overload # type: ignore[override] def replaceChild( self, newChild: DocumentFragment, oldChild: _ElementChildrenVar ) -> _ElementChildrenVar | DocumentFragment: ... @overload def replaceChild(self, newChild: _ElementChildren, oldChild: _ElementChildrenVar) -> _ElementChildrenVar | None: ... # type: ignore[override] + def removeChild(self, oldChild: _ElementChildrenVar) -> _ElementChildrenVar: ... # type: ignore[override] class Childless: @@ -661,15 +673,18 @@ class Document(Node, DocumentLS): encoding: str | None = None, standalone: bool | None = None, ) -> None: ... + @overload def renameNode(self, n: Element, namespaceURI: str, name: str) -> Element: ... @overload def renameNode(self, n: Attr, namespaceURI: str, name: str) -> Attr: ... @overload def renameNode(self, n: Element | Attr, namespaceURI: str, name: str) -> Element | Attr: ... + def insertBefore( self, newChild: _DocumentChildrenPlusFragment, refChild: _DocumentChildren | None # type: ignore[override] ) -> _DocumentChildrenPlusFragment: ... + @overload # type: ignore[override] def replaceChild( self, newChild: DocumentFragment, oldChild: _DocumentChildrenVar diff --git a/mypy/typeshed/stdlib/xml/dom/pulldom.pyi b/mypy/typeshed/stdlib/xml/dom/pulldom.pyi index df7a3ad0eddb0..4ede390155855 100644 --- a/mypy/typeshed/stdlib/xml/dom/pulldom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/pulldom.pyi @@ -1,8 +1,8 @@ import sys from _typeshed import Incomplete, Unused from collections.abc import MutableSequence, Sequence -from typing import Final, Literal, NoReturn -from typing_extensions import Self, TypeAlias +from typing import Final, Literal, NoReturn, TypeAlias +from typing_extensions import Self from xml.dom.minidom import Comment, Document, DOMImplementation, Element, ProcessingInstruction, Text from xml.sax import _SupportsReadClose from xml.sax.handler import ContentHandler diff --git a/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi b/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi index 10784e7d40214..5db08fb0df053 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi @@ -22,6 +22,7 @@ class FatalIncludeError(SyntaxError): ... def default_loader(href: FileDescriptorOrPath, parse: Literal["xml"], encoding: str | None = None) -> Element: ... @overload def default_loader(href: FileDescriptorOrPath, parse: Literal["text"], encoding: str | None = None) -> str: ... + def include(elem: Element, loader: _Loader | None = None, base_url: str | None = None, max_depth: int | None = 6) -> None: ... class LimitedRecursiveIncludeError(FatalIncludeError): ... diff --git a/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi b/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi index 5c03dd014b639..1dd6f86cead63 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi @@ -1,7 +1,6 @@ from collections.abc import Callable, Generator, Iterable from re import Pattern -from typing import Any, Final, Literal, TypeVar, overload -from typing_extensions import TypeAlias +from typing import Any, Final, Literal, TypeAlias, TypeVar, overload from xml.etree.ElementTree import Element xpath_tokenizer_re: Final[Pattern[str]] @@ -33,8 +32,10 @@ def iterfind( # type: ignore[overload-overlap] ) -> None: ... @overload def iterfind(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> Generator[Element]: ... + def find(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> Element | None: ... def findall(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ... + @overload def findtext(elem: Element[Any], path: str, default: None = None, namespaces: dict[str, str] | None = None) -> str | None: ... @overload diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index 6340a44bd51c8..c77af2cb4dd11 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -2,8 +2,8 @@ import sys from _collections_abc import dict_keys from _typeshed import FileDescriptorOrPath, ReadableBuffer, SupportsRead, SupportsWrite from collections.abc import Callable, Generator, ItemsView, Iterable, Iterator, Mapping, Sequence -from typing import Any, Final, Generic, Literal, Protocol, SupportsIndex, TypeVar, overload, type_check_only -from typing_extensions import TypeAlias, TypeGuard, deprecated, disjoint_base +from typing import Any, Final, Generic, Literal, Protocol, SupportsIndex, TypeAlias, TypeGuard, TypeVar, overload, type_check_only +from typing_extensions import deprecated, disjoint_base from xml.parsers.expat import XMLParserType __all__ = [ @@ -27,13 +27,14 @@ __all__ = [ "tostring", "tostringlist", "TreeBuilder", - "VERSION", "XML", "XMLID", "XMLParser", "XMLPullParser", "register_namespace", ] +if sys.version_info < (3, 15): + __all__ += ["VERSION"] _T = TypeVar("_T") _FileRead: TypeAlias = FileDescriptorOrPath | SupportsRead[bytes] | SupportsRead[str] @@ -48,6 +49,7 @@ class ParseError(SyntaxError): # In reality it works based on `.tag` attribute duck typing. def iselement(element: object) -> TypeGuard[Element]: ... + @overload def canonicalize( xml_data: str | ReadableBuffer | None = None, @@ -96,21 +98,26 @@ class Element(Generic[_Tag]): def extend(self, elements: Iterable[Element[Any]], /) -> None: ... def find(self, path: str, namespaces: dict[str, str] | None = None) -> Element | None: ... def findall(self, path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ... + @overload def findtext(self, path: str, default: None = None, namespaces: dict[str, str] | None = None) -> str | None: ... @overload def findtext(self, path: str, default: _T, namespaces: dict[str, str] | None = None) -> _T | str: ... + @overload def get(self, key: str, default: None = None) -> str | None: ... @overload def get(self, key: str, default: _T) -> str | _T: ... + def insert(self, index: int, subelement: Element[Any], /) -> None: ... def items(self) -> ItemsView[str, str]: ... def iter(self, tag: str | None = None) -> Generator[Element]: ... + @overload def iterfind(self, path: Literal[""], namespaces: dict[str, str] | None = None) -> None: ... # type: ignore[overload-overlap] @overload def iterfind(self, path: str, namespaces: dict[str, str] | None = None) -> Generator[Element]: ... + def itertext(self) -> Generator[str]: ... def keys(self) -> dict_keys[str, str]: ... # makeelement returns the type of self in Python impl, but not in C impl @@ -120,13 +127,16 @@ class Element(Generic[_Tag]): def __copy__(self) -> Element[_Tag]: ... # returns the type of self in Python impl, but not in C impl def __deepcopy__(self, memo: Any, /) -> Element: ... # Only exists in C impl def __delitem__(self, key: SupportsIndex | slice, /) -> None: ... + @overload def __getitem__(self, key: SupportsIndex, /) -> Element: ... @overload def __getitem__(self, key: slice[SupportsIndex | None], /) -> list[Element]: ... + def __len__(self) -> int: ... # Doesn't actually exist at runtime, but instance of the class are indeed iterable due to __getitem__. def __iter__(self) -> Iterator[Element]: ... + @overload def __setitem__(self, key: SupportsIndex, value: Element[Any], /) -> None: ... @overload @@ -161,15 +171,19 @@ class ElementTree(Generic[_Root]): def parse(self, source: _FileRead, parser: XMLParser | None = None) -> Element: ... def iter(self, tag: str | None = None) -> Generator[Element]: ... def find(self, path: str, namespaces: dict[str, str] | None = None) -> Element | None: ... + @overload def findtext(self, path: str, default: None = None, namespaces: dict[str, str] | None = None) -> str | None: ... @overload def findtext(self, path: str, default: _T, namespaces: dict[str, str] | None = None) -> _T | str: ... + def findall(self, path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ... + @overload def iterfind(self, path: Literal[""], namespaces: dict[str, str] | None = None) -> None: ... # type: ignore[overload-overlap] @overload def iterfind(self, path: str, namespaces: dict[str, str] | None = None) -> Generator[Element]: ... + def write( self, file_or_filename: _FileWrite, @@ -185,6 +199,7 @@ class ElementTree(Generic[_Root]): HTML_EMPTY: Final[set[str]] def register_namespace(prefix: str, uri: str) -> None: ... + @overload def tostring( element: Element[Any], @@ -215,6 +230,7 @@ def tostring( default_namespace: str | None = None, short_empty_elements: bool = True, ) -> Any: ... + @overload def tostringlist( element: Element[Any], @@ -245,32 +261,47 @@ def tostringlist( default_namespace: str | None = None, short_empty_elements: bool = True, ) -> list[Any]: ... + def dump(elem: Element[Any] | ElementTree[Any]) -> None: ... def indent(tree: Element[Any] | ElementTree[Any], space: str = " ", level: int = 0) -> None: ... def parse(source: _FileRead, parser: XMLParser[Any] | None = None) -> ElementTree[Element]: ... -# This class is defined inside the body of iterparse +# The type of the second element of the tuple yielded by iterparse depends +# on the event type in the first element of the tuple: +# * start, end: Element[str] +# * comment, pi: Element[_ElementCallable] +# * start-ns: tuple[str, str] (prefix, uri) +# * end-ns: None +_EventT_co = TypeVar("_EventT_co", bound=Element[str] | Element[_ElementCallable] | tuple[str, str] | None, covariant=True) +_EventType: TypeAlias = Literal["start", "end", "comment", "pi", "start-ns", "end-ns"] + +# This class is defined inside the body of iterparse. @type_check_only -class _IterParseIterator(Iterator[tuple[str, Element]], Protocol): - def __next__(self) -> tuple[str, Element]: ... +class _IterParseIterator(Iterator[tuple[_EventType, _EventT_co]], Protocol[_EventT_co]): if sys.version_info >= (3, 13): def close(self) -> None: ... if sys.version_info >= (3, 11): def __del__(self) -> None: ... +# See the comment for _EventT_co above for possible iterator types. @overload -def iterparse(source: _FileRead, events: Sequence[str] | None = None) -> _IterParseIterator: ... +def iterparse(source: _FileRead, events: Iterable[_EventType]) -> _IterParseIterator[Any]: ... +@overload +def iterparse(source: _FileRead, events: None = None) -> _IterParseIterator[Element[str]]: ... + +# In case a custom parser is passed, the type of the second element of the tuple +# yielded by iterparse depends on the parser. @overload @deprecated("The `parser` parameter is deprecated since Python 3.4.") -def iterparse(source: _FileRead, events: Sequence[str] | None = None, parser: XMLParser | None = None) -> _IterParseIterator: ... +def iterparse(source: _FileRead, events: Iterable[_EventType], parser: XMLParser | None = None) -> _IterParseIterator[Any]: ... _EventQueue: TypeAlias = tuple[str] | tuple[str, tuple[str, str]] | tuple[str, None] -class XMLPullParser(Generic[_E]): - def __init__(self, events: Sequence[str] | None = None, *, _parser: XMLParser[_E] | None = None) -> None: ... +class XMLPullParser(Generic[_EventT_co]): + def __init__(self, events: Iterable[_EventType] | None = None, *, _parser: XMLParser[_EventT_co] | None = None) -> None: ... def feed(self, data: str | ReadableBuffer) -> None: ... def close(self) -> None: ... - def read_events(self) -> Iterator[_EventQueue | tuple[str, _E]]: ... + def read_events(self) -> Iterator[_EventQueue | tuple[_EventType, _EventT_co]]: ... def flush(self) -> None: ... def XML(text: str | ReadableBuffer, parser: XMLParser | None = None) -> Element: ... diff --git a/mypy/typeshed/stdlib/xml/sax/__init__.pyi b/mypy/typeshed/stdlib/xml/sax/__init__.pyi index 679466fa34d2c..9b5c3bf4ddea9 100644 --- a/mypy/typeshed/stdlib/xml/sax/__init__.pyi +++ b/mypy/typeshed/stdlib/xml/sax/__init__.pyi @@ -1,8 +1,7 @@ import sys from _typeshed import ReadableBuffer, StrPath, SupportsRead, _T_co from collections.abc import Iterable -from typing import Final, Protocol, type_check_only -from typing_extensions import TypeAlias +from typing import Final, Protocol, TypeAlias, type_check_only from xml.sax._exceptions import ( SAXException as SAXException, SAXNotRecognizedException as SAXNotRecognizedException, diff --git a/mypy/typeshed/stdlib/xml/sax/expatreader.pyi b/mypy/typeshed/stdlib/xml/sax/expatreader.pyi index 3f9573a25f9aa..e29853ebc3fe3 100644 --- a/mypy/typeshed/stdlib/xml/sax/expatreader.pyi +++ b/mypy/typeshed/stdlib/xml/sax/expatreader.pyi @@ -1,13 +1,8 @@ -import sys from _typeshed import ReadableBuffer from collections.abc import Mapping -from typing import Any, Final, Literal, overload -from typing_extensions import TypeAlias +from typing import Any, Final, Literal, TypeAlias, overload from xml.sax import _Source, xmlreader -from xml.sax.handler import _ContentHandlerProtocol - -if sys.version_info >= (3, 10): - from xml.sax.handler import LexicalHandler +from xml.sax.handler import LexicalHandler, _ContentHandlerProtocol _BoolType: TypeAlias = Literal[0, 1] | bool @@ -33,26 +28,25 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): def setContentHandler(self, handler: _ContentHandlerProtocol) -> None: ... def getFeature(self, name: str) -> _BoolType: ... def setFeature(self, name: str, state: _BoolType) -> None: ... - if sys.version_info >= (3, 10): - @overload - def getProperty(self, name: Literal["http://xml.org/sax/properties/lexical-handler"]) -> LexicalHandler | None: ... + @overload + def getProperty(self, name: Literal["http://xml.org/sax/properties/lexical-handler"]) -> LexicalHandler | None: ... @overload def getProperty(self, name: Literal["http://www.python.org/sax/properties/interning-dict"]) -> dict[str, Any] | None: ... @overload def getProperty(self, name: Literal["http://xml.org/sax/properties/xml-string"]) -> bytes | None: ... @overload def getProperty(self, name: str) -> object: ... - if sys.version_info >= (3, 10): - @overload - def setProperty(self, name: Literal["http://xml.org/sax/properties/lexical-handler"], value: LexicalHandler) -> None: ... + @overload + def setProperty(self, name: Literal["http://xml.org/sax/properties/lexical-handler"], value: LexicalHandler) -> None: ... @overload def setProperty( self, name: Literal["http://www.python.org/sax/properties/interning-dict"], value: dict[str, Any] ) -> None: ... @overload def setProperty(self, name: str, value: object) -> None: ... + def feed(self, data: str | ReadableBuffer, isFinal: bool = False) -> None: ... def flush(self) -> None: ... def close(self) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/sax/handler.pyi b/mypy/typeshed/stdlib/xml/sax/handler.pyi index 5ecbfa6f1272c..e1e080ac2d1aa 100644 --- a/mypy/typeshed/stdlib/xml/sax/handler.pyi +++ b/mypy/typeshed/stdlib/xml/sax/handler.pyi @@ -1,4 +1,3 @@ -import sys from typing import Final, NoReturn, Protocol, type_check_only from xml.sax import xmlreader @@ -77,10 +76,9 @@ property_encoding: Final = "http://www.python.org/sax/properties/encoding" property_interning_dict: Final[str] # too long string all_properties: Final[list[str]] -if sys.version_info >= (3, 10): - class LexicalHandler: - def comment(self, content: str) -> None: ... - def startDTD(self, name: str, public_id: str | None, system_id: str | None) -> None: ... - def endDTD(self) -> None: ... - def startCDATA(self) -> None: ... - def endCDATA(self) -> None: ... +class LexicalHandler: + def comment(self, content: str) -> None: ... + def startDTD(self, name: str, public_id: str | None, system_id: str | None) -> None: ... + def endDTD(self) -> None: ... + def startCDATA(self) -> None: ... + def endCDATA(self) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi b/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi index e7d04ddeadb80..a7ae5edc55d35 100644 --- a/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi +++ b/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi @@ -1,7 +1,7 @@ from _typeshed import ReadableBuffer from collections.abc import Mapping -from typing import Generic, Literal, TypeVar, overload -from typing_extensions import Self, TypeAlias +from typing import Generic, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Self from xml.sax import _Source, _SupportsReadClose from xml.sax.handler import _ContentHandlerProtocol, _DTDHandlerProtocol, _EntityResolverProtocol, _ErrorHandlerProtocol @@ -64,10 +64,12 @@ class AttributesImpl(Generic[_AttrKey]): def __getitem__(self, name: _AttrKey) -> str: ... def keys(self) -> list[_AttrKey]: ... def __contains__(self, name: _AttrKey) -> bool: ... + @overload def get(self, name: _AttrKey, alternative: None = None) -> str | None: ... @overload def get(self, name: _AttrKey, alternative: str) -> str: ... + def copy(self) -> Self: ... def items(self) -> list[tuple[_AttrKey, str]]: ... def values(self) -> list[str]: ... @@ -83,8 +85,10 @@ class AttributesNSImpl(AttributesImpl[_NSName]): def __getitem__(self, name: _NSName) -> str: ... def keys(self) -> list[_NSName]: ... def __contains__(self, name: _NSName) -> bool: ... + @overload def get(self, name: _NSName, alternative: None = None) -> str | None: ... @overload def get(self, name: _NSName, alternative: str) -> str: ... + def items(self) -> list[tuple[_NSName, str]]: ... diff --git a/mypy/typeshed/stdlib/xml/utils.pyi b/mypy/typeshed/stdlib/xml/utils.pyi new file mode 100644 index 0000000000000..1c3bb877a7ccf --- /dev/null +++ b/mypy/typeshed/stdlib/xml/utils.pyi @@ -0,0 +1,2 @@ +def is_valid_name(name: str) -> bool: ... +def is_valid_text(data: str) -> bool: ... diff --git a/mypy/typeshed/stdlib/xmlrpc/client.pyi b/mypy/typeshed/stdlib/xmlrpc/client.pyi index 42420ee85848f..573401f18d082 100644 --- a/mypy/typeshed/stdlib/xmlrpc/client.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/client.pyi @@ -6,8 +6,8 @@ from collections.abc import Callable, Iterable, Mapping from datetime import datetime from io import BytesIO from types import TracebackType -from typing import Any, ClassVar, Final, Literal, Protocol, overload, type_check_only -from typing_extensions import Self, TypeAlias +from typing import Any, ClassVar, Final, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self @type_check_only class _SupportsTimeTuple(Protocol): @@ -282,12 +282,14 @@ class ServerProxy: context: Any | None = None, ) -> None: ... def __getattr__(self, name: str) -> _Method: ... + @overload def __call__(self, attr: Literal["close"]) -> Callable[[], None]: ... @overload def __call__(self, attr: Literal["transport"]) -> Transport: ... @overload def __call__(self, attr: str) -> Callable[[], None] | Transport: ... + def __enter__(self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None diff --git a/mypy/typeshed/stdlib/xmlrpc/server.pyi b/mypy/typeshed/stdlib/xmlrpc/server.pyi index 286aaf980fbf5..7bf397d2b1a43 100644 --- a/mypy/typeshed/stdlib/xmlrpc/server.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/server.pyi @@ -4,8 +4,7 @@ import socketserver from _typeshed import ReadableBuffer from collections.abc import Callable, Iterable, Mapping from re import Pattern -from typing import Any, ClassVar, Protocol, type_check_only -from typing_extensions import TypeAlias +from typing import Any, ClassVar, Protocol, TypeAlias, type_check_only from xmlrpc.client import Fault, _Marshallable # The dispatch accepts anywhere from 0 to N arguments, no easy way to allow this in mypy diff --git a/mypy/typeshed/stdlib/xxlimited.pyi b/mypy/typeshed/stdlib/xxlimited.pyi index 78a50b85f405a..503caf0183f31 100644 --- a/mypy/typeshed/stdlib/xxlimited.pyi +++ b/mypy/typeshed/stdlib/xxlimited.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, ClassVar, final +from typing import Any, final class Str(str): ... @@ -12,13 +12,4 @@ class Xxo: def foo(i: int, j: int, /) -> Any: ... def new() -> Xxo: ... -if sys.version_info >= (3, 10): - class Error(Exception): ... - -else: - class error(Exception): ... - - class Null: - __hash__: ClassVar[None] # type: ignore[assignment] - - def roj(b: Any, /) -> None: ... +class Error(Exception): ... diff --git a/mypy/typeshed/stdlib/zipapp.pyi b/mypy/typeshed/stdlib/zipapp.pyi index c7cf1704b1359..48713bced8921 100644 --- a/mypy/typeshed/stdlib/zipapp.pyi +++ b/mypy/typeshed/stdlib/zipapp.pyi @@ -1,7 +1,6 @@ from collections.abc import Callable from pathlib import Path -from typing import BinaryIO -from typing_extensions import TypeAlias +from typing import BinaryIO, TypeAlias __all__ = ["ZipAppError", "create_archive", "get_interpreter"] diff --git a/mypy/typeshed/stdlib/zipfile/__init__.pyi b/mypy/typeshed/stdlib/zipfile/__init__.pyi index 19d8117a621fc..0039a05b5d6fe 100644 --- a/mypy/typeshed/stdlib/zipfile/__init__.pyi +++ b/mypy/typeshed/stdlib/zipfile/__init__.pyi @@ -5,8 +5,8 @@ from collections.abc import Callable, Iterable, Iterator from io import TextIOWrapper from os import PathLike from types import TracebackType -from typing import IO, Final, Literal, Protocol, overload, type_check_only -from typing_extensions import Self, TypeAlias +from typing import IO, Final, Literal, Protocol, TypeAlias, overload, type_check_only +from typing_extensions import Self __all__ = [ "BadZipFile", @@ -67,6 +67,7 @@ class ZipExtFile(io.BufferedIOBase): newlines: list[bytes] | None mode: _ReadWriteMode name: str + @overload def __init__( self, fileobj: _ClosableZipStream, mode: _ReadWriteMode, zipinfo: ZipInfo, pwd: bytes | None, close_fileobj: Literal[True] @@ -90,6 +91,7 @@ class ZipExtFile(io.BufferedIOBase): pwd: bytes | None = None, close_fileobj: Literal[False] = False, ) -> None: ... + def read(self, n: int | None = -1) -> bytes: ... def readline(self, limit: int = -1) -> bytes: ... # type: ignore[override] def peek(self, n: int = 1) -> bytes: ... @@ -330,6 +332,7 @@ if sys.version_info >= (3, 12): else: class CompleteDirs(ZipFile): def resolve_dir(self, name: str) -> str: ... + @overload @classmethod def make(cls, source: ZipFile) -> CompleteDirs: ... @@ -345,9 +348,8 @@ else: def name(self) -> str: ... @property def parent(self) -> PathLike[str]: ... # undocumented - if sys.version_info >= (3, 10): - @property - def filename(self) -> PathLike[str]: ... # undocumented + @property + def filename(self) -> PathLike[str]: ... # undocumented if sys.version_info >= (3, 11): @property def suffix(self) -> str: ... @@ -371,11 +373,7 @@ else: @overload def open(self, mode: Literal["rb", "wb"], *, pwd: bytes | None = None) -> IO[bytes]: ... - if sys.version_info >= (3, 10): - def iterdir(self) -> Iterator[Self]: ... - else: - def iterdir(self) -> Iterator[Path]: ... - + def iterdir(self) -> Iterator[Self]: ... def is_dir(self) -> bool: ... def is_file(self) -> bool: ... def exists(self) -> bool: ... @@ -388,11 +386,7 @@ else: write_through: bool = False, ) -> str: ... def read_bytes(self) -> bytes: ... - if sys.version_info >= (3, 10): - def joinpath(self, *other: StrPath) -> Path: ... - else: - def joinpath(self, add: StrPath) -> Path: ... # undocumented - + def joinpath(self, *other: StrPath) -> Path: ... def __truediv__(self, add: StrPath) -> Path: ... def is_zipfile(filename: StrOrBytesPath | _SupportsReadSeekTell) -> bool: ... diff --git a/mypy/typeshed/stdlib/zipfile/_path/__init__.pyi b/mypy/typeshed/stdlib/zipfile/_path/__init__.pyi index c936c4494c7cb..e1449dc681ad5 100644 --- a/mypy/typeshed/stdlib/zipfile/_path/__init__.pyi +++ b/mypy/typeshed/stdlib/zipfile/_path/__init__.pyi @@ -19,12 +19,14 @@ if sys.version_info >= (3, 12): class CompleteDirs(InitializedState, ZipFile): def resolve_dir(self, name: str) -> str: ... + @overload @classmethod def make(cls, source: ZipFile) -> CompleteDirs: ... @overload @classmethod def make(cls, source: StrPath | IO[bytes]) -> Self: ... + if sys.version_info >= (3, 13): @classmethod def inject(cls, zf: _ZF) -> _ZF: ... @@ -45,6 +47,7 @@ if sys.version_info >= (3, 12): def suffixes(self) -> list[str]: ... @property def stem(self) -> str: ... + @overload def open( self, @@ -59,6 +62,7 @@ if sys.version_info >= (3, 12): ) -> TextIOWrapper: ... @overload def open(self, mode: Literal["rb", "wb"], *, pwd: bytes | None = None) -> IO[bytes]: ... + def iterdir(self) -> Iterator[Self]: ... def is_dir(self) -> bool: ... def is_file(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/zipimport.pyi b/mypy/typeshed/stdlib/zipimport.pyi index 22af3c272759b..4b34f1f2ad3e7 100644 --- a/mypy/typeshed/stdlib/zipimport.pyi +++ b/mypy/typeshed/stdlib/zipimport.pyi @@ -1,19 +1,11 @@ import sys +from _frozen_importlib_external import _LoaderBasics from _typeshed import StrOrBytesPath from importlib.machinery import ModuleSpec +from importlib.readers import ZipReader from types import CodeType, ModuleType from typing_extensions import deprecated -if sys.version_info >= (3, 10): - from importlib.readers import ZipReader -else: - from importlib.abc import ResourceReader - -if sys.version_info >= (3, 10): - from _frozen_importlib_external import _LoaderBasics -else: - _LoaderBasics = object - __all__ = ["ZipImportError", "zipimporter"] class ZipImportError(ImportError): ... @@ -27,33 +19,26 @@ class zipimporter(_LoaderBasics): def __init__(self, path: StrOrBytesPath) -> None: ... if sys.version_info < (3, 12): - if sys.version_info >= (3, 10): - @deprecated("Deprecated since Python 3.10; removed in Python 3.12. Use `find_spec()` instead.") - def find_loader(self, fullname: str, path: str | None = None) -> tuple[zipimporter | None, list[str]]: ... - @deprecated("Deprecated since Python 3.10; removed in Python 3.12. Use `find_spec()` instead.") - def find_module(self, fullname: str, path: str | None = None) -> zipimporter | None: ... - else: - def find_loader(self, fullname: str, path: str | None = None) -> tuple[zipimporter | None, list[str]]: ... - def find_module(self, fullname: str, path: str | None = None) -> zipimporter | None: ... + @deprecated("Deprecated since Python 3.10; removed in Python 3.12. Use `find_spec()` instead.") + def find_loader(self, fullname: str, path: str | None = None) -> tuple[zipimporter | None, list[str]]: ... + @deprecated("Deprecated since Python 3.10; removed in Python 3.12. Use `find_spec()` instead.") + def find_module(self, fullname: str, path: str | None = None) -> zipimporter | None: ... def get_code(self, fullname: str) -> CodeType: ... def get_data(self, pathname: str) -> bytes: ... def get_filename(self, fullname: str) -> str: ... if sys.version_info >= (3, 14): def get_resource_reader(self, fullname: str) -> ZipReader: ... # undocumented - elif sys.version_info >= (3, 10): - def get_resource_reader(self, fullname: str) -> ZipReader | None: ... # undocumented else: - def get_resource_reader(self, fullname: str) -> ResourceReader | None: ... # undocumented + def get_resource_reader(self, fullname: str) -> ZipReader | None: ... # undocumented def get_source(self, fullname: str) -> str | None: ... def is_package(self, fullname: str) -> bool: ... - if sys.version_info >= (3, 10): + if sys.version_info < (3, 15): @deprecated("Deprecated since Python 3.10; removed in Python 3.15. Use `exec_module()` instead.") def load_module(self, fullname: str) -> ModuleType: ... - def exec_module(self, module: ModuleType) -> None: ... - def create_module(self, spec: ModuleSpec) -> None: ... - def find_spec(self, fullname: str, target: ModuleType | None = None) -> ModuleSpec | None: ... - def invalidate_caches(self) -> None: ... - else: - def load_module(self, fullname: str) -> ModuleType: ... + + def exec_module(self, module: ModuleType) -> None: ... + def create_module(self, spec: ModuleSpec) -> None: ... + def find_spec(self, fullname: str, target: ModuleType | None = None) -> ModuleSpec | None: ... + def invalidate_caches(self) -> None: ... diff --git a/mypy/typeshed/stdlib/zlib.pyi b/mypy/typeshed/stdlib/zlib.pyi index d5998cab90fef..557fa761feebf 100644 --- a/mypy/typeshed/stdlib/zlib.pyi +++ b/mypy/typeshed/stdlib/zlib.pyi @@ -60,6 +60,9 @@ class _Decompress: def adler32(data: ReadableBuffer, value: int = 1, /) -> int: ... +if sys.version_info >= (3, 15): + def adler32_combine(adler1: int, adler2: int, len2: int, /) -> int: ... + if sys.version_info >= (3, 11): def compress(data: ReadableBuffer, /, level: int = -1, wbits: int = 15) -> bytes: ... @@ -70,5 +73,9 @@ def compressobj( level: int = -1, method: int = 8, wbits: int = 15, memLevel: int = 8, strategy: int = 0, zdict: ReadableBuffer | None = None ) -> _Compress: ... def crc32(data: ReadableBuffer, value: int = 0, /) -> int: ... + +if sys.version_info >= (3, 15): + def crc32_combine(crc1: int, crc2: int, len2: int, /) -> int: ... + def decompress(data: ReadableBuffer, /, wbits: int = 15, bufsize: int = 16384) -> bytes: ... def decompressobj(wbits: int = 15, zdict: ReadableBuffer = b"") -> _Decompress: ... diff --git a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi index b7433f835f83d..def31546becbf 100644 --- a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi +++ b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi @@ -19,6 +19,7 @@ class ZoneInfo(tzinfo): def __new__(cls, key: str) -> Self: ... @classmethod def no_cache(cls, key: str) -> Self: ... + if sys.version_info >= (3, 12): @classmethod def from_file(cls, file_obj: _IOBytes, /, key: str | None = None) -> Self: ...