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 d0b1aca381df..9958005c199c 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 b5f2cc9633f9f6cd9326eee96a32efb3aff70701 Mon Sep 17 00:00:00 2001 +From f12b57ec89a6431737e4f473cecabf0d350b0d46 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,7 +8,7 @@ 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 029bfeefe..9dbd8c308 100644 +index 32beaff14..e97a2d2e1 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -2,7 +2,7 @@ import sys @@ -20,7 +20,7 @@ index 029bfeefe..9dbd8c308 100644 from typing_extensions import Self, TypeAlias, deprecated __all__ = [ -@@ -38,7 +38,9 @@ ONE_OR_MORE: Final = "+" +@@ -36,7 +36,9 @@ ONE_OR_MORE: Final = "+" OPTIONAL: Final = "?" PARSER: Final = "A..." REMAINDER: Final = "..." @@ -31,7 +31,7 @@ index 029bfeefe..9dbd8c308 100644 ZERO_OR_MORE: Final = "*" _UNRECOGNIZED_ARGS_ATTR: Final = "_unrecognized_args" # undocumented -@@ -81,7 +83,7 @@ class _ActionsContainer: +@@ -79,7 +81,7 @@ class _ActionsContainer: # more precisely, Literal["?", "*", "+", "...", "A...", "==SUPPRESS=="], # but using this would make it hard to annotate callers that don't use a # literal argument and for subclasses to override this method. @@ -41,5 +41,5 @@ index 029bfeefe..9dbd8c308 100644 default: Any = ..., type: _ActionType = ..., -- -2.48.1 +2.49.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 91e255242ee9..e7a3e1ae1a1d 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,4 +1,4 @@ -From b4259edd94188f9e4cc77a22e768eea183a32053 Mon Sep 17 00:00:00 2001 +From d33ae9f29cc3ff83102dfa68c22ab2a459fbeb43 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) @@ -8,10 +8,10 @@ Subject: [PATCH] Remove use of LiteralString in builtins (#13743) 1 file changed, 1 insertion(+), 99 deletions(-) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi -index 63c53a5f6..d55042b56 100644 +index b75250aad..64d08dba0 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi -@@ -63,7 +63,6 @@ from typing import ( # noqa: Y022 +@@ -62,7 +62,6 @@ from typing import ( # noqa: Y022,UP035 from typing_extensions import ( # noqa: Y023 Concatenate, Literal, @@ -19,7 +19,7 @@ index 63c53a5f6..d55042b56 100644 ParamSpec, Self, TypeAlias, -@@ -438,31 +437,16 @@ class str(Sequence[str]): +@@ -440,31 +439,16 @@ class str(Sequence[str]): def __new__(cls, object: object = ...) -> Self: ... @overload def __new__(cls, object: ReadableBuffer, encoding: str = ..., errors: str = ...) -> Self: ... @@ -51,7 +51,7 @@ index 63c53a5f6..d55042b56 100644 def format(self, *args: object, **kwargs: object) -> str: ... def format_map(self, mapping: _FormatMapMapping, /) -> str: ... def index(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ... -@@ -478,99 +462,35 @@ class str(Sequence[str]): +@@ -480,98 +464,34 @@ class str(Sequence[str]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... @@ -89,16 +89,15 @@ index 63c53a5f6..d55042b56 100644 - ) -> LiteralString: ... - @overload def replace(self, old: str, new: str, count: SupportsIndex = -1, /) -> str: ... # type: ignore[misc] - if sys.version_info >= (3, 9): -- @overload -- def removeprefix(self: LiteralString, prefix: LiteralString, /) -> LiteralString: ... -- @overload - def removeprefix(self, prefix: str, /) -> str: ... # type: ignore[misc] -- @overload -- def removesuffix(self: LiteralString, suffix: LiteralString, /) -> LiteralString: ... -- @overload - def removesuffix(self, suffix: str, /) -> str: ... # type: ignore[misc] +- @overload +- def removeprefix(self: LiteralString, prefix: LiteralString, /) -> LiteralString: ... +- @overload + def removeprefix(self, prefix: str, /) -> str: ... # type: ignore[misc] +- @overload +- def removesuffix(self: LiteralString, suffix: LiteralString, /) -> LiteralString: ... +- @overload + def removesuffix(self, suffix: str, /) -> str: ... # type: ignore[misc] def rfind(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ... def rindex(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ... - @overload @@ -151,7 +150,7 @@ index 63c53a5f6..d55042b56 100644 def zfill(self, width: SupportsIndex, /) -> str: ... # type: ignore[misc] @staticmethod @overload -@@ -581,39 +501,21 @@ class str(Sequence[str]): +@@ -582,39 +502,21 @@ class str(Sequence[str]): @staticmethod @overload def maketrans(x: str, y: str, z: str, /) -> dict[int, int | None]: ... @@ -193,5 +192,5 @@ index 63c53a5f6..d55042b56 100644 def __getnewargs__(self) -> tuple[str]: ... -- -2.47.0 +2.49.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 ef1d9f4d3fa3..665491ea97c5 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 abc5225e3c69d7ae8f3388c87260fe496efaecac Mon Sep 17 00:00:00 2001 +From 49ed611997ce5c8b41dcbf6238b3c73526bfe1c0 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 89cdff6cc..1397e579d 100644 +index be486fddb..3c918d818 100644 --- a/mypy/typeshed/stdlib/_asyncio.pyi +++ b/mypy/typeshed/stdlib/_asyncio.pyi @@ -1,6 +1,6 @@ @@ -24,90 +24,90 @@ index 89cdff6cc..1397e579d 100644 -from collections.abc import Awaitable, Callable, Coroutine, Generator +from collections.abc import Awaitable, Callable, Coroutine, Generator, Iterable from contextvars import Context - from types import FrameType + from types import FrameType, GenericAlias from typing import Any, Literal, TextIO, TypeVar -@@ -13,7 +13,7 @@ _T = TypeVar("_T") +@@ -10,7 +10,7 @@ _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) _TaskYieldType: TypeAlias = Future[object] | None - + -class Future(Awaitable[_T]): +class Future(Awaitable[_T], Iterable[_T]): _state: str @property def _exception(self) -> BaseException | None: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi -index b75e34fc5..526406acc 100644 +index 64d08dba0..e45967e10 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi -@@ -1130,7 +1130,7 @@ class frozenset(AbstractSet[_T_co]): - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... - +@@ -1134,7 +1134,7 @@ class frozenset(AbstractSet[_T_co]): + def __hash__(self) -> int: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + -class enumerate(Generic[_T]): +class enumerate(Iterator[tuple[int, _T]]): def __new__(cls, iterable: Iterable[_T], start: int = 0) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> tuple[int, _T]: ... -@@ -1324,7 +1324,7 @@ else: - +@@ -1330,7 +1330,7 @@ else: + exit: _sitebuiltins.Quitter - + -class filter(Generic[_T]): +class filter(Iterator[_T]): @overload def __new__(cls, function: None, iterable: Iterable[_T | None], /) -> Self: ... @overload -@@ -1389,7 +1389,7 @@ license: _sitebuiltins._Printer - +@@ -1395,7 +1395,7 @@ license: _sitebuiltins._Printer + def locals() -> dict[str, Any]: ... - + -class map(Generic[_S]): +class map(Iterator[_S]): @overload def __new__(cls, func: Callable[[_T1], _S], iterable: Iterable[_T1], /) -> Self: ... @overload -@@ -1632,7 +1632,7 @@ def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex - +@@ -1638,7 +1638,7 @@ def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex + quit: _sitebuiltins.Quitter - + -class reversed(Generic[_T]): +class reversed(Iterator[_T]): @overload def __new__(cls, sequence: Reversible[_T], /) -> Iterator[_T]: ... # type: ignore[misc] @overload -@@ -1693,7 +1693,7 @@ def vars(object: type, /) -> types.MappingProxyType[str, Any]: ... +@@ -1699,7 +1699,7 @@ def vars(object: type, /) -> types.MappingProxyType[str, Any]: ... @overload def vars(object: Any = ..., /) -> dict[str, Any]: ... - + -class zip(Generic[_T_co]): +class zip(Iterator[_T_co]): if sys.version_info >= (3, 10): @overload def __new__(cls, *, strict: bool = ...) -> zip[Any]: ... diff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi -index 4a82de638..ef93129d6 100644 +index 2c8e7109c..4ed0ab1d8 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi @@ -25,7 +25,7 @@ else: from _csv import _reader as Reader, _writer as Writer - + from _typeshed import SupportsWrite -from collections.abc import Collection, Iterable, Mapping, Sequence +from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence + from types import GenericAlias from typing import Any, Generic, Literal, TypeVar, overload from typing_extensions import Self - -@@ -75,7 +75,7 @@ class excel(Dialect): ... +@@ -73,7 +73,7 @@ class excel(Dialect): ... class excel_tab(excel): ... class unix_dialect(Dialect): ... - + -class DictReader(Generic[_T]): +class DictReader(Iterator[dict[_T | Any, str | Any]], Generic[_T]): fieldnames: Sequence[_T] | None restkey: _T | None restval: str | Any | None diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi -index bf6daad0a..1e6aa78e2 100644 +index 948b39ea1..1d5f9cf00 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -1,8 +1,8 @@ @@ -115,27 +115,27 @@ index bf6daad0a..1e6aa78e2 100644 from _typeshed import AnyStr_co, StrOrBytesPath -from collections.abc import Callable, Iterable +from collections.abc import Callable, Iterable, Iterator - from types import TracebackType + from types import GenericAlias, TracebackType -from typing import IO, Any, AnyStr, Generic, Literal, Protocol, overload +from typing import IO, Any, AnyStr, Literal, Protocol, overload from typing_extensions import Self, TypeAlias - - if sys.version_info >= (3, 9): -@@ -107,7 +107,7 @@ def fileno() -> int: ... + + __all__ = [ +@@ -104,7 +104,7 @@ def fileno() -> int: ... def isfirstline() -> bool: ... def isstdin() -> bool: ... - + -class FileInput(Generic[AnyStr]): +class FileInput(Iterator[AnyStr]): if sys.version_info >= (3, 10): # encoding and errors are added @overload diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi -index 55b0814ac..675533d44 100644 +index d0085dd72..7d05b1318 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi -@@ -29,7 +29,7 @@ _Predicate: TypeAlias = Callable[[_T], object] - +@@ -27,7 +27,7 @@ _Predicate: TypeAlias = Callable[[_T], object] + # Technically count can take anything that implements a number protocol and has an add method # but we can't enforce the add method -class count(Generic[_N]): @@ -143,144 +143,144 @@ index 55b0814ac..675533d44 100644 @overload def __new__(cls) -> count[int]: ... @overload -@@ -39,12 +39,12 @@ class count(Generic[_N]): +@@ -37,12 +37,12 @@ class count(Generic[_N]): def __next__(self) -> _N: ... def __iter__(self) -> Self: ... - + -class cycle(Generic[_T]): +class cycle(Iterator[_T]): def __new__(cls, iterable: Iterable[_T], /) -> Self: ... def __next__(self) -> _T: ... def __iter__(self) -> Self: ... - + -class repeat(Generic[_T]): +class repeat(Iterator[_T]): @overload def __new__(cls, object: _T) -> Self: ... @overload -@@ -53,7 +53,7 @@ class repeat(Generic[_T]): +@@ -51,7 +51,7 @@ class repeat(Generic[_T]): def __iter__(self) -> Self: ... def __length_hint__(self) -> int: ... - + -class accumulate(Generic[_T]): +class accumulate(Iterator[_T]): @overload def __new__(cls, iterable: Iterable[_T], func: None = None, *, initial: _T | None = ...) -> Self: ... @overload -@@ -61,7 +61,7 @@ class accumulate(Generic[_T]): +@@ -59,7 +59,7 @@ class accumulate(Generic[_T]): def __iter__(self) -> Self: ... def __next__(self) -> _T: ... - + -class chain(Generic[_T]): +class chain(Iterator[_T]): def __new__(cls, *iterables: Iterable[_T]) -> Self: ... def __next__(self) -> _T: ... def __iter__(self) -> Self: ... -@@ -71,22 +71,22 @@ class chain(Generic[_T]): - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... - +@@ -68,22 +68,22 @@ class chain(Generic[_T]): + def from_iterable(cls: type[Any], iterable: Iterable[Iterable[_S]], /) -> chain[_S]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + -class compress(Generic[_T]): +class compress(Iterator[_T]): def __new__(cls, data: Iterable[_T], selectors: Iterable[Any]) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... - + -class dropwhile(Generic[_T]): +class dropwhile(Iterator[_T]): def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... - + -class filterfalse(Generic[_T]): +class filterfalse(Iterator[_T]): def __new__(cls, function: _Predicate[_T] | None, iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... - + -class groupby(Generic[_T_co, _S_co]): +class groupby(Iterator[tuple[_T_co, Iterator[_S_co]]], Generic[_T_co, _S_co]): @overload def __new__(cls, iterable: Iterable[_T1], key: None = None) -> groupby[_T1, _T1]: ... @overload -@@ -94,7 +94,7 @@ class groupby(Generic[_T_co, _S_co]): +@@ -91,7 +91,7 @@ class groupby(Generic[_T_co, _S_co]): def __iter__(self) -> Self: ... def __next__(self) -> tuple[_T_co, Iterator[_S_co]]: ... - + -class islice(Generic[_T]): +class islice(Iterator[_T]): @overload def __new__(cls, iterable: Iterable[_T], stop: int | None, /) -> Self: ... @overload -@@ -102,19 +102,19 @@ class islice(Generic[_T]): +@@ -99,19 +99,19 @@ class islice(Generic[_T]): def __iter__(self) -> Self: ... def __next__(self) -> _T: ... - + -class starmap(Generic[_T_co]): +class starmap(Iterator[_T_co]): def __new__(cls, function: Callable[..., _T], iterable: Iterable[Iterable[Any]], /) -> starmap[_T]: ... def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... - + -class takewhile(Generic[_T]): +class takewhile(Iterator[_T]): def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> _T: ... - + def tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]: ... - + -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 = ...) -> zip_longest[tuple[_T1]]: ... -@@ -192,7 +192,7 @@ class zip_longest(Generic[_T_co]): +@@ -189,7 +189,7 @@ class zip_longest(Generic[_T_co]): def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... - + -class product(Generic[_T_co]): +class product(Iterator[_T_co]): @overload def __new__(cls, iter1: Iterable[_T1], /) -> product[tuple[_T1]]: ... @overload -@@ -277,7 +277,7 @@ class product(Generic[_T_co]): +@@ -274,7 +274,7 @@ class product(Generic[_T_co]): def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... - + -class permutations(Generic[_T_co]): +class permutations(Iterator[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> permutations[tuple[_T, _T]]: ... @overload -@@ -291,7 +291,7 @@ class permutations(Generic[_T_co]): +@@ -288,7 +288,7 @@ class permutations(Generic[_T_co]): def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... - + -class combinations(Generic[_T_co]): +class combinations(Iterator[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations[tuple[_T, _T]]: ... @overload -@@ -305,7 +305,7 @@ class combinations(Generic[_T_co]): +@@ -302,7 +302,7 @@ class combinations(Generic[_T_co]): def __iter__(self) -> Self: ... def __next__(self) -> _T_co: ... - + -class combinations_with_replacement(Generic[_T_co]): +class combinations_with_replacement(Iterator[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations_with_replacement[tuple[_T, _T]]: ... @overload -@@ -320,13 +320,13 @@ class combinations_with_replacement(Generic[_T_co]): +@@ -317,13 +317,13 @@ class combinations_with_replacement(Generic[_T_co]): def __next__(self) -> _T_co: ... - + if sys.version_info >= (3, 10): - 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): - class batched(Generic[_T_co]): + class batched(Iterator[tuple[_T_co, ...]], Generic[_T_co]): @@ -288,20 +288,19 @@ index 55b0814ac..675533d44 100644 def __new__(cls, iterable: Iterable[_T_co], n: int, *, strict: bool = False) -> Self: ... else: diff --git a/mypy/typeshed/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi -index 2937d45e3..93197e5d4 100644 +index b79f9e773..f276372d0 100644 --- a/mypy/typeshed/stdlib/multiprocessing/pool.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/pool.pyi -@@ -1,5 +1,5 @@ - import sys +@@ -1,4 +1,4 @@ -from collections.abc import Callable, Iterable, Mapping +from collections.abc import Callable, Iterable, Iterator, Mapping from multiprocessing.context import DefaultContext, Process - from types import TracebackType + from types import GenericAlias, TracebackType from typing import Any, Final, Generic, TypeVar -@@ -37,7 +37,7 @@ class MapResult(ApplyResult[list[_T]]): +@@ -32,7 +32,7 @@ class MapResult(ApplyResult[list[_T]]): error_callback: Callable[[BaseException], object] | None, ) -> None: ... - + -class IMapIterator(Generic[_T]): +class IMapIterator(Iterator[_T]): def __init__(self, pool: Pool) -> None: ... @@ -314,11 +313,12 @@ index b83516b4d..724bc3166 100644 @@ -397,7 +397,7 @@ class Connection: self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None, / ) -> Literal[False]: ... - + -class Cursor: +class Cursor(Iterator[Any]): arraysize: int @property def connection(self) -> Connection: ... --- -2.47.1 +-- +2.49.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 331628af1424..6c7999ea8e51 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 58c6a6ab863c1c38e95ccafaf13792ed9c00e499 Mon Sep 17 00:00:00 2001 +From ea30f4a61c9b4094519d02b4793cee5ad2ba6b54 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 ea9f8c894..a6065cc67 100644 +index e45967e10..e9b0d51eb 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi -@@ -1653,7 +1653,7 @@ _SupportsSumNoDefaultT = TypeVar("_SupportsSumNoDefaultT", bound=_SupportsSumWit +@@ -1686,7 +1686,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 ea9f8c894..a6065cc67 100644 def sum(iterable: Iterable[_SupportsSumNoDefaultT], /) -> _SupportsSumNoDefaultT | Literal[0]: ... @overload -- -2.46.0 +2.49.0 diff --git a/misc/typeshed_patches/0001-Revert-typeshed-ctypes-change.patch b/misc/typeshed_patches/0001-Revert-typeshed-ctypes-change.patch index 27066bf3c25b..e2f7eca0e5ba 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 61a490091d7c941780919660dc4fdfa88ae6474a Mon Sep 17 00:00:00 2001 +From 59b3ec786214d308b6e6950b1cfa2d6266967174 Mon Sep 17 00:00:00 2001 From: AlexWaygood Date: Mon, 1 May 2023 20:34:55 +0100 Subject: [PATCH] Revert typeshed ctypes change Since the plugin provides @@ -11,10 +11,10 @@ Subject: [PATCH] Revert typeshed ctypes change Since the plugin provides 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/mypy/typeshed/stdlib/_ctypes.pyi b/mypy/typeshed/stdlib/_ctypes.pyi -index 60bbc51d9..cf9cb81a4 100644 +index 4cbb030bb..6b79b9ff0 100644 --- a/mypy/typeshed/stdlib/_ctypes.pyi +++ b/mypy/typeshed/stdlib/_ctypes.pyi -@@ -169,11 +169,7 @@ class Array(_CData, Generic[_CT]): +@@ -284,11 +284,7 @@ class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): def _type_(self) -> type[_CT]: ... @_type_.setter def _type_(self, value: type[_CT]) -> None: ... @@ -25,8 +25,8 @@ index 60bbc51d9..cf9cb81a4 100644 - 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. + # 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.39.3 (Apple Git-146) +2.49.0 diff --git a/mypy/typeshed/stdlib/VERSIONS b/mypy/typeshed/stdlib/VERSIONS index 3c6898dc1a77..fec56ce59e36 100644 --- a/mypy/typeshed/stdlib/VERSIONS +++ b/mypy/typeshed/stdlib/VERSIONS @@ -36,8 +36,6 @@ _curses: 3.0- _curses_panel: 3.0- _dbm: 3.0- _decimal: 3.3- -_dummy_thread: 3.0-3.8 -_dummy_threading: 3.0-3.8 _frozen_importlib: 3.0- _frozen_importlib_external: 3.5- _gdbm: 3.0- @@ -140,7 +138,6 @@ distutils: 3.0-3.11 distutils.command.bdist_msi: 3.0-3.10 distutils.command.bdist_wininst: 3.0-3.9 doctest: 3.0- -dummy_threading: 3.0-3.8 email: 3.0- encodings: 3.0- encodings.cp1125: 3.4- @@ -148,7 +145,6 @@ encodings.cp273: 3.4- encodings.cp858: 3.2- encodings.koi8_t: 3.5- encodings.kz1048: 3.5- -encodings.mac_centeuro: 3.0-3.8 ensurepip: 3.0- enum: 3.4- errno: 3.0- diff --git a/mypy/typeshed/stdlib/_ast.pyi b/mypy/typeshed/stdlib/_ast.pyi index 8dc1bcbea32c..bc0ebd9d8a0f 100644 --- a/mypy/typeshed/stdlib/_ast.pyi +++ b/mypy/typeshed/stdlib/_ast.pyi @@ -130,17 +130,6 @@ if sys.version_info >= (3, 10): pattern as pattern, ) -if sys.version_info < (3, 9): - from ast import ( - AugLoad as AugLoad, - AugStore as AugStore, - ExtSlice as ExtSlice, - Index as Index, - Param as Param, - Suite as Suite, - slice as slice, - ) - PyCF_ALLOW_TOP_LEVEL_AWAIT: Literal[8192] PyCF_ONLY_AST: Literal[1024] PyCF_TYPE_COMMENTS: Literal[4096] diff --git a/mypy/typeshed/stdlib/_asyncio.pyi b/mypy/typeshed/stdlib/_asyncio.pyi index 1397e579d53b..3c918d818256 100644 --- a/mypy/typeshed/stdlib/_asyncio.pyi +++ b/mypy/typeshed/stdlib/_asyncio.pyi @@ -2,13 +2,10 @@ import sys from asyncio.events import AbstractEventLoop from collections.abc import Awaitable, Callable, Coroutine, Generator, Iterable from contextvars import Context -from types import FrameType +from types import FrameType, GenericAlias from typing import Any, Literal, TextIO, TypeVar from typing_extensions import Self, TypeAlias -if sys.version_info >= (3, 9): - from types import GenericAlias - _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) _TaskYieldType: TypeAlias = Future[object] | None @@ -29,11 +26,7 @@ class Future(Awaitable[_T], Iterable[_T]): @property def _callbacks(self) -> list[tuple[Callable[[Self], Any], Context]]: ... def add_done_callback(self, fn: Callable[[Self], object], /, *, context: Context | None = None) -> None: ... - if sys.version_info >= (3, 9): - def cancel(self, msg: Any | None = None) -> bool: ... - else: - def cancel(self) -> bool: ... - + def cancel(self, msg: Any | None = None) -> bool: ... def cancelled(self) -> bool: ... def done(self) -> bool: ... def result(self) -> _T: ... @@ -45,15 +38,12 @@ class Future(Awaitable[_T], Iterable[_T]): def __await__(self) -> Generator[Any, None, _T]: ... @property def _loop(self) -> AbstractEventLoop: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... if sys.version_info >= (3, 12): _TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co] -elif sys.version_info >= (3, 9): - _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co] else: - _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Awaitable[_T_co] + _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co] # mypy and pyright complain that a subclass of an invariant class shouldn't be covariant. # While this is true in general, here it's sort-of okay to have a covariant subclass, @@ -99,13 +89,8 @@ class Task(Future[_T_co]): # type: ignore[type-var] # pyright: ignore[reportIn if sys.version_info >= (3, 11): def cancelling(self) -> int: ... def uncancel(self) -> int: ... - if sys.version_info < (3, 9): - @classmethod - def current_task(cls, loop: AbstractEventLoop | None = None) -> Task[Any] | None: ... - @classmethod - def all_tasks(cls, loop: AbstractEventLoop | None = None) -> set[Task[Any]]: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... def get_event_loop() -> AbstractEventLoop: ... def get_running_loop() -> AbstractEventLoop: ... diff --git a/mypy/typeshed/stdlib/_blake2.pyi b/mypy/typeshed/stdlib/_blake2.pyi index 3d17cb59c79b..d578df55c2fa 100644 --- a/mypy/typeshed/stdlib/_blake2.pyi +++ b/mypy/typeshed/stdlib/_blake2.pyi @@ -1,4 +1,3 @@ -import sys from _typeshed import ReadableBuffer from typing import ClassVar, final from typing_extensions import Self @@ -21,44 +20,24 @@ class blake2b: block_size: int digest_size: int name: str - if sys.version_info >= (3, 9): - def __new__( - cls, - data: ReadableBuffer = b"", - /, - *, - digest_size: int = 64, - key: ReadableBuffer = b"", - salt: ReadableBuffer = b"", - person: ReadableBuffer = b"", - fanout: int = 1, - depth: int = 1, - leaf_size: int = 0, - node_offset: int = 0, - node_depth: int = 0, - inner_size: int = 0, - last_node: bool = False, - usedforsecurity: bool = True, - ) -> Self: ... - else: - def __new__( - cls, - data: ReadableBuffer = b"", - /, - *, - digest_size: int = 64, - key: ReadableBuffer = b"", - salt: ReadableBuffer = b"", - person: ReadableBuffer = b"", - fanout: int = 1, - depth: int = 1, - leaf_size: int = 0, - node_offset: int = 0, - node_depth: int = 0, - inner_size: int = 0, - last_node: bool = False, - ) -> Self: ... - + def __new__( + cls, + data: ReadableBuffer = b"", + /, + *, + digest_size: int = 64, + key: ReadableBuffer = b"", + salt: ReadableBuffer = b"", + person: ReadableBuffer = b"", + fanout: int = 1, + depth: int = 1, + leaf_size: int = 0, + node_offset: int = 0, + node_depth: int = 0, + inner_size: int = 0, + last_node: bool = False, + usedforsecurity: bool = True, + ) -> Self: ... def copy(self) -> Self: ... def digest(self) -> bytes: ... def hexdigest(self) -> str: ... @@ -73,44 +52,24 @@ class blake2s: block_size: int digest_size: int name: str - if sys.version_info >= (3, 9): - def __new__( - cls, - data: ReadableBuffer = b"", - /, - *, - digest_size: int = 32, - key: ReadableBuffer = b"", - salt: ReadableBuffer = b"", - person: ReadableBuffer = b"", - fanout: int = 1, - depth: int = 1, - leaf_size: int = 0, - node_offset: int = 0, - node_depth: int = 0, - inner_size: int = 0, - last_node: bool = False, - usedforsecurity: bool = True, - ) -> Self: ... - else: - def __new__( - cls, - data: ReadableBuffer = b"", - /, - *, - digest_size: int = 32, - key: ReadableBuffer = b"", - salt: ReadableBuffer = b"", - person: ReadableBuffer = b"", - fanout: int = 1, - depth: int = 1, - leaf_size: int = 0, - node_offset: int = 0, - node_depth: int = 0, - inner_size: int = 0, - last_node: bool = False, - ) -> Self: ... - + def __new__( + cls, + data: ReadableBuffer = b"", + /, + *, + digest_size: int = 32, + key: ReadableBuffer = b"", + salt: ReadableBuffer = b"", + person: ReadableBuffer = b"", + fanout: int = 1, + depth: int = 1, + leaf_size: int = 0, + node_offset: int = 0, + node_depth: int = 0, + inner_size: int = 0, + last_node: bool = False, + usedforsecurity: bool = True, + ) -> Self: ... def copy(self) -> Self: ... def digest(self) -> bytes: ... def hexdigest(self) -> str: ... diff --git a/mypy/typeshed/stdlib/_codecs.pyi b/mypy/typeshed/stdlib/_codecs.pyi index 11c5d58a855b..89f97edb9ba8 100644 --- a/mypy/typeshed/stdlib/_codecs.pyi +++ b/mypy/typeshed/stdlib/_codecs.pyi @@ -81,26 +81,12 @@ def escape_decode(data: str | ReadableBuffer, errors: str | None = None, /) -> t def escape_encode(data: bytes, errors: str | None = None, /) -> tuple[bytes, int]: ... def latin_1_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... def latin_1_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... - -if sys.version_info >= (3, 9): - def raw_unicode_escape_decode( - data: str | ReadableBuffer, errors: str | None = None, final: bool = True, / - ) -> tuple[str, int]: ... - -else: - def raw_unicode_escape_decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... - +def raw_unicode_escape_decode( + data: str | ReadableBuffer, errors: str | None = None, final: bool = True, / +) -> tuple[str, int]: ... def raw_unicode_escape_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... def readbuffer_encode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[bytes, int]: ... - -if sys.version_info >= (3, 9): - def unicode_escape_decode( - data: str | ReadableBuffer, errors: str | None = None, final: bool = True, / - ) -> tuple[str, int]: ... - -else: - def unicode_escape_decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... - +def unicode_escape_decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ... def unicode_escape_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... def utf_16_be_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ... def utf_16_be_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... diff --git a/mypy/typeshed/stdlib/_collections_abc.pyi b/mypy/typeshed/stdlib/_collections_abc.pyi index 8bac0ce1dca3..b099bdd98f3c 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 +from typing import ( # noqa: Y022,Y038,UP035 AbstractSet as Set, AsyncGenerator as AsyncGenerator, AsyncIterable as AsyncIterable, @@ -61,7 +61,7 @@ __all__ = [ "MutableSequence", ] if sys.version_info < (3, 14): - from typing import ByteString as ByteString # noqa: Y057 + from typing import ByteString as ByteString # noqa: Y057,UP035 __all__ += ["ByteString"] diff --git a/mypy/typeshed/stdlib/_contextvars.pyi b/mypy/typeshed/stdlib/_contextvars.pyi index c7d0814b3cb4..33df799a768c 100644 --- a/mypy/typeshed/stdlib/_contextvars.pyi +++ b/mypy/typeshed/stdlib/_contextvars.pyi @@ -1,11 +1,8 @@ -import sys from collections.abc import Callable, Iterator, Mapping +from types import GenericAlias from typing import Any, ClassVar, Generic, TypeVar, final, overload from typing_extensions import ParamSpec, Self -if sys.version_info >= (3, 9): - from types import GenericAlias - _T = TypeVar("_T") _D = TypeVar("_D") _P = ParamSpec("_P") @@ -27,8 +24,7 @@ class ContextVar(Generic[_T]): def get(self, default: _D, /) -> _D | _T: ... def set(self, value: _T, /) -> Token[_T]: ... def reset(self, token: Token[_T], /) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @final class Token(Generic[_T]): @@ -38,8 +34,7 @@ class Token(Generic[_T]): def old_value(self) -> Any: ... # returns either _T or MISSING, but that's hard to express MISSING: ClassVar[object] __hash__: ClassVar[None] # type: ignore[assignment] - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... def copy_context() -> Context: ... diff --git a/mypy/typeshed/stdlib/_ctypes.pyi b/mypy/typeshed/stdlib/_ctypes.pyi index 2977bf5afa94..6b79b9ff0a66 100644 --- a/mypy/typeshed/stdlib/_ctypes.pyi +++ b/mypy/typeshed/stdlib/_ctypes.pyi @@ -4,12 +4,10 @@ from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer 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, Generic, TypeVar, final, overload, type_check_only from typing_extensions import Self, TypeAlias -if sys.version_info >= (3, 9): - from types import GenericAlias - _T = TypeVar("_T") _CT = TypeVar("_CT", bound=_CData) @@ -288,7 +286,7 @@ class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): 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. + # 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 # here, because of a special feature of ctypes. # By default, when accessing an element of an Array[_CT], the returned object has type _CT. @@ -313,8 +311,7 @@ class Array(_CData, Generic[_CT], metaclass=_PyCArrayType): # Can't inherit from Sized because the metaclass conflict between # Sized and _CData prevents using _CDataMeta. def __len__(self) -> int: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... def addressof(obj: _CData | _CDataType, /) -> int: ... def alignment(obj_or_type: _CData | _CDataType | type[_CData | _CDataType], /) -> int: ... diff --git a/mypy/typeshed/stdlib/_curses.pyi b/mypy/typeshed/stdlib/_curses.pyi index 52c5185727e7..d7820c72c090 100644 --- a/mypy/typeshed/stdlib/_curses.pyi +++ b/mypy/typeshed/stdlib/_curses.pyi @@ -95,13 +95,14 @@ BUTTON4_DOUBLE_CLICKED: int BUTTON4_PRESSED: int BUTTON4_RELEASED: int BUTTON4_TRIPLE_CLICKED: int -# Darwin ncurses doesn't provide BUTTON5_* constants -if sys.version_info >= (3, 10) and sys.platform != "darwin": - BUTTON5_PRESSED: int - BUTTON5_RELEASED: int - BUTTON5_CLICKED: int - BUTTON5_DOUBLE_CLICKED: int - BUTTON5_TRIPLE_CLICKED: 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: int + BUTTON5_RELEASED: int + BUTTON5_CLICKED: int + BUTTON5_DOUBLE_CLICKED: int + BUTTON5_TRIPLE_CLICKED: int BUTTON_ALT: int BUTTON_CTRL: int BUTTON_SHIFT: int @@ -292,11 +293,8 @@ def erasechar() -> bytes: ... def filter() -> None: ... def flash() -> None: ... def flushinp() -> None: ... - -if sys.version_info >= (3, 9): - def get_escdelay() -> int: ... - def get_tabsize() -> int: ... - +def get_escdelay() -> int: ... +def get_tabsize() -> int: ... def getmouse() -> tuple[int, int, int, int, int]: ... def getsyx() -> tuple[int, int]: ... def getwin(file: SupportsRead[bytes], /) -> window: ... @@ -341,11 +339,8 @@ def resetty() -> None: ... def resize_term(nlines: int, ncols: int, /) -> None: ... def resizeterm(nlines: int, ncols: int, /) -> None: ... def savetty() -> None: ... - -if sys.version_info >= (3, 9): - def set_escdelay(ms: int, /) -> None: ... - def set_tabsize(size: int, /) -> None: ... - +def set_escdelay(ms: int, /) -> None: ... +def set_tabsize(size: int, /) -> None: ... def setsyx(y: int, x: int, /) -> None: ... def setupterm(term: str | None = None, fd: int = -1) -> None: ... def start_color() -> None: ... diff --git a/mypy/typeshed/stdlib/_dummy_thread.pyi b/mypy/typeshed/stdlib/_dummy_thread.pyi deleted file mode 100644 index 1182e53c66c3..000000000000 --- a/mypy/typeshed/stdlib/_dummy_thread.pyi +++ /dev/null @@ -1,33 +0,0 @@ -from collections.abc import Callable -from types import TracebackType -from typing import Any, NoReturn, overload -from typing_extensions import TypeVarTuple, Unpack - -__all__ = ["error", "start_new_thread", "exit", "get_ident", "allocate_lock", "interrupt_main", "LockType", "RLock"] - -_Ts = TypeVarTuple("_Ts") - -TIMEOUT_MAX: int -error = RuntimeError - -@overload -def start_new_thread(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]]) -> None: ... -@overload -def start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any]) -> None: ... -def exit() -> NoReturn: ... -def get_ident() -> int: ... -def allocate_lock() -> LockType: ... -def stack_size(size: int | None = None) -> int: ... - -class LockType: - locked_status: bool - def acquire(self, waitflag: bool | None = None, timeout: int = -1) -> bool: ... - def __enter__(self, waitflag: bool | None = None, timeout: int = -1) -> bool: ... - def __exit__(self, typ: type[BaseException] | None, val: BaseException | None, tb: TracebackType | None) -> None: ... - def release(self) -> bool: ... - def locked(self) -> bool: ... - -class RLock(LockType): - def release(self) -> None: ... # type: ignore[override] - -def interrupt_main() -> None: ... diff --git a/mypy/typeshed/stdlib/_dummy_threading.pyi b/mypy/typeshed/stdlib/_dummy_threading.pyi deleted file mode 100644 index 1b66fb414d7a..000000000000 --- a/mypy/typeshed/stdlib/_dummy_threading.pyi +++ /dev/null @@ -1,56 +0,0 @@ -from _threading_local import local as local -from _typeshed import ProfileFunction, TraceFunction -from threading import ( - TIMEOUT_MAX as TIMEOUT_MAX, - Barrier as Barrier, - BoundedSemaphore as BoundedSemaphore, - BrokenBarrierError as BrokenBarrierError, - Condition as Condition, - Event as Event, - ExceptHookArgs as ExceptHookArgs, - Lock as Lock, - RLock as RLock, - Semaphore as Semaphore, - Thread as Thread, - ThreadError as ThreadError, - Timer as Timer, - _DummyThread as _DummyThread, - _RLock as _RLock, - excepthook as excepthook, -) - -__all__ = [ - "get_ident", - "active_count", - "Condition", - "current_thread", - "enumerate", - "main_thread", - "TIMEOUT_MAX", - "Event", - "Lock", - "RLock", - "Semaphore", - "BoundedSemaphore", - "Thread", - "Barrier", - "BrokenBarrierError", - "Timer", - "ThreadError", - "setprofile", - "settrace", - "local", - "stack_size", - "ExceptHookArgs", - "excepthook", -] - -def active_count() -> int: ... -def current_thread() -> Thread: ... -def currentThread() -> Thread: ... -def get_ident() -> int: ... -def enumerate() -> list[Thread]: ... -def main_thread() -> Thread: ... -def settrace(func: TraceFunction) -> None: ... -def setprofile(func: ProfileFunction | None) -> None: ... -def stack_size(size: int | None = None) -> int: ... diff --git a/mypy/typeshed/stdlib/_hashlib.pyi b/mypy/typeshed/stdlib/_hashlib.pyi index e91f2cdb331c..746b1657e2db 100644 --- a/mypy/typeshed/stdlib/_hashlib.pyi +++ b/mypy/typeshed/stdlib/_hashlib.pyi @@ -37,53 +37,42 @@ class HASH: if sys.version_info >= (3, 10): class UnsupportedDigestmodError(ValueError): ... -if sys.version_info >= (3, 9): - class HASHXOF(HASH): - def digest(self, length: int) -> bytes: ... # type: ignore[override] - def hexdigest(self, length: int) -> str: ... # type: ignore[override] +class HASHXOF(HASH): + def digest(self, length: int) -> bytes: ... # type: ignore[override] + def hexdigest(self, length: int) -> str: ... # type: ignore[override] - @final - class HMAC: - @property - def digest_size(self) -> int: ... - @property - def block_size(self) -> int: ... - @property - def name(self) -> str: ... - def copy(self) -> Self: ... - def digest(self) -> bytes: ... - def hexdigest(self) -> str: ... - def update(self, msg: ReadableBuffer) -> None: ... - - @overload - 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 new(name: str, string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... - def openssl_md5(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... - def openssl_sha1(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... - def openssl_sha224(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... - def openssl_sha256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... - def openssl_sha384(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... - def openssl_sha512(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... - def openssl_sha3_224(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... - def openssl_sha3_256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... - def openssl_sha3_384(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... - def openssl_sha3_512(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... - def openssl_shake_128(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASHXOF: ... - def openssl_shake_256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASHXOF: ... - -else: - def new(name: str, string: ReadableBuffer = b"") -> HASH: ... - def openssl_md5(string: ReadableBuffer = b"") -> HASH: ... - def openssl_sha1(string: ReadableBuffer = b"") -> HASH: ... - def openssl_sha224(string: ReadableBuffer = b"") -> HASH: ... - def openssl_sha256(string: ReadableBuffer = b"") -> HASH: ... - def openssl_sha384(string: ReadableBuffer = b"") -> HASH: ... - def openssl_sha512(string: ReadableBuffer = b"") -> HASH: ... +@final +class HMAC: + @property + def digest_size(self) -> int: ... + @property + def block_size(self) -> int: ... + @property + def name(self) -> str: ... + def copy(self) -> Self: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, msg: ReadableBuffer) -> None: ... +@overload +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 new(name: str, string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... +def openssl_md5(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... +def openssl_sha1(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... +def openssl_sha224(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... +def openssl_sha256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... +def openssl_sha384(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... +def openssl_sha512(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... +def openssl_sha3_224(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... +def openssl_sha3_256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... +def openssl_sha3_384(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... +def openssl_sha3_512(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... +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 pbkdf2_hmac( hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: int | None = None diff --git a/mypy/typeshed/stdlib/_pickle.pyi b/mypy/typeshed/stdlib/_pickle.pyi index 50bbb6bc16cd..8e8afb600efa 100644 --- a/mypy/typeshed/stdlib/_pickle.pyi +++ b/mypy/typeshed/stdlib/_pickle.pyi @@ -1,4 +1,3 @@ -import sys from _typeshed import ReadableBuffer, SupportsWrite from collections.abc import Callable, Iterable, Iterator, Mapping from pickle import PickleBuffer as PickleBuffer @@ -75,10 +74,9 @@ class Pickler: def memo(self, value: PicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ... def dump(self, obj: Any, /) -> None: ... def clear_memo(self) -> None: ... - if sys.version_info >= (3, 13): - def persistent_id(self, obj: Any, /) -> Any: ... - else: - persistent_id: Callable[[Any], Any] + + # this method has no default implementation for Python < 3.13 + def persistent_id(self, obj: Any, /) -> Any: ... @type_check_only class UnpicklerMemoProxy: @@ -101,7 +99,6 @@ class Unpickler: 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: ... - if sys.version_info >= (3, 13): - def persistent_load(self, pid: Any, /) -> Any: ... - else: - persistent_load: Callable[[Any], Any] + + # this method has no default implementation for Python < 3.13 + def persistent_load(self, pid: Any, /) -> Any: ... diff --git a/mypy/typeshed/stdlib/_queue.pyi b/mypy/typeshed/stdlib/_queue.pyi index 0d4caea7442e..f98397b132ab 100644 --- a/mypy/typeshed/stdlib/_queue.pyi +++ b/mypy/typeshed/stdlib/_queue.pyi @@ -1,9 +1,6 @@ -import sys +from types import GenericAlias from typing import Any, Generic, TypeVar -if sys.version_info >= (3, 9): - from types import GenericAlias - _T = TypeVar("_T") class Empty(Exception): ... @@ -16,5 +13,4 @@ class SimpleQueue(Generic[_T]): def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: ... def put_nowait(self, item: _T) -> None: ... def qsize(self) -> int: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/_socket.pyi b/mypy/typeshed/stdlib/_socket.pyi index 649728257c1a..5399f4edf010 100644 --- a/mypy/typeshed/stdlib/_socket.pyi +++ b/mypy/typeshed/stdlib/_socket.pyi @@ -78,7 +78,7 @@ if sys.platform == "win32": SO_EXCLUSIVEADDRUSE: int if sys.platform != "win32": SO_REUSEPORT: int - if sys.platform != "darwin": + if sys.platform != "darwin" or sys.version_info >= (3, 13): SO_BINDTODEVICE: int if sys.platform != "win32" and sys.platform != "darwin": @@ -192,7 +192,7 @@ if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "lin IPPROTO_BIP: int # Not FreeBSD either IPPROTO_MOBILE: int # Not FreeBSD either IPPROTO_VRRP: int # Not FreeBSD either -if sys.version_info >= (3, 9) and sys.platform == "linux": +if sys.platform == "linux": # Availability: Linux >= 2.6.20, FreeBSD >= 10.1 IPPROTO_UDPLITE: int if sys.version_info >= (3, 10) and sys.platform == "linux": @@ -250,29 +250,26 @@ IPV6_RECVTCLASS: int IPV6_TCLASS: int IPV6_UNICAST_HOPS: int IPV6_V6ONLY: int -if sys.version_info >= (3, 9) or sys.platform != "darwin": - IPV6_DONTFRAG: int - IPV6_HOPLIMIT: int - IPV6_HOPOPTS: int - IPV6_PKTINFO: int - IPV6_RECVRTHDR: int - IPV6_RTHDR: int +IPV6_DONTFRAG: int +IPV6_HOPLIMIT: int +IPV6_HOPOPTS: int +IPV6_PKTINFO: int +IPV6_RECVRTHDR: int +IPV6_RTHDR: int if sys.platform != "win32": IPV6_RTHDR_TYPE_0: int - if sys.version_info >= (3, 9) or sys.platform != "darwin": - IPV6_DSTOPTS: int - IPV6_NEXTHOP: int - IPV6_PATHMTU: int - IPV6_RECVDSTOPTS: int - IPV6_RECVHOPLIMIT: int - IPV6_RECVHOPOPTS: int - IPV6_RECVPATHMTU: int - IPV6_RECVPKTINFO: int - IPV6_RTHDRDSTOPTS: int + IPV6_DSTOPTS: int + IPV6_NEXTHOP: int + IPV6_PATHMTU: int + IPV6_RECVDSTOPTS: int + IPV6_RECVHOPLIMIT: int + IPV6_RECVHOPOPTS: int + IPV6_RECVPATHMTU: int + IPV6_RECVPKTINFO: int + IPV6_RTHDRDSTOPTS: int if sys.platform != "win32" and sys.platform != "linux": - if sys.version_info >= (3, 9) or sys.platform != "darwin": - IPV6_USE_MIN_MTU: int + IPV6_USE_MIN_MTU: int EAI_AGAIN: int EAI_BADFLAGS: int @@ -414,16 +411,10 @@ if sys.platform == "linux": if sys.platform == "linux": # Availability: Linux >= 3.6 CAN_RAW_FD_FRAMES: int - -if sys.platform == "linux" and sys.version_info >= (3, 9): # Availability: Linux >= 4.1 CAN_RAW_JOIN_FILTERS: int - -if sys.platform == "linux": # Availability: Linux >= 2.6.25 CAN_ISOTP: int - -if sys.platform == "linux" and sys.version_info >= (3, 9): # Availability: Linux >= 5.4 CAN_J1939: int @@ -566,18 +557,16 @@ if sys.platform == "linux": SO_VM_SOCKETS_BUFFER_MIN_SIZE: int VM_SOCKETS_INVALID_VERSION: int # undocumented -if sys.platform != "win32" or sys.version_info >= (3, 9): - # Documented as only available on BSD, macOS, but empirically sometimes - # available on Windows - if sys.platform != "linux": - AF_LINK: int +# Documented as only available on BSD, macOS, but empirically sometimes +# available on Windows +if sys.platform != "linux": + AF_LINK: int has_ipv6: bool if sys.platform != "darwin" and sys.platform != "linux": - if sys.platform != "win32" or sys.version_info >= (3, 9): - BDADDR_ANY: str - BDADDR_LOCAL: str + BDADDR_ANY: str + BDADDR_LOCAL: str if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": HCI_FILTER: int # not in NetBSD or DragonFlyBSD @@ -649,8 +638,7 @@ if sys.platform == "darwin": SYSPROTO_CONTROL: int if sys.platform != "darwin" and sys.platform != "linux": - if sys.version_info >= (3, 9) or sys.platform != "win32": - AF_BLUETOOTH: int + AF_BLUETOOTH: int if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": # Linux and some BSD support is explicit in the docs @@ -659,10 +647,9 @@ if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "lin BTPROTO_L2CAP: int BTPROTO_SCO: int # not in FreeBSD if sys.platform != "darwin" and sys.platform != "linux": - if sys.version_info >= (3, 9) or sys.platform != "win32": - BTPROTO_RFCOMM: int + BTPROTO_RFCOMM: int -if sys.version_info >= (3, 9) and sys.platform == "linux": +if sys.platform == "linux": UDPLITE_RECV_CSCOV: int UDPLITE_SEND_CSCOV: int diff --git a/mypy/typeshed/stdlib/_tracemalloc.pyi b/mypy/typeshed/stdlib/_tracemalloc.pyi index b1aeb710233e..e9720f46692c 100644 --- a/mypy/typeshed/stdlib/_tracemalloc.pyi +++ b/mypy/typeshed/stdlib/_tracemalloc.pyi @@ -1,4 +1,3 @@ -import sys from collections.abc import Sequence from tracemalloc import _FrameTuple, _TraceTuple @@ -9,9 +8,6 @@ def get_traceback_limit() -> int: ... def get_traced_memory() -> tuple[int, int]: ... def get_tracemalloc_memory() -> int: ... def is_tracing() -> bool: ... - -if sys.version_info >= (3, 9): - def reset_peak() -> None: ... - +def reset_peak() -> None: ... def start(nframe: int = 1, /) -> None: ... def stop() -> None: ... diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index 99d21b67360a..a503637998d0 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -3,7 +3,6 @@ # See the README.md file in this directory for more information. import sys -import typing_extensions from collections.abc import Awaitable, Callable, Iterable, Sequence, Set as AbstractSet, Sized from dataclasses import Field from os import PathLike @@ -23,7 +22,7 @@ from typing import ( final, overload, ) -from typing_extensions import Buffer, LiteralString, TypeAlias +from typing_extensions import Buffer, LiteralString, Self as _Self, TypeAlias _KT = TypeVar("_KT") _KT_co = TypeVar("_KT_co", covariant=True) @@ -329,9 +328,9 @@ class structseq(Generic[_T_co]): # The second parameter will accept a dict of any kind without raising an exception, # but only has any meaning if you supply it a dict where the keys are strings. # https://github.com/python/typeshed/pull/6560#discussion_r767149830 - def __new__(cls, sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> typing_extensions.Self: ... + def __new__(cls, sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> _Self: ... if sys.version_info >= (3, 13): - def __replace__(self, **kwargs: Any) -> typing_extensions.Self: ... + def __replace__(self, **kwargs: Any) -> _Self: ... # Superset of typing.AnyStr that also includes LiteralString AnyOrLiteralStr = TypeVar("AnyOrLiteralStr", str, bytes, LiteralString) # noqa: Y001 diff --git a/mypy/typeshed/stdlib/_weakrefset.pyi b/mypy/typeshed/stdlib/_weakrefset.pyi index b55318528208..dad1ed7a4fb5 100644 --- a/mypy/typeshed/stdlib/_weakrefset.pyi +++ b/mypy/typeshed/stdlib/_weakrefset.pyi @@ -1,11 +1,8 @@ -import sys from collections.abc import Iterable, Iterator, MutableSet +from types import GenericAlias from typing import Any, ClassVar, TypeVar, overload from typing_extensions import Self -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = ["WeakSet"] _S = TypeVar("_S") @@ -48,5 +45,4 @@ class WeakSet(MutableSet[_T]): def union(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... def __or__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... def isdisjoint(self, other: Iterable[_T]) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/aifc.pyi b/mypy/typeshed/stdlib/aifc.pyi index 05bf53986b29..bfe12c6af2b0 100644 --- a/mypy/typeshed/stdlib/aifc.pyi +++ b/mypy/typeshed/stdlib/aifc.pyi @@ -1,12 +1,8 @@ -import sys from types import TracebackType from typing import IO, Any, Literal, NamedTuple, overload from typing_extensions import Self, TypeAlias -if sys.version_info >= (3, 9): - __all__ = ["Error", "open"] -else: - __all__ = ["Error", "open", "openfp"] +__all__ = ["Error", "open"] class Error(Exception): ... @@ -81,11 +77,3 @@ def open(f: _File, mode: Literal["r", "rb"]) -> Aifc_read: ... def open(f: _File, mode: Literal["w", "wb"]) -> Aifc_write: ... @overload def open(f: _File, mode: str | None = None) -> Any: ... - -if sys.version_info < (3, 9): - @overload - def openfp(f: _File, mode: Literal["r", "rb"]) -> Aifc_read: ... - @overload - def openfp(f: _File, mode: Literal["w", "wb"]) -> Aifc_write: ... - @overload - def openfp(f: _File, mode: str | None = None) -> Any: ... diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index 9dbd8c308b59..e97a2d2e16b6 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -17,6 +17,7 @@ __all__ = [ "MetavarTypeHelpFormatter", "Namespace", "Action", + "BooleanOptionalAction", "ONE_OR_MORE", "OPTIONAL", "PARSER", @@ -25,9 +26,6 @@ __all__ = [ "ZERO_OR_MORE", ] -if sys.version_info >= (3, 9): - __all__ += ["BooleanOptionalAction"] - _T = TypeVar("_T") _ActionT = TypeVar("_ActionT", bound=Action) _ArgumentParserT = TypeVar("_ArgumentParserT", bound=ArgumentParser) @@ -134,40 +132,22 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): _subparsers: _ArgumentGroup | None # Note: the constructor arguments are also used in _SubParsersAction.add_parser. - if sys.version_info >= (3, 9): - def __init__( - self, - prog: str | None = None, - usage: str | None = None, - description: str | None = None, - epilog: str | None = None, - parents: Sequence[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, - ) -> None: ... - else: - def __init__( - self, - prog: str | None = None, - usage: str | None = None, - description: str | None = None, - epilog: str | None = None, - parents: Sequence[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, - ) -> None: ... - + def __init__( + self, + prog: str | None = None, + usage: str | None = None, + description: str | None = None, + epilog: str | None = None, + parents: Sequence[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, + ) -> None: ... @overload def parse_args(self, args: Sequence[str] | None = None, namespace: None = None) -> Namespace: ... @overload @@ -354,8 +334,7 @@ class Action(_AttributeHolder): def __call__( self, parser: ArgumentParser, namespace: Namespace, values: str | Sequence[Any] | None, option_string: str | None = None ) -> None: ... - if sys.version_info >= (3, 9): - def format_usage(self) -> str: ... + def format_usage(self) -> str: ... if sys.version_info >= (3, 12): class BooleanOptionalAction(Action): @@ -420,7 +399,7 @@ if sys.version_info >= (3, 12): metavar: str | tuple[str, ...] | None = sentinel, ) -> None: ... -elif sys.version_info >= (3, 9): +else: class BooleanOptionalAction(Action): @overload def __init__( @@ -715,29 +694,6 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]): exit_on_error: bool = ..., **kwargs: Any, # Accepting any additional kwargs for custom parser classes ) -> _ArgumentParserT: ... - elif sys.version_info >= (3, 9): - def add_parser( - self, - name: str, - *, - help: str | None = ..., - aliases: Sequence[str] = ..., - # Kwargs from ArgumentParser constructor - prog: str | None = ..., - usage: str | None = ..., - description: str | None = ..., - epilog: str | None = ..., - parents: Sequence[_ArgumentParserT] = ..., - formatter_class: _FormatterClass = ..., - prefix_chars: str = ..., - fromfile_prefix_chars: str | None = ..., - argument_default: Any = ..., - conflict_handler: str = ..., - add_help: bool = ..., - allow_abbrev: bool = ..., - exit_on_error: bool = ..., - **kwargs: Any, # Accepting any additional kwargs for custom parser classes - ) -> _ArgumentParserT: ... else: def add_parser( self, @@ -758,6 +714,7 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]): conflict_handler: str = ..., add_help: bool = ..., allow_abbrev: bool = ..., + exit_on_error: bool = ..., **kwargs: Any, # Accepting any additional kwargs for custom parser classes ) -> _ArgumentParserT: ... diff --git a/mypy/typeshed/stdlib/array.pyi b/mypy/typeshed/stdlib/array.pyi index 19ec8c1e78f9..bd96c9bc2d31 100644 --- a/mypy/typeshed/stdlib/array.pyi +++ b/mypy/typeshed/stdlib/array.pyi @@ -1,14 +1,10 @@ import sys from _typeshed import ReadableBuffer, SupportsRead, SupportsWrite -from collections.abc import Iterable - -# pytype crashes if array inherits from collections.abc.MutableSequence instead of typing.MutableSequence -from typing import Any, ClassVar, Literal, MutableSequence, SupportsIndex, TypeVar, overload # noqa: Y022 +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 -if sys.version_info >= (3, 12): - from types import GenericAlias - _IntTypeCode: TypeAlias = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] _FloatTypeCode: TypeAlias = Literal["f", "d"] _UnicodeTypeCode: TypeAlias = Literal["u"] @@ -60,9 +56,6 @@ class array(MutableSequence[_T]): def tofile(self, f: SupportsWrite[bytes], /) -> None: ... def tolist(self) -> list[_T]: ... def tounicode(self) -> str: ... - if sys.version_info < (3, 9): - def fromstring(self, buffer: str | ReadableBuffer, /) -> None: ... - def tostring(self) -> bytes: ... __hash__: ClassVar[None] # type: ignore[assignment] def __len__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/ast.pyi b/mypy/typeshed/stdlib/ast.pyi index 7a4438a33fbc..1a3d3e97d11e 100644 --- a/mypy/typeshed/stdlib/ast.pyi +++ b/mypy/typeshed/stdlib/ast.pyi @@ -1144,8 +1144,7 @@ class Tuple(expr): __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, 9): - dims: list[expr] + dims: list[expr] if sys.version_info >= (3, 13): def __init__(self, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ... else: @@ -1155,16 +1154,10 @@ class Tuple(expr): def __replace__(self, *, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ... @deprecated("Deprecated since Python 3.9.") -class slice(AST): ... # deprecated and moved to ast.py for >= (3, 9) +class slice(AST): ... -if sys.version_info >= (3, 9): - _Slice: typing_extensions.TypeAlias = expr - _SliceAttributes: typing_extensions.TypeAlias = _Attributes -else: - # alias for use with variables named slice - _Slice: typing_extensions.TypeAlias = slice - - class _SliceAttributes(TypedDict): ... +_Slice: typing_extensions.TypeAlias = expr +_SliceAttributes: typing_extensions.TypeAlias = _Attributes class Slice(_Slice): if sys.version_info >= (3, 10): @@ -1187,37 +1180,26 @@ class Slice(_Slice): ) -> Self: ... @deprecated("Deprecated since Python 3.9. Use ast.Tuple instead.") -class ExtSlice(slice): # deprecated and moved to ast.py if sys.version_info >= (3, 9) - if sys.version_info >= (3, 9): - def __new__(cls, dims: Iterable[slice] = (), **kwargs: Unpack[_SliceAttributes]) -> Tuple: ... # type: ignore[misc] - else: - dims: list[slice] - def __init__(self, dims: list[slice], **kwargs: Unpack[_SliceAttributes]) -> None: ... +class ExtSlice(slice): + def __new__(cls, dims: Iterable[slice] = (), **kwargs: Unpack[_SliceAttributes]) -> Tuple: ... # type: ignore[misc] @deprecated("Deprecated since Python 3.9. Use the index value directly instead.") -class Index(slice): # deprecated and moved to ast.py if sys.version_info >= (3, 9) - if sys.version_info >= (3, 9): - def __new__(cls, value: expr, **kwargs: Unpack[_SliceAttributes]) -> expr: ... # type: ignore[misc] - else: - value: expr - def __init__(self, value: expr, **kwargs: Unpack[_SliceAttributes]) -> None: ... +class Index(slice): + def __new__(cls, value: expr, **kwargs: Unpack[_SliceAttributes]) -> expr: ... # type: ignore[misc] class expr_context(AST): ... @deprecated("Deprecated since Python 3.9. Unused in Python 3.") -class AugLoad(expr_context): ... # deprecated and moved to ast.py if sys.version_info >= (3, 9) +class AugLoad(expr_context): ... @deprecated("Deprecated since Python 3.9. Unused in Python 3.") -class AugStore(expr_context): ... # deprecated and moved to ast.py if sys.version_info >= (3, 9) +class AugStore(expr_context): ... @deprecated("Deprecated since Python 3.9. Unused in Python 3.") -class Param(expr_context): ... # deprecated and moved to ast.py if sys.version_info >= (3, 9) +class Param(expr_context): ... @deprecated("Deprecated since Python 3.9. Unused in Python 3.") -class Suite(mod): # deprecated and moved to ast.py if sys.version_info >= (3, 9) - if sys.version_info < (3, 9): - body: list[stmt] - def __init__(self, body: list[stmt]) -> None: ... +class Suite(mod): ... class Load(expr_context): ... class Store(expr_context): ... @@ -1702,8 +1684,7 @@ if sys.version_info >= (3, 12): ) -> Self: ... class _ABC(type): - if sys.version_info >= (3, 9): - def __init__(cls, *args: Unused) -> None: ... + def __init__(cls, *args: Unused) -> None: ... if sys.version_info < (3, 14): @deprecated("Replaced by ast.Constant; removed in Python 3.14") @@ -1894,14 +1875,11 @@ if sys.version_info >= (3, 13): show_empty: bool = False, ) -> str: ... -elif sys.version_info >= (3, 9): +else: def dump( node: AST, annotate_fields: bool = True, include_attributes: bool = False, *, indent: int | str | None = None ) -> str: ... -else: - def dump(node: AST, annotate_fields: bool = True, include_attributes: bool = False) -> str: ... - def copy_location(new_node: _T, old_node: AST) -> _T: ... def fix_missing_locations(node: _T) -> _T: ... def increment_lineno(node: _T, n: int = 1) -> _T: ... @@ -1915,8 +1893,12 @@ if sys.version_info >= (3, 14): def compare(left: AST, right: AST, /, *, compare_attributes: bool = False) -> bool: ... class NodeVisitor: + # All visit methods below can be overwritten by subclasses and return an + # arbitrary value, which is passed to the caller. def visit(self, node: AST) -> Any: ... def generic_visit(self, node: AST) -> Any: ... + # The following visit methods are not defined on NodeVisitor, but can + # be implemented by subclasses and are called during a visit if defined. def visit_Module(self, node: Module) -> Any: ... def visit_Interactive(self, node: Interactive) -> Any: ... def visit_Expression(self, node: Expression) -> Any: ... @@ -2059,8 +2041,5 @@ class NodeTransformer(NodeVisitor): # The usual return type is AST | None, but Iterable[AST] # is also allowed in some cases -- this needs to be mapped. -if sys.version_info >= (3, 9): - def unparse(ast_obj: AST) -> str: ... - -if sys.version_info >= (3, 9): - def main() -> None: ... +def unparse(ast_obj: AST) -> str: ... +def main() -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/__init__.pyi b/mypy/typeshed/stdlib/asyncio/__init__.pyi index e47f640a1f9b..c314acbea1ca 100644 --- a/mypy/typeshed/stdlib/asyncio/__init__.pyi +++ b/mypy/typeshed/stdlib/asyncio/__init__.pyi @@ -18,11 +18,9 @@ from .runners import * from .streams import * from .subprocess import * from .tasks import * +from .threads import * from .transports import * -if sys.version_info >= (3, 9): - from .threads import * - if sys.version_info >= (3, 11): from .taskgroups import * from .timeouts import * @@ -412,7 +410,7 @@ if sys.platform == "win32": "WindowsSelectorEventLoopPolicy", # from windows_events "WindowsProactorEventLoopPolicy", # from windows_events ) - elif sys.version_info >= (3, 9): + else: __all__ = ( "BaseEventLoop", # from base_events "Server", # from base_events @@ -499,91 +497,6 @@ if sys.platform == "win32": "WindowsSelectorEventLoopPolicy", # from windows_events "WindowsProactorEventLoopPolicy", # from windows_events ) - else: - __all__ = ( - "BaseEventLoop", # from base_events - "coroutine", # from coroutines - "iscoroutinefunction", # from coroutines - "iscoroutine", # from coroutines - "AbstractEventLoopPolicy", # from events - "AbstractEventLoop", # from events - "AbstractServer", # from events - "Handle", # from events - "TimerHandle", # from events - "get_event_loop_policy", # from events - "set_event_loop_policy", # from events - "get_event_loop", # from events - "set_event_loop", # from events - "new_event_loop", # from events - "get_child_watcher", # from events - "set_child_watcher", # from events - "_set_running_loop", # from events - "get_running_loop", # from events - "_get_running_loop", # from events - "CancelledError", # from exceptions - "InvalidStateError", # from exceptions - "TimeoutError", # from exceptions - "IncompleteReadError", # from exceptions - "LimitOverrunError", # from exceptions - "SendfileNotAvailableError", # from exceptions - "Future", # from futures - "wrap_future", # from futures - "isfuture", # from futures - "Lock", # from locks - "Event", # from locks - "Condition", # from locks - "Semaphore", # from locks - "BoundedSemaphore", # from locks - "BaseProtocol", # from protocols - "Protocol", # from protocols - "DatagramProtocol", # from protocols - "SubprocessProtocol", # from protocols - "BufferedProtocol", # from protocols - "run", # from runners - "Queue", # from queues - "PriorityQueue", # from queues - "LifoQueue", # from queues - "QueueFull", # from queues - "QueueEmpty", # from queues - "StreamReader", # from streams - "StreamWriter", # from streams - "StreamReaderProtocol", # from streams - "open_connection", # from streams - "start_server", # from streams - "create_subprocess_exec", # from subprocess - "create_subprocess_shell", # from subprocess - "Task", # from tasks - "create_task", # from tasks - "FIRST_COMPLETED", # from tasks - "FIRST_EXCEPTION", # from tasks - "ALL_COMPLETED", # from tasks - "wait", # from tasks - "wait_for", # from tasks - "as_completed", # from tasks - "sleep", # from tasks - "gather", # from tasks - "shield", # from tasks - "ensure_future", # from tasks - "run_coroutine_threadsafe", # from tasks - "current_task", # from tasks - "all_tasks", # from tasks - "_register_task", # from tasks - "_unregister_task", # from tasks - "_enter_task", # from tasks - "_leave_task", # from tasks - "BaseTransport", # from transports - "ReadTransport", # from transports - "WriteTransport", # from transports - "Transport", # from transports - "DatagramTransport", # from transports - "SubprocessTransport", # from transports - "SelectorEventLoop", # from windows_events - "ProactorEventLoop", # from windows_events - "IocpProactor", # from windows_events - "DefaultEventLoopPolicy", # from windows_events - "WindowsSelectorEventLoopPolicy", # from windows_events - "WindowsProactorEventLoopPolicy", # from windows_events - ) else: if sys.version_info >= (3, 14): __all__ = ( @@ -974,7 +887,7 @@ else: "ThreadedChildWatcher", # from unix_events "DefaultEventLoopPolicy", # from unix_events ) - elif sys.version_info >= (3, 9): + else: __all__ = ( "BaseEventLoop", # from base_events "Server", # from base_events @@ -1065,94 +978,6 @@ else: "ThreadedChildWatcher", # from unix_events "DefaultEventLoopPolicy", # from unix_events ) - else: - __all__ = ( - "BaseEventLoop", # from base_events - "coroutine", # from coroutines - "iscoroutinefunction", # from coroutines - "iscoroutine", # from coroutines - "AbstractEventLoopPolicy", # from events - "AbstractEventLoop", # from events - "AbstractServer", # from events - "Handle", # from events - "TimerHandle", # from events - "get_event_loop_policy", # from events - "set_event_loop_policy", # from events - "get_event_loop", # from events - "set_event_loop", # from events - "new_event_loop", # from events - "get_child_watcher", # from events - "set_child_watcher", # from events - "_set_running_loop", # from events - "get_running_loop", # from events - "_get_running_loop", # from events - "CancelledError", # from exceptions - "InvalidStateError", # from exceptions - "TimeoutError", # from exceptions - "IncompleteReadError", # from exceptions - "LimitOverrunError", # from exceptions - "SendfileNotAvailableError", # from exceptions - "Future", # from futures - "wrap_future", # from futures - "isfuture", # from futures - "Lock", # from locks - "Event", # from locks - "Condition", # from locks - "Semaphore", # from locks - "BoundedSemaphore", # from locks - "BaseProtocol", # from protocols - "Protocol", # from protocols - "DatagramProtocol", # from protocols - "SubprocessProtocol", # from protocols - "BufferedProtocol", # from protocols - "run", # from runners - "Queue", # from queues - "PriorityQueue", # from queues - "LifoQueue", # from queues - "QueueFull", # from queues - "QueueEmpty", # from queues - "StreamReader", # from streams - "StreamWriter", # from streams - "StreamReaderProtocol", # from streams - "open_connection", # from streams - "start_server", # from streams - "open_unix_connection", # from streams - "start_unix_server", # from streams - "create_subprocess_exec", # from subprocess - "create_subprocess_shell", # from subprocess - "Task", # from tasks - "create_task", # from tasks - "FIRST_COMPLETED", # from tasks - "FIRST_EXCEPTION", # from tasks - "ALL_COMPLETED", # from tasks - "wait", # from tasks - "wait_for", # from tasks - "as_completed", # from tasks - "sleep", # from tasks - "gather", # from tasks - "shield", # from tasks - "ensure_future", # from tasks - "run_coroutine_threadsafe", # from tasks - "current_task", # from tasks - "all_tasks", # from tasks - "_register_task", # from tasks - "_unregister_task", # from tasks - "_enter_task", # from tasks - "_leave_task", # from tasks - "BaseTransport", # from transports - "ReadTransport", # from transports - "WriteTransport", # from transports - "Transport", # from transports - "DatagramTransport", # from transports - "SubprocessTransport", # from transports - "SelectorEventLoop", # from unix_events - "AbstractChildWatcher", # from unix_events - "SafeChildWatcher", # from unix_events - "FastChildWatcher", # from unix_events - "MultiLoopChildWatcher", # from unix_events - "ThreadedChildWatcher", # from unix_events - "DefaultEventLoopPolicy", # from unix_events - ) _T_co = TypeVar("_T_co", covariant=True) diff --git a/mypy/typeshed/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi index 9527e9d052aa..cad7dde40b01 100644 --- a/mypy/typeshed/stdlib/asyncio/base_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_events.pyi @@ -15,10 +15,7 @@ from typing import IO, Any, Literal, TypeVar, overload from typing_extensions import TypeAlias, TypeVarTuple, Unpack # Keep asyncio.__all__ updated with any changes to __all__ here -if sys.version_info >= (3, 9): - __all__ = ("BaseEventLoop", "Server") -else: - __all__ = ("BaseEventLoop",) +__all__ = ("BaseEventLoop", "Server") _T = TypeVar("_T") _Ts = TypeVarTuple("_Ts") @@ -485,7 +482,7 @@ class BaseEventLoop(AbstractEventLoop): def set_debug(self, enabled: bool) -> None: ... if sys.version_info >= (3, 12): async def shutdown_default_executor(self, timeout: float | None = None) -> None: ... - elif sys.version_info >= (3, 9): + else: async def shutdown_default_executor(self) -> None: ... def __del__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index a9f7d24237a4..afe912d01fe1 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -138,27 +138,19 @@ class AbstractEventLoop: @abstractmethod async def shutdown_asyncgens(self) -> None: ... # Methods scheduling callbacks. All these return Handles. - if sys.version_info >= (3, 9): # "context" added in 3.9.10/3.10.2 - @abstractmethod - def call_soon( - self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None - ) -> Handle: ... - @abstractmethod - def call_later( - self, delay: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None - ) -> TimerHandle: ... - @abstractmethod - def call_at( - self, when: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None - ) -> TimerHandle: ... - else: - @abstractmethod - def call_soon(self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> Handle: ... - @abstractmethod - def call_later(self, delay: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> TimerHandle: ... - @abstractmethod - def call_at(self, when: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> TimerHandle: ... - + # "context" added in 3.9.10/3.10.2 for call_* + @abstractmethod + def call_soon( + self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> Handle: ... + @abstractmethod + def call_later( + self, delay: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> TimerHandle: ... + @abstractmethod + def call_at( + self, when: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> TimerHandle: ... @abstractmethod def time(self) -> float: ... # Future methods @@ -179,15 +171,11 @@ class AbstractEventLoop: @abstractmethod def get_task_factory(self) -> _TaskFactory | None: ... # Methods for interacting with threads - if sys.version_info >= (3, 9): # "context" added in 3.9.10/3.10.2 - @abstractmethod - def call_soon_threadsafe( - self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None - ) -> Handle: ... - else: - @abstractmethod - def call_soon_threadsafe(self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> Handle: ... - + # "context" added in 3.9.10/3.10.2 + @abstractmethod + def call_soon_threadsafe( + self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None + ) -> Handle: ... @abstractmethod def run_in_executor(self, executor: Executor | None, func: Callable[[Unpack[_Ts]], _T], *args: Unpack[_Ts]) -> Future[_T]: ... @abstractmethod @@ -607,9 +595,8 @@ class AbstractEventLoop: def get_debug(self) -> bool: ... @abstractmethod def set_debug(self, enabled: bool) -> None: ... - if sys.version_info >= (3, 9): - @abstractmethod - async def shutdown_default_executor(self) -> None: ... + @abstractmethod + async def shutdown_default_executor(self) -> None: ... class AbstractEventLoopPolicy: @abstractmethod diff --git a/mypy/typeshed/stdlib/asyncio/locks.pyi b/mypy/typeshed/stdlib/asyncio/locks.pyi index 4eef69dee5c3..17390b0c5a0e 100644 --- a/mypy/typeshed/stdlib/asyncio/locks.pyi +++ b/mypy/typeshed/stdlib/asyncio/locks.pyi @@ -2,7 +2,7 @@ import enum import sys from _typeshed import Unused from collections import deque -from collections.abc import Callable, Generator +from collections.abc import Callable from types import TracebackType from typing import Any, Literal, TypeVar from typing_extensions import Self @@ -23,29 +23,11 @@ else: _T = TypeVar("_T") -if sys.version_info >= (3, 9): - class _ContextManagerMixin: - async def __aenter__(self) -> None: ... - async def __aexit__( - self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None - ) -> None: ... - -else: - class _ContextManager: - def __init__(self, lock: Lock | Semaphore) -> None: ... - def __enter__(self) -> None: ... - def __exit__(self, *args: Unused) -> None: ... - - class _ContextManagerMixin: - # Apparently this exists to *prohibit* use as a context manager. - # def __enter__(self) -> NoReturn: ... see: https://github.com/python/typing/issues/1043 - # def __exit__(self, *args: Any) -> None: ... - def __iter__(self) -> Generator[Any, None, _ContextManager]: ... - def __await__(self) -> Generator[Any, None, _ContextManager]: ... - async def __aenter__(self) -> None: ... - async def __aexit__( - self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None - ) -> None: ... +class _ContextManagerMixin: + async def __aenter__(self) -> None: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None + ) -> None: ... class Lock(_ContextManagerMixin, _LoopBoundMixin): _waiters: deque[Future[Any]] | None diff --git a/mypy/typeshed/stdlib/asyncio/queues.pyi b/mypy/typeshed/stdlib/asyncio/queues.pyi index d287fe779297..63cd98f53da3 100644 --- a/mypy/typeshed/stdlib/asyncio/queues.pyi +++ b/mypy/typeshed/stdlib/asyncio/queues.pyi @@ -1,10 +1,8 @@ import sys from asyncio.events import AbstractEventLoop +from types import GenericAlias from typing import Any, Generic, TypeVar -if sys.version_info >= (3, 9): - from types import GenericAlias - if sys.version_info >= (3, 10): from .mixins import _LoopBoundMixin else: @@ -48,8 +46,7 @@ class Queue(Generic[_T], _LoopBoundMixin): # noqa: Y059 def get_nowait(self) -> _T: ... async def join(self) -> None: ... def task_done(self) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, type: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, type: Any, /) -> GenericAlias: ... if sys.version_info >= (3, 13): def shutdown(self, immediate: bool = False) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index f6ee109915e0..e42151213e69 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -407,10 +407,8 @@ else: if sys.version_info >= (3, 12): _TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co] -elif sys.version_info >= (3, 9): - _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co] else: - _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Awaitable[_T_co] + _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co] def all_tasks(loop: AbstractEventLoop | None = None) -> set[Task[Any]]: ... diff --git a/mypy/typeshed/stdlib/asyncio/unix_events.pyi b/mypy/typeshed/stdlib/asyncio/unix_events.pyi index abf5d7ffd699..79f99fbe37f0 100644 --- a/mypy/typeshed/stdlib/asyncio/unix_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/unix_events.pyi @@ -30,7 +30,7 @@ if sys.platform != "win32": "DefaultEventLoopPolicy", "EventLoop", ) - elif sys.version_info >= (3, 9): + else: # adds PidfdChildWatcher __all__ = ( "SelectorEventLoop", @@ -42,16 +42,6 @@ if sys.platform != "win32": "ThreadedChildWatcher", "DefaultEventLoopPolicy", ) - else: - __all__ = ( - "SelectorEventLoop", - "AbstractChildWatcher", - "SafeChildWatcher", - "FastChildWatcher", - "MultiLoopChildWatcher", - "ThreadedChildWatcher", - "DefaultEventLoopPolicy", - ) # This is also technically not available on Win, # but other parts of typeshed need this definition. @@ -239,16 +229,15 @@ if sys.platform != "win32": def remove_child_handler(self, pid: int) -> bool: ... def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... - if sys.version_info >= (3, 9): - class PidfdChildWatcher(AbstractChildWatcher): - def __enter__(self) -> Self: ... - def __exit__( - self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None - ) -> None: ... - def is_active(self) -> bool: ... - def close(self) -> None: ... - def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... - def add_child_handler( - self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] - ) -> None: ... - def remove_child_handler(self, pid: int) -> bool: ... + class PidfdChildWatcher(AbstractChildWatcher): + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + ) -> None: ... + def is_active(self) -> bool: ... + def close(self) -> None: ... + def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... + def add_child_handler( + self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts] + ) -> None: ... + def remove_child_handler(self, pid: int) -> bool: ... diff --git a/mypy/typeshed/stdlib/base64.pyi b/mypy/typeshed/stdlib/base64.pyi index 8be4cfe69de0..279d74a94ebe 100644 --- a/mypy/typeshed/stdlib/base64.pyi +++ b/mypy/typeshed/stdlib/base64.pyi @@ -56,10 +56,6 @@ def encode(input: IO[bytes], output: IO[bytes]) -> None: ... def encodebytes(s: ReadableBuffer) -> bytes: ... def decodebytes(s: ReadableBuffer) -> bytes: ... -if sys.version_info < (3, 9): - def encodestring(s: ReadableBuffer) -> bytes: ... - def decodestring(s: ReadableBuffer) -> bytes: ... - if sys.version_info >= (3, 13): def z85encode(s: ReadableBuffer) -> bytes: ... def z85decode(s: str | ReadableBuffer) -> bytes: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index dc8ddb8fe7a8..e9b0d51ebf65 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -32,11 +32,11 @@ 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 types import CellType, CodeType, TracebackType +from types import CellType, CodeType, GenericAlias, TracebackType # mypy crashes if any of {ByteString, Sequence, MutableSequence, Mapping, MutableMapping} # are imported from collections.abc in builtins.pyi -from typing import ( # noqa: Y022 +from typing import ( # noqa: Y022,UP035 IO, Any, BinaryIO, @@ -71,9 +71,6 @@ from typing_extensions import ( # noqa: Y023 deprecated, ) -if sys.version_info >= (3, 9): - from types import GenericAlias - _T = TypeVar("_T") _I = TypeVar("_I", default=int) _T_co = TypeVar("_T_co", covariant=True) @@ -376,10 +373,8 @@ class float: def __rpow__(self, value: float, mod: None = None, /) -> Any: ... def __getnewargs__(self) -> tuple[float]: ... def __trunc__(self) -> int: ... - if sys.version_info >= (3, 9): - def __ceil__(self) -> int: ... - def __floor__(self) -> int: ... - + def __ceil__(self) -> int: ... + def __floor__(self) -> int: ... @overload def __round__(self, ndigits: None = None, /) -> int: ... @overload @@ -478,10 +473,9 @@ class str(Sequence[str]): def replace(self, old: str, new: str, /, count: SupportsIndex = -1) -> str: ... # type: ignore[misc] else: def replace(self, old: str, new: str, count: SupportsIndex = -1, /) -> str: ... # type: ignore[misc] - if sys.version_info >= (3, 9): - def removeprefix(self, prefix: str, /) -> str: ... # type: ignore[misc] - def removesuffix(self, suffix: str, /) -> str: ... # type: ignore[misc] + 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 = ..., end: SupportsIndex | None = ..., /) -> int: ... def rindex(self, sub: str, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., /) -> int: ... def rjust(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] @@ -568,10 +562,8 @@ class bytes(Sequence[int]): 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, 9): - def removeprefix(self, prefix: ReadableBuffer, /) -> bytes: ... - def removesuffix(self, suffix: ReadableBuffer, /) -> bytes: ... - + def removeprefix(self, prefix: ReadableBuffer, /) -> bytes: ... + def removesuffix(self, suffix: ReadableBuffer, /) -> bytes: ... def rfind( self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / ) -> int: ... @@ -673,10 +665,8 @@ class bytearray(MutableSequence[int]): def partition(self, sep: ReadableBuffer, /) -> tuple[bytearray, bytearray, bytearray]: ... def pop(self, index: int = -1, /) -> int: ... def remove(self, value: int, /) -> None: ... - if sys.version_info >= (3, 9): - def removeprefix(self, prefix: ReadableBuffer, /) -> bytearray: ... - def removesuffix(self, suffix: ReadableBuffer, /) -> bytearray: ... - + def removeprefix(self, prefix: ReadableBuffer, /) -> bytearray: ... + def removesuffix(self, suffix: ReadableBuffer, /) -> bytearray: ... def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytearray: ... def rfind( self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = ..., end: SupportsIndex | None = ..., / @@ -911,8 +901,7 @@ class tuple(Sequence[_T_co]): def __rmul__(self, value: SupportsIndex, /) -> tuple[_T_co, ...]: ... def count(self, value: Any, /) -> int: ... def index(self, value: Any, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... # Doesn't exist at runtime, but deleting this breaks mypy and pyright. See: # https://github.com/python/typeshed/issues/7580 @@ -994,8 +983,7 @@ class list(MutableSequence[_T]): def __lt__(self, value: list[_T], /) -> bool: ... def __le__(self, value: list[_T], /) -> bool: ... def __eq__(self, value: object, /) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class dict(MutableMapping[_KT, _VT]): # __init__ should be kept roughly in line with `collections.UserDict.__init__`, which has similar semantics @@ -1064,21 +1052,20 @@ class dict(MutableMapping[_KT, _VT]): def __eq__(self, value: object, /) -> bool: ... def __reversed__(self) -> Iterator[_KT]: ... __hash__: ClassVar[None] # type: ignore[assignment] - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... - @overload - def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... - @overload - def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... - @overload - def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... - @overload - def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... - # dict.__ior__ should be kept roughly in line with MutableMapping.update() - @overload # type: ignore[misc] - def __ior__(self, value: SupportsKeysAndGetItem[_KT, _VT], /) -> Self: ... - @overload - def __ior__(self, value: Iterable[tuple[_KT, _VT]], /) -> Self: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + @overload + def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload + def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + @overload + def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ... + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... + # dict.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self, value: SupportsKeysAndGetItem[_KT, _VT], /) -> Self: ... + @overload + def __ior__(self, value: Iterable[tuple[_KT, _VT]], /) -> Self: ... class set(MutableSet[_T]): @overload @@ -1117,8 +1104,7 @@ class set(MutableSet[_T]): def __gt__(self, value: AbstractSet[object], /) -> bool: ... def __eq__(self, value: object, /) -> bool: ... __hash__: ClassVar[None] # type: ignore[assignment] - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class frozenset(AbstractSet[_T_co]): @overload @@ -1146,15 +1132,13 @@ class frozenset(AbstractSet[_T_co]): def __gt__(self, value: AbstractSet[object], /) -> bool: ... def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class enumerate(Iterator[tuple[int, _T]]): def __new__(cls, iterable: Iterable[_T], start: int = 0) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> tuple[int, _T]: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @final class range(Sequence[int]): @@ -1199,6 +1183,9 @@ 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: ... diff --git a/mypy/typeshed/stdlib/bz2.pyi b/mypy/typeshed/stdlib/bz2.pyi index 2f869f9697f4..3b21fbcf7117 100644 --- a/mypy/typeshed/stdlib/bz2.pyi +++ b/mypy/typeshed/stdlib/bz2.pyi @@ -1,10 +1,9 @@ import _compression -import sys from _bz2 import BZ2Compressor as BZ2Compressor, BZ2Decompressor as BZ2Decompressor from _compression import BaseStream from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer from collections.abc import Iterable -from typing import IO, Any, Literal, Protocol, SupportsIndex, TextIO, overload +from typing import IO, Literal, Protocol, SupportsIndex, TextIO, overload from typing_extensions import Self, TypeAlias __all__ = ["BZ2File", "BZ2Compressor", "BZ2Decompressor", "open", "compress", "decompress"] @@ -94,33 +93,14 @@ def open( class BZ2File(BaseStream, IO[bytes]): def __enter__(self) -> Self: ... - if sys.version_info >= (3, 9): - @overload - def __init__(self, filename: _WritableFileobj, mode: _WriteBinaryMode, *, compresslevel: int = 9) -> None: ... - @overload - def __init__(self, filename: _ReadableFileobj, mode: _ReadBinaryMode = "r", *, compresslevel: int = 9) -> None: ... - @overload - def __init__( - self, filename: StrOrBytesPath, mode: _ReadBinaryMode | _WriteBinaryMode = "r", *, compresslevel: int = 9 - ) -> None: ... - else: - @overload - def __init__( - self, filename: _WritableFileobj, mode: _WriteBinaryMode, buffering: Any | None = None, compresslevel: int = 9 - ) -> None: ... - @overload - def __init__( - self, filename: _ReadableFileobj, mode: _ReadBinaryMode = "r", buffering: Any | None = None, compresslevel: int = 9 - ) -> None: ... - @overload - def __init__( - self, - filename: StrOrBytesPath, - mode: _ReadBinaryMode | _WriteBinaryMode = "r", - buffering: Any | None = None, - compresslevel: int = 9, - ) -> None: ... - + @overload + def __init__(self, filename: _WritableFileobj, mode: _WriteBinaryMode, *, compresslevel: int = 9) -> None: ... + @overload + def __init__(self, filename: _ReadableFileobj, mode: _ReadBinaryMode = "r", *, compresslevel: int = 9) -> None: ... + @overload + 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/code.pyi b/mypy/typeshed/stdlib/code.pyi index 54971f3ae93c..16721927c236 100644 --- a/mypy/typeshed/stdlib/code.pyi +++ b/mypy/typeshed/stdlib/code.pyi @@ -1,15 +1,15 @@ import sys from codeop import CommandCompiler -from collections.abc import Callable, Mapping +from collections.abc import Callable from types import CodeType from typing import Any __all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact", "compile_command"] class InteractiveInterpreter: - locals: Mapping[str, Any] # undocumented + locals: dict[str, Any] # undocumented compile: CommandCompiler # undocumented - def __init__(self, locals: Mapping[str, Any] | None = None) -> None: ... + def __init__(self, locals: dict[str, Any] | None = None) -> None: ... def runsource(self, source: str, filename: str = "", symbol: str = "single") -> bool: ... def runcode(self, code: CodeType) -> None: ... if sys.version_info >= (3, 13): @@ -25,11 +25,11 @@ class InteractiveConsole(InteractiveInterpreter): filename: str # undocumented if sys.version_info >= (3, 13): def __init__( - self, locals: Mapping[str, Any] | None = None, filename: str = "", *, local_exit: bool = False + self, locals: dict[str, Any] | None = None, filename: str = "", *, local_exit: bool = False ) -> None: ... def push(self, line: str, filename: str | None = None) -> bool: ... else: - def __init__(self, locals: Mapping[str, Any] | None = None, filename: str = "") -> None: ... + def __init__(self, locals: dict[str, Any] | None = None, filename: str = "") -> None: ... def push(self, line: str) -> bool: ... def interact(self, banner: str | None = None, exitmsg: str | None = None) -> None: ... @@ -40,7 +40,7 @@ if sys.version_info >= (3, 13): def interact( banner: str | None = None, readfunc: Callable[[str], str] | None = None, - local: Mapping[str, Any] | None = None, + local: dict[str, Any] | None = None, exitmsg: str | None = None, local_exit: bool = False, ) -> None: ... @@ -49,7 +49,7 @@ else: def interact( banner: str | None = None, readfunc: Callable[[str], str] | None = None, - local: Mapping[str, Any] | None = None, + local: dict[str, Any] | None = None, exitmsg: str | None = None, ) -> None: ... diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index 0f99b5c3c67e..b9e4f84ec0b6 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -1,12 +1,10 @@ import sys from _collections_abc import dict_items, dict_keys, dict_values from _typeshed import SupportsItems, SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT +from types import GenericAlias from typing import Any, ClassVar, Generic, NoReturn, SupportsIndex, TypeVar, final, overload from typing_extensions import Self -if sys.version_info >= (3, 9): - from types import GenericAlias - if sys.version_info >= (3, 10): from collections.abc import ( Callable, @@ -93,20 +91,19 @@ class UserDict(MutableMapping[_KT, _VT]): @classmethod @overload def fromkeys(cls, iterable: Iterable[_T], value: _S) -> UserDict[_T, _S]: ... - if sys.version_info >= (3, 9): - @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: ... + @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: ... @@ -213,10 +210,8 @@ class UserString(Sequence[UserString]): def lstrip(self, chars: str | None = None) -> Self: ... maketrans = str.maketrans def partition(self, sep: str) -> tuple[str, str, str]: ... - if sys.version_info >= (3, 9): - def removeprefix(self, prefix: str | UserString, /) -> Self: ... - def removesuffix(self, suffix: str | UserString, /) -> Self: ... - + def removeprefix(self, prefix: str | UserString, /) -> Self: ... + def removesuffix(self, suffix: str | UserString, /) -> Self: ... def replace(self, old: str | UserString, new: str | UserString, maxsplit: int = -1) -> Self: ... def rfind(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ... def rindex(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ... @@ -271,8 +266,7 @@ class deque(MutableSequence[_T]): def __gt__(self, value: deque[_T], /) -> bool: ... def __ge__(self, value: deque[_T], /) -> bool: ... def __eq__(self, value: object, /) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class Counter(dict[_T, int], Generic[_T]): @overload @@ -387,15 +381,14 @@ class OrderedDict(dict[_KT, _VT]): @overload def pop(self, key: _KT, default: _T) -> _VT | _T: ... def __eq__(self, value: object, /) -> bool: ... - if sys.version_info >= (3, 9): - @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] + @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] class defaultdict(dict[_KT, _VT]): default_factory: Callable[[], _VT] | None @@ -435,15 +428,14 @@ class defaultdict(dict[_KT, _VT]): def __missing__(self, key: _KT, /) -> _VT: ... def __copy__(self) -> Self: ... def copy(self) -> Self: ... - if sys.version_info >= (3, 9): - @overload - def __or__(self, value: dict[_KT, _VT], /) -> Self: ... - @overload - def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... - @overload - def __ror__(self, value: dict[_KT, _VT], /) -> Self: ... - @overload - def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] + @overload + def __or__(self, value: dict[_KT, _VT], /) -> Self: ... + @overload + def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... + @overload + def __ror__(self, value: dict[_KT, _VT], /) -> Self: ... + @overload + def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] class ChainMap(MutableMapping[_KT, _VT]): maps: list[MutableMapping[_KT, _VT]] @@ -488,17 +480,16 @@ class ChainMap(MutableMapping[_KT, _VT]): @classmethod @overload def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> ChainMap[_T, _S]: ... - if sys.version_info >= (3, 9): - @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: ... - @overload - def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... + @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: ... + @overload + def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... diff --git a/mypy/typeshed/stdlib/colorsys.pyi b/mypy/typeshed/stdlib/colorsys.pyi index 443ee828ebfe..7842f80284ef 100644 --- a/mypy/typeshed/stdlib/colorsys.pyi +++ b/mypy/typeshed/stdlib/colorsys.pyi @@ -7,7 +7,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 +# TODO: undocumented ONE_SIXTH: float ONE_THIRD: float TWO_THIRD: float diff --git a/mypy/typeshed/stdlib/compileall.pyi b/mypy/typeshed/stdlib/compileall.pyi index f35c584cedfb..a599b1b23540 100644 --- a/mypy/typeshed/stdlib/compileall.pyi +++ b/mypy/typeshed/stdlib/compileall.pyi @@ -42,7 +42,7 @@ if sys.version_info >= (3, 10): hardlink_dupes: bool = False, ) -> bool: ... -elif sys.version_info >= (3, 9): +else: def compile_dir( dir: StrPath, maxlevels: int | None = None, @@ -76,30 +76,6 @@ elif sys.version_info >= (3, 9): hardlink_dupes: bool = False, ) -> bool: ... -else: - def compile_dir( - dir: StrPath, - maxlevels: int = 10, - 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, - ) -> 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, - ) -> bool: ... - def compile_path( skip_curdir: bool = ..., maxlevels: int = 0, diff --git a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi index 0c019457902b..7294b69567d6 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi @@ -1,15 +1,12 @@ import sys import threading from _typeshed import Unused -from collections.abc import Callable, Collection, Iterable, Iterator +from collections.abc import Callable, Iterable, Iterator from logging import Logger -from types import TracebackType +from types import GenericAlias, TracebackType from typing import Any, Final, Generic, NamedTuple, Protocol, TypeVar from typing_extensions import ParamSpec, Self -if sys.version_info >= (3, 9): - from types import GenericAlias - FIRST_COMPLETED: Final = "FIRST_COMPLETED" FIRST_EXCEPTION: Final = "FIRST_EXCEPTION" ALL_COMPLETED: Final = "ALL_COMPLETED" @@ -53,23 +50,14 @@ class Future(Generic[_T]): def set_result(self, result: _T) -> None: ... def exception(self, timeout: float | None = None) -> BaseException | None: ... def set_exception(self, exception: BaseException | None) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class Executor: - if sys.version_info >= (3, 9): - def submit(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... - else: - def submit(self, fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... - + def submit(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... def map( self, fn: Callable[..., _T], *iterables: Iterable[Any], timeout: float | None = None, chunksize: int = 1 ) -> Iterator[_T]: ... - if sys.version_info >= (3, 9): - def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None: ... - else: - def shutdown(self, wait: bool = True) -> None: ... - + def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None: ... def __enter__(self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None @@ -91,15 +79,9 @@ class DoneAndNotDoneFutures(NamedTuple, Generic[_T]): done: set[Future[_T]] not_done: set[Future[_T]] -if sys.version_info >= (3, 9): - def wait( - fs: Iterable[Future[_T]], timeout: float | None = None, return_when: str = "ALL_COMPLETED" - ) -> DoneAndNotDoneFutures[_T]: ... - -else: - def wait( - fs: Collection[Future[_T]], timeout: float | None = None, return_when: str = "ALL_COMPLETED" - ) -> DoneAndNotDoneFutures[_T]: ... +def wait( + fs: Iterable[Future[_T]], timeout: float | None = None, return_when: str = "ALL_COMPLETED" +) -> DoneAndNotDoneFutures[_T]: ... class _Waiter: event: threading.Event diff --git a/mypy/typeshed/stdlib/concurrent/futures/process.pyi b/mypy/typeshed/stdlib/concurrent/futures/process.pyi index 97dc261be7ed..9c904f793fa9 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/process.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/process.pyi @@ -84,7 +84,7 @@ class _SafeQueue(Queue[Future[Any]]): pending_work_items: dict[int, _WorkItem[Any]], thread_wakeup: _ThreadWakeup, ) -> None: ... - elif sys.version_info >= (3, 9): + else: def __init__( self, max_size: int | None = 0, @@ -94,10 +94,6 @@ class _SafeQueue(Queue[Future[Any]]): shutdown_lock: Lock, thread_wakeup: _ThreadWakeup, ) -> None: ... - else: - def __init__( - self, max_size: int | None = 0, *, ctx: BaseContext, pending_work_items: dict[int, _WorkItem[Any]] - ) -> None: ... def _on_queue_feeder_error(self, e: Exception, obj: _CallItem) -> None: ... @@ -135,27 +131,26 @@ else: initargs: tuple[Unpack[_Ts]], ) -> None: ... -if sys.version_info >= (3, 9): - class _ExecutorManagerThread(Thread): - thread_wakeup: _ThreadWakeup - shutdown_lock: Lock - executor_reference: ref[Any] - processes: MutableMapping[int, Process] - call_queue: Queue[_CallItem] - result_queue: SimpleQueue[_ResultItem] - work_ids_queue: Queue[int] - pending_work_items: dict[int, _WorkItem[Any]] - def __init__(self, executor: ProcessPoolExecutor) -> None: ... - def run(self) -> None: ... - def add_call_item_to_queue(self) -> None: ... - def wait_result_broken_or_wakeup(self) -> tuple[Any, bool, str]: ... - def process_result_item(self, result_item: int | _ResultItem) -> None: ... - def is_shutting_down(self) -> bool: ... - def terminate_broken(self, cause: str) -> None: ... - def flag_executor_shutting_down(self) -> None: ... - def shutdown_workers(self) -> None: ... - def join_executor_internals(self) -> None: ... - def get_n_children_alive(self) -> int: ... +class _ExecutorManagerThread(Thread): + thread_wakeup: _ThreadWakeup + shutdown_lock: Lock + executor_reference: ref[Any] + processes: MutableMapping[int, Process] + call_queue: Queue[_CallItem] + result_queue: SimpleQueue[_ResultItem] + work_ids_queue: Queue[int] + pending_work_items: dict[int, _WorkItem[Any]] + def __init__(self, executor: ProcessPoolExecutor) -> None: ... + def run(self) -> None: ... + def add_call_item_to_queue(self) -> None: ... + def wait_result_broken_or_wakeup(self) -> tuple[Any, bool, str]: ... + def process_result_item(self, result_item: int | _ResultItem) -> None: ... + def is_shutting_down(self) -> bool: ... + def terminate_broken(self, cause: str) -> None: ... + def flag_executor_shutting_down(self) -> None: ... + def shutdown_workers(self) -> None: ... + def join_executor_internals(self) -> None: ... + def get_n_children_alive(self) -> int: ... _system_limits_checked: bool _system_limited: bool | None @@ -238,7 +233,6 @@ class ProcessPoolExecutor(Executor): initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]], ) -> None: ... - if sys.version_info >= (3, 9): - def _start_executor_manager_thread(self) -> None: ... + def _start_executor_manager_thread(self) -> None: ... def _adjust_process_count(self) -> None: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi index d1b7858eae02..da3e006b6f13 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi @@ -1,7 +1,7 @@ import queue -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, TypeVar, overload from typing_extensions import TypeVarTuple, Unpack from weakref import ref @@ -16,9 +16,6 @@ _global_shutdown_lock: Lock def _python_exit() -> None: ... -if sys.version_info >= (3, 9): - from types import GenericAlias - _S = TypeVar("_S") class _WorkItem(Generic[_S]): @@ -28,8 +25,7 @@ class _WorkItem(Generic[_S]): kwargs: Mapping[str, Any] def __init__(self, future: Future[_S], fn: Callable[..., _S], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ... def run(self) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... def _worker( executor_reference: ref[Any], diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index 08ac5a28b8b8..70d0dbdcb2f1 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -81,14 +81,9 @@ class _GeneratorContextManager( AbstractContextManager[_T_co, bool | None], ContextDecorator, ): - if sys.version_info >= (3, 9): - def __exit__( - self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None - ) -> bool | None: ... - else: - def __exit__( - self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None - ) -> bool | None: ... + def __exit__( + self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ... diff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi index ef93129d6546..4ed0ab1d83b8 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi @@ -26,12 +26,10 @@ else: from _typeshed import SupportsWrite 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 -if sys.version_info >= (3, 12): - from types import GenericAlias - __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", diff --git a/mypy/typeshed/stdlib/ctypes/__init__.pyi b/mypy/typeshed/stdlib/ctypes/__init__.pyi index 4f44975d657f..a7e19483301c 100644 --- a/mypy/typeshed/stdlib/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/ctypes/__init__.pyi @@ -26,7 +26,8 @@ from _ctypes import ( ) from _typeshed import StrPath from ctypes._endian import BigEndianStructure as BigEndianStructure, LittleEndianStructure as LittleEndianStructure -from typing import Any, ClassVar, Generic, TypeVar, type_check_only +from types import GenericAlias +from typing import Any, ClassVar, Generic, Literal, TypeVar, type_check_only from typing_extensions import Self, TypeAlias, deprecated if sys.platform == "win32": @@ -35,10 +36,7 @@ if sys.platform == "win32": if sys.version_info >= (3, 11): from ctypes._endian import BigEndianUnion as BigEndianUnion, LittleEndianUnion as LittleEndianUnion -if sys.version_info >= (3, 9): - from types import GenericAlias - -_T = TypeVar("_T") +_T = TypeVar("_T", default=Any) _DLLT = TypeVar("_DLLT", bound=CDLL) _CT = TypeVar("_CT", bound=_CData) @@ -92,8 +90,7 @@ class LibraryLoader(Generic[_DLLT]): def __getattr__(self, name: str) -> _DLLT: ... def __getitem__(self, name: str) -> _DLLT: ... def LoadLibrary(self, name: str) -> _DLLT: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... cdll: LibraryLoader[CDLL] if sys.platform == "win32": @@ -151,14 +148,12 @@ c_buffer = create_string_buffer def create_unicode_buffer(init: int | str, size: int | None = None) -> Array[c_wchar]: ... @deprecated("Deprecated in Python 3.13; removal scheduled for Python 3.15") -def SetPointerType( - pointer: type[_Pointer[Any]], cls: Any # noqa: F811 # Redefinition of unused `pointer` from line 22 -) -> None: ... +def SetPointerType(pointer: type[_Pointer[Any]], cls: Any) -> None: ... # noqa: F811 def ARRAY(typ: _CT, len: int) -> Array[_CT]: ... # Soft Deprecated, no plans to remove if sys.platform == "win32": def DllCanUnloadNow() -> int: ... - def DllGetClassObject(rclsid: Any, riid: Any, ppv: Any) -> int: ... # TODO not documented + def DllGetClassObject(rclsid: Any, riid: Any, ppv: Any) -> int: ... # TODO: not documented # Actually just an instance of _NamedFuncPointer (aka _CDLLFuncPointer), # but we want to set a more specific __call__ @@ -191,73 +186,121 @@ if sys.platform == "win32": def wstring_at(ptr: _CVoidConstPLike, size: int = -1) -> str: ... -class c_byte(_SimpleCData[int]): ... +class py_object(_CanCastTo, _SimpleCData[_T]): + _type_: ClassVar[Literal["O"]] + +class c_bool(_SimpleCData[bool]): + _type_: ClassVar[Literal["?"]] + def __init__(self, value: bool = ...) -> None: ... + +class c_byte(_SimpleCData[int]): + _type_: ClassVar[Literal["b"]] + +class c_ubyte(_SimpleCData[int]): + _type_: ClassVar[Literal["B"]] + +class c_short(_SimpleCData[int]): + _type_: ClassVar[Literal["h"]] + +class c_ushort(_SimpleCData[int]): + _type_: ClassVar[Literal["H"]] + +class c_long(_SimpleCData[int]): + _type_: ClassVar[Literal["l"]] + +class c_ulong(_SimpleCData[int]): + _type_: ClassVar[Literal["L"]] + +class c_int(_SimpleCData[int]): # can be an alias for c_long + _type_: ClassVar[Literal["i", "l"]] + +class c_uint(_SimpleCData[int]): # can be an alias for c_ulong + _type_: ClassVar[Literal["I", "L"]] + +class c_longlong(_SimpleCData[int]): # can be an alias for c_long + _type_: ClassVar[Literal["q", "l"]] + +class c_ulonglong(_SimpleCData[int]): # can be an alias for c_ulong + _type_: ClassVar[Literal["Q", "L"]] + +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"]] + +class c_uint16(_SimpleCData[int]): # can be an alias for c_ushort or c_uint + _type_: ClassVar[Literal["H", "I"]] + +class c_int32(_SimpleCData[int]): # can be an alias for c_int or c_long + _type_: ClassVar[Literal["i", "l"]] + +class c_uint32(_SimpleCData[int]): # can be an alias for c_uint or c_ulong + _type_: ClassVar[Literal["I", "L"]] + +class c_int64(_SimpleCData[int]): # can be an alias for c_long or c_longlong + _type_: ClassVar[Literal["l", "q"]] + +class c_uint64(_SimpleCData[int]): # can be an alias for c_ulong or c_ulonglong + _type_: ClassVar[Literal["L", "Q"]] + +class c_ssize_t(_SimpleCData[int]): # alias for c_int, c_long, or c_longlong + _type_: ClassVar[Literal["i", "l", "q"]] + +class c_size_t(_SimpleCData[int]): # alias for c_uint, c_ulong, or c_ulonglong + _type_: ClassVar[Literal["I", "L", "Q"]] + +class c_float(_SimpleCData[float]): + _type_: ClassVar[Literal["f"]] + +class c_double(_SimpleCData[float]): + _type_: ClassVar[Literal["d"]] + +class c_longdouble(_SimpleCData[float]): # can be an alias for c_double + _type_: ClassVar[Literal["d", "g"]] + +if sys.version_info >= (3, 14): + class c_float_complex(_SimpleCData[complex]): + _type_: ClassVar[Literal["E"]] + + class c_double_complex(_SimpleCData[complex]): + _type_: ClassVar[Literal["C"]] + + class c_longdouble_complex(_SimpleCData[complex]): + _type_: ClassVar[Literal["F"]] class c_char(_SimpleCData[bytes]): + _type_: ClassVar[Literal["c"]] def __init__(self, value: int | bytes | bytearray = ...) -> None: ... class c_char_p(_PointerLike, _SimpleCData[bytes | None]): + _type_: ClassVar[Literal["z"]] def __init__(self, value: int | bytes | None = ...) -> None: ... @classmethod def from_param(cls, value: Any, /) -> Self | _CArgObject: ... -class c_double(_SimpleCData[float]): ... -class c_longdouble(_SimpleCData[float]): ... # can be an alias for c_double -class c_float(_SimpleCData[float]): ... -class c_int(_SimpleCData[int]): ... # can be an alias for c_long -class c_long(_SimpleCData[int]): ... -class c_longlong(_SimpleCData[int]): ... # can be an alias for c_long -class c_short(_SimpleCData[int]): ... -class c_size_t(_SimpleCData[int]): ... # alias for c_uint, c_ulong, or c_ulonglong -class c_ssize_t(_SimpleCData[int]): ... # alias for c_int, c_long, or c_longlong -class c_ubyte(_SimpleCData[int]): ... -class c_uint(_SimpleCData[int]): ... # can be an alias for c_ulong -class c_ulong(_SimpleCData[int]): ... -class c_ulonglong(_SimpleCData[int]): ... # can be an alias for c_ulong -class c_ushort(_SimpleCData[int]): ... - class c_void_p(_PointerLike, _SimpleCData[int | None]): + _type_: ClassVar[Literal["P"]] @classmethod def from_param(cls, value: Any, /) -> Self | _CArgObject: ... c_voidp = c_void_p # backwards compatibility (to a bug) -class c_wchar(_SimpleCData[str]): ... - -c_int8 = c_byte - -# these are actually dynamic aliases for c_short, c_int, c_long, or c_longlong -class c_int16(_SimpleCData[int]): ... -class c_int32(_SimpleCData[int]): ... -class c_int64(_SimpleCData[int]): ... - -c_uint8 = c_ubyte - -# these are actually dynamic aliases for c_ushort, c_uint, c_ulong, or c_ulonglong -class c_uint16(_SimpleCData[int]): ... -class c_uint32(_SimpleCData[int]): ... -class c_uint64(_SimpleCData[int]): ... +class c_wchar(_SimpleCData[str]): + _type_: ClassVar[Literal["u"]] class c_wchar_p(_PointerLike, _SimpleCData[str | None]): + _type_: ClassVar[Literal["Z"]] def __init__(self, value: int | str | None = ...) -> None: ... @classmethod def from_param(cls, value: Any, /) -> Self | _CArgObject: ... -class c_bool(_SimpleCData[bool]): - def __init__(self, value: bool = ...) -> None: ... - if sys.platform == "win32": - class HRESULT(_SimpleCData[int]): ... # TODO undocumented + class HRESULT(_SimpleCData[int]): # TODO: undocumented + _type_: ClassVar[Literal["l"]] if sys.version_info >= (3, 12): # At runtime, this is an alias for either c_int32 or c_int64, - # which are themselves an alias for one of c_short, c_int, c_long, or c_longlong + # which are themselves an alias for one of c_int, c_long, or c_longlong # This covers all our bases. - c_time_t: type[c_int32 | c_int64 | c_short | c_int | c_long | c_longlong] - -class py_object(_CanCastTo, _SimpleCData[_T]): ... - -if sys.version_info >= (3, 14): - class c_float_complex(_SimpleCData[complex]): ... - class c_double_complex(_SimpleCData[complex]): ... - class c_longdouble_complex(_SimpleCData[complex]): ... + c_time_t: type[c_int32 | c_int64 | c_int | c_long | c_longlong] diff --git a/mypy/typeshed/stdlib/ctypes/wintypes.pyi b/mypy/typeshed/stdlib/ctypes/wintypes.pyi index e938d8f22957..63f117787aa0 100644 --- a/mypy/typeshed/stdlib/ctypes/wintypes.pyi +++ b/mypy/typeshed/stdlib/ctypes/wintypes.pyi @@ -1,10 +1,10 @@ +import sys from _ctypes import _CArgObject, _CField from ctypes import ( Array, Structure, _Pointer, _SimpleCData, - c_byte, c_char, c_char_p, c_double, @@ -24,7 +24,15 @@ from ctypes import ( from typing import Any, TypeVar from typing_extensions import Self, TypeAlias -BYTE = c_byte +if sys.version_info >= (3, 12): + from ctypes import c_ubyte + + BYTE = c_ubyte +else: + from ctypes import c_byte + + BYTE = c_byte + WORD = c_ushort DWORD = c_ulong CHAR = c_char diff --git a/mypy/typeshed/stdlib/curses/__init__.pyi b/mypy/typeshed/stdlib/curses/__init__.pyi index edc64a00cd39..5c157fd7c2f6 100644 --- a/mypy/typeshed/stdlib/curses/__init__.pyi +++ b/mypy/typeshed/stdlib/curses/__init__.pyi @@ -23,11 +23,6 @@ COLOR_PAIRS: int def wrapper(func: Callable[Concatenate[window, _P], _T], /, *arg: _P.args, **kwds: _P.kwargs) -> _T: ... -# typeshed used the name _CursesWindow for the underlying C class before -# it was mapped to the name 'window' in 3.8. -# Kept here as a legacy alias in case any third-party code is relying on it. -_CursesWindow = window - # At runtime this class is unexposed and calls itself curses.ncurses_version. # That name would conflict with the actual curses.ncurses_version, which is # an instance of this class. diff --git a/mypy/typeshed/stdlib/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index 3d89b830352b..e08b1919d8e5 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -4,11 +4,9 @@ import types from _typeshed import DataclassInstance from builtins import type as Type # alias to avoid name clashes with fields named "type" from collections.abc import Callable, Iterable, Mapping +from types import GenericAlias from typing import Any, Generic, Literal, Protocol, TypeVar, overload -from typing_extensions import Never, TypeAlias, TypeIs - -if sys.version_info >= (3, 9): - from types import GenericAlias +from typing_extensions import Never, TypeIs _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) @@ -142,8 +140,7 @@ class Field(Generic[_T]): ) -> None: ... def __set_name__(self, owner: Type[Any], name: str) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... # NOTE: Actual return type is 'Field[_T]', but we want to help type checkers # to understand the magic that happens at runtime. @@ -232,22 +229,13 @@ def is_dataclass(obj: object) -> TypeIs[DataclassInstance | type[DataclassInstan class FrozenInstanceError(AttributeError): ... -if sys.version_info >= (3, 9): - _InitVarMeta: TypeAlias = type -else: - class _InitVarMeta(type): - # Not used, instead `InitVar.__class_getitem__` is called. - # pyright (not unreasonably) thinks this is an invalid use of InitVar. - def __getitem__(self, params: Any) -> InitVar[Any]: ... # pyright: ignore[reportInvalidTypeForm] - -class InitVar(Generic[_T], metaclass=_InitVarMeta): +class InitVar(Generic[_T], metaclass=type): type: Type[_T] def __init__(self, type: Type[_T]) -> None: ... - if sys.version_info >= (3, 9): - @overload - def __class_getitem__(cls, type: Type[_T]) -> InitVar[_T]: ... # pyright: ignore[reportInvalidTypeForm] - @overload - def __class_getitem__(cls, type: Any) -> InitVar[Any]: ... # pyright: ignore[reportInvalidTypeForm] + @overload + def __class_getitem__(cls, type: Type[_T]) -> InitVar[_T]: ... # pyright: ignore[reportInvalidTypeForm] + @overload + def __class_getitem__(cls, type: Any) -> InitVar[Any]: ... # pyright: ignore[reportInvalidTypeForm] if sys.version_info >= (3, 12): def make_dataclass( diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index 4907bf4607c8..72fb5fceb1fb 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -6,7 +6,7 @@ from typing_extensions import CapsuleType, Self, TypeAlias, deprecated if sys.version_info >= (3, 11): __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR", "UTC") -elif sys.version_info >= (3, 9): +else: __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR") MINYEAR: Final = 1 @@ -39,18 +39,17 @@ class timezone(tzinfo): if sys.version_info >= (3, 11): UTC: timezone -if sys.version_info >= (3, 9): - # This class calls itself datetime.IsoCalendarDate. It's neither - # NamedTuple nor structseq. - @final - @type_check_only - class _IsoCalendarDate(tuple[int, int, int]): - @property - def year(self) -> int: ... - @property - def week(self) -> int: ... - @property - def weekday(self) -> int: ... +# This class calls itself datetime.IsoCalendarDate. It's neither +# NamedTuple nor structseq. +@final +@type_check_only +class _IsoCalendarDate(tuple[int, int, int]): + @property + def year(self) -> int: ... + @property + def week(self) -> int: ... + @property + def weekday(self) -> int: ... class date: min: ClassVar[date] @@ -106,10 +105,7 @@ class date: def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... - if sys.version_info >= (3, 9): - def isocalendar(self) -> _IsoCalendarDate: ... - else: - def isocalendar(self) -> tuple[int, int, int]: ... + def isocalendar(self) -> _IsoCalendarDate: ... class time: min: ClassVar[time] diff --git a/mypy/typeshed/stdlib/difflib.pyi b/mypy/typeshed/stdlib/difflib.pyi index 50154d785c2f..18583a3acfe9 100644 --- a/mypy/typeshed/stdlib/difflib.pyi +++ b/mypy/typeshed/stdlib/difflib.pyi @@ -1,10 +1,7 @@ -import sys from collections.abc import Callable, Iterable, Iterator, Sequence +from types import GenericAlias from typing import Any, AnyStr, Generic, Literal, NamedTuple, TypeVar, overload -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = [ "get_close_matches", "ndiff", @@ -43,19 +40,14 @@ class SequenceMatcher(Generic[_T]): 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: ... - if sys.version_info >= (3, 9): - def find_longest_match(self, alo: int = 0, ahi: int | None = None, blo: int = 0, bhi: int | None = None) -> Match: ... - else: - def find_longest_match(self, alo: int, ahi: int, blo: int, bhi: int) -> Match: ... - + def find_longest_match(self, alo: int = 0, ahi: int | None = None, blo: int = 0, bhi: int | None = None) -> Match: ... def get_matching_blocks(self) -> list[Match]: ... def get_opcodes(self) -> list[tuple[Literal["replace", "delete", "insert", "equal"], int, int, int, int]]: ... def get_grouped_opcodes(self, n: int = 3) -> Iterable[list[tuple[str, int, int, int, int]]]: ... def ratio(self) -> float: ... def quick_ratio(self) -> float: ... def real_quick_ratio(self) -> float: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @overload def get_close_matches(word: AnyStr, possibilities: Iterable[AnyStr], n: int = 3, cutoff: float = 0.6) -> list[AnyStr]: ... diff --git a/mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi b/mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi index baeee7d3eccb..d677f81d1425 100644 --- a/mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi +++ b/mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi @@ -21,8 +21,7 @@ if sys.platform == "win32": boolean_options: ClassVar[list[str]] all_versions: Incomplete other_version: str - if sys.version_info >= (3, 9): - def __init__(self, *args, **kw) -> None: ... + def __init__(self, *args, **kw) -> None: ... bdist_dir: Incomplete plat_name: Incomplete keep_temp: int diff --git a/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi index e66d8cc9f2c5..f3fa2a1255a6 100644 --- a/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi +++ b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi @@ -13,7 +13,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 + # TODO: kinda wrong, `getopt(object=object())` is invalid @overload def getopt( self, args: _SliceableT[_StrSequenceT_co] | None = None, object: None = None diff --git a/mypy/typeshed/stdlib/dummy_threading.pyi b/mypy/typeshed/stdlib/dummy_threading.pyi deleted file mode 100644 index 757cb8d4bd4c..000000000000 --- a/mypy/typeshed/stdlib/dummy_threading.pyi +++ /dev/null @@ -1,2 +0,0 @@ -from _dummy_threading import * -from _dummy_threading import __all__ as __all__ diff --git a/mypy/typeshed/stdlib/email/_header_value_parser.pyi b/mypy/typeshed/stdlib/email/_header_value_parser.pyi index a4c2d8b1a92e..a8abfead9217 100644 --- a/mypy/typeshed/stdlib/email/_header_value_parser.pyi +++ b/mypy/typeshed/stdlib/email/_header_value_parser.pyi @@ -17,12 +17,13 @@ TOKEN_ENDS: Final[set[str]] ASPECIALS: Final[set[str]] ATTRIBUTE_ENDS: Final[set[str]] EXTENDED_ATTRIBUTE_ENDS: Final[set[str]] -# Added in Python 3.8.20, 3.9.20, 3.10.15, 3.11.10, 3.12.5 +# Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 NLSET: Final[set[str]] -# Added in Python 3.8.20, 3.9.20, 3.10.15, 3.11.10, 3.12.5 +# Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 SPECIALSNL: Final[set[str]] -if sys.version_info >= (3, 12): +if sys.version_info >= (3, 10): + # Added in Python 3.10.17, 3.11.12, 3.12.9, 3.13.2 (may still be backported to 3.9) def make_quoted_pairs(value: Any) -> str: ... def quote_string(value: Any) -> str: ... @@ -349,7 +350,7 @@ ListSeparator: Final[ValueTerminal] RouteComponentMarker: Final[ValueTerminal] def get_fws(value: str) -> tuple[WhiteSpaceTerminal, str]: ... -def get_encoded_word(value: str) -> tuple[EncodedWord, str]: ... +def get_encoded_word(value: str, terminal_type: str = "vtext") -> tuple[EncodedWord, str]: ... def get_unstructured(value: str) -> UnstructuredTokenList: ... def get_qp_ctext(value: str) -> tuple[WhiteSpaceTerminal, str]: ... def get_qcontent(value: str) -> tuple[ValueTerminal, str]: ... diff --git a/mypy/typeshed/stdlib/email/_policybase.pyi b/mypy/typeshed/stdlib/email/_policybase.pyi index f5dbbd96da14..5266609e597f 100644 --- a/mypy/typeshed/stdlib/email/_policybase.pyi +++ b/mypy/typeshed/stdlib/email/_policybase.pyi @@ -23,7 +23,7 @@ class _PolicyBase(Generic[_MessageT]): raise_on_defect: bool mangle_from_: bool message_factory: _MessageFactory[_MessageT] | None - # Added in Python 3.8.20, 3.9.20, 3.10.15, 3.11.10, 3.12.5 + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 verify_generated_headers: bool def __init__( @@ -35,7 +35,7 @@ class _PolicyBase(Generic[_MessageT]): raise_on_defect: bool = False, mangle_from_: bool = ..., # default depends on sub-class message_factory: _MessageFactory[_MessageT] | None = None, - # Added in Python 3.8.20, 3.9.20, 3.10.15, 3.11.10, 3.12.5 + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 verify_generated_headers: bool = True, ) -> None: ... def clone( @@ -47,7 +47,7 @@ class _PolicyBase(Generic[_MessageT]): raise_on_defect: bool = ..., mangle_from_: bool = ..., message_factory: _MessageFactory[_MessageT] | None = ..., - # Added in Python 3.8.20, 3.9.20, 3.10.15, 3.11.10, 3.12.5 + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 verify_generated_headers: bool = ..., ) -> Self: ... def __add__(self, other: Policy) -> Self: ... diff --git a/mypy/typeshed/stdlib/email/errors.pyi b/mypy/typeshed/stdlib/email/errors.pyi index f105576c5ee4..b501a5866556 100644 --- a/mypy/typeshed/stdlib/email/errors.pyi +++ b/mypy/typeshed/stdlib/email/errors.pyi @@ -7,7 +7,7 @@ class BoundaryError(MessageParseError): ... class MultipartConversionError(MessageError, TypeError): ... class CharsetError(MessageError): ... -# Added in Python 3.8.20, 3.9.20, 3.10.15, 3.11.10, 3.12.5 +# Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 class HeaderWriteError(MessageError): ... class MessageDefect(ValueError): diff --git a/mypy/typeshed/stdlib/email/policy.pyi b/mypy/typeshed/stdlib/email/policy.pyi index 5b145bcf2318..5005483edf86 100644 --- a/mypy/typeshed/stdlib/email/policy.pyi +++ b/mypy/typeshed/stdlib/email/policy.pyi @@ -24,7 +24,7 @@ class EmailPolicy(Policy[_MessageT]): raise_on_defect: bool = ..., mangle_from_: bool = ..., message_factory: None = None, - # Added in Python 3.8.20, 3.9.20, 3.10.15, 3.11.10, 3.12.5 + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 verify_generated_headers: bool = ..., utf8: bool = ..., refold_source: str = ..., @@ -41,7 +41,7 @@ class EmailPolicy(Policy[_MessageT]): raise_on_defect: bool = ..., mangle_from_: bool = ..., message_factory: _MessageFactory[_MessageT] | None = ..., - # Added in Python 3.8.20, 3.9.20, 3.10.15, 3.11.10, 3.12.5 + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 verify_generated_headers: bool = ..., utf8: bool = ..., refold_source: str = ..., @@ -62,7 +62,7 @@ class EmailPolicy(Policy[_MessageT]): raise_on_defect: bool = ..., mangle_from_: bool = ..., message_factory: _MessageFactory[_MessageT] | None = ..., - # Added in Python 3.8.20, 3.9.20, 3.10.15, 3.11.10, 3.12.5 + # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 verify_generated_headers: bool = ..., utf8: bool = ..., refold_source: str = ..., diff --git a/mypy/typeshed/stdlib/email/utils.pyi b/mypy/typeshed/stdlib/email/utils.pyi index dc3eecb5ef7f..efc32a7abce2 100644 --- a/mypy/typeshed/stdlib/email/utils.pyi +++ b/mypy/typeshed/stdlib/email/utils.pyi @@ -30,11 +30,11 @@ _PDTZ: TypeAlias = tuple[int, int, int, int, int, int, int, int, int, int | None def quote(str: str) -> str: ... def unquote(str: str) -> str: ... -# `strict` parameter added in Python 3.8.20, 3.9.20, 3.10.15, 3.11.10, 3.12.5 +# `strict` parameter added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5 def parseaddr(addr: str | list[str], *, strict: bool = True) -> tuple[str, str]: ... def formataddr(pair: tuple[str | None, str], charset: str | Charset = "utf-8") -> str: ... -# `strict` parameter added in Python 3.8.20, 3.9.20, 3.10.15, 3.11.10, 3.12.5 +# `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: ... diff --git a/mypy/typeshed/stdlib/encodings/mac_centeuro.pyi b/mypy/typeshed/stdlib/encodings/mac_centeuro.pyi deleted file mode 100644 index f62195662ce9..000000000000 --- a/mypy/typeshed/stdlib/encodings/mac_centeuro.pyi +++ /dev/null @@ -1,21 +0,0 @@ -import codecs -from _codecs import _EncodingMap -from _typeshed import ReadableBuffer - -class Codec(codecs.Codec): - def encode(self, input: str, errors: str = "strict") -> tuple[bytes, int]: ... - def decode(self, input: bytes, errors: str = "strict") -> tuple[str, int]: ... - -class IncrementalEncoder(codecs.IncrementalEncoder): - def encode(self, input: str, final: bool = False) -> bytes: ... - -class IncrementalDecoder(codecs.IncrementalDecoder): - def decode(self, input: ReadableBuffer, final: bool = False) -> str: ... - -class StreamWriter(Codec, codecs.StreamWriter): ... -class StreamReader(Codec, codecs.StreamReader): ... - -def getregentry() -> codecs.CodecInfo: ... - -decoding_table: str -encoding_table: _EncodingMap diff --git a/mypy/typeshed/stdlib/encodings/raw_unicode_escape.pyi b/mypy/typeshed/stdlib/encodings/raw_unicode_escape.pyi index 74abb4623fab..2887739468f2 100644 --- a/mypy/typeshed/stdlib/encodings/raw_unicode_escape.pyi +++ b/mypy/typeshed/stdlib/encodings/raw_unicode_escape.pyi @@ -1,5 +1,4 @@ import codecs -import sys from _typeshed import ReadableBuffer class Codec(codecs.Codec): @@ -7,28 +6,18 @@ class Codec(codecs.Codec): @staticmethod def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... # At runtime, this is codecs.raw_unicode_escape_decode - if sys.version_info >= (3, 9): - @staticmethod - def decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ... - else: - @staticmethod - def decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... + @staticmethod + def decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ... class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input: str, final: bool = False) -> bytes: ... -if sys.version_info >= (3, 9): - class IncrementalDecoder(codecs.BufferedIncrementalDecoder): - def _buffer_decode(self, input: str | ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ... - -else: - class IncrementalDecoder(codecs.IncrementalDecoder): - def decode(self, input: str | ReadableBuffer, final: bool = False) -> str: ... +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: str | ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ... class StreamWriter(Codec, codecs.StreamWriter): ... class StreamReader(Codec, codecs.StreamReader): - if sys.version_info >= (3, 9): - def decode(self, input: str | ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... # type: ignore[override] + def decode(self, input: str | ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... # type: ignore[override] def getregentry() -> codecs.CodecInfo: ... diff --git a/mypy/typeshed/stdlib/encodings/unicode_escape.pyi b/mypy/typeshed/stdlib/encodings/unicode_escape.pyi index 1e942f57916e..ceaa39a3859a 100644 --- a/mypy/typeshed/stdlib/encodings/unicode_escape.pyi +++ b/mypy/typeshed/stdlib/encodings/unicode_escape.pyi @@ -1,5 +1,4 @@ import codecs -import sys from _typeshed import ReadableBuffer class Codec(codecs.Codec): @@ -7,28 +6,18 @@ class Codec(codecs.Codec): @staticmethod def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ... # At runtime, this is codecs.unicode_escape_decode - if sys.version_info >= (3, 9): - @staticmethod - def decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ... - else: - @staticmethod - def decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ... + @staticmethod + def decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ... class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input: str, final: bool = False) -> bytes: ... -if sys.version_info >= (3, 9): - class IncrementalDecoder(codecs.BufferedIncrementalDecoder): - def _buffer_decode(self, input: str | ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ... - -else: - class IncrementalDecoder(codecs.IncrementalDecoder): - def decode(self, input: str | ReadableBuffer, final: bool = False) -> str: ... +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def _buffer_decode(self, input: str | ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ... class StreamWriter(Codec, codecs.StreamWriter): ... class StreamReader(Codec, codecs.StreamReader): - if sys.version_info >= (3, 9): - def decode(self, input: str | ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... # type: ignore[override] + def decode(self, input: str | ReadableBuffer, errors: str = "strict") -> tuple[str, int]: ... # type: ignore[override] def getregentry() -> codecs.CodecInfo: ... diff --git a/mypy/typeshed/stdlib/enum.pyi b/mypy/typeshed/stdlib/enum.pyi index 4a6287a712af..8c88b26a3a2f 100644 --- a/mypy/typeshed/stdlib/enum.pyi +++ b/mypy/typeshed/stdlib/enum.pyi @@ -100,20 +100,13 @@ class EnumMeta(type): _simple: bool = False, **kwds: Any, ) -> _typeshed.Self: ... - elif sys.version_info >= (3, 9): + else: def __new__( metacls: type[_typeshed.Self], cls: str, bases: tuple[type, ...], classdict: _EnumDict, **kwds: Any ) -> _typeshed.Self: ... - else: - def __new__(metacls: type[_typeshed.Self], cls: str, bases: tuple[type, ...], classdict: _EnumDict) -> _typeshed.Self: ... - - if sys.version_info >= (3, 9): - @classmethod - def __prepare__(metacls, cls: str, bases: tuple[type, ...], **kwds: Any) -> _EnumDict: ... # type: ignore[override] - else: - @classmethod - def __prepare__(metacls, cls: str, bases: tuple[type, ...]) -> _EnumDict: ... # type: ignore[override] + @classmethod + def __prepare__(metacls, cls: str, bases: tuple[type, ...], **kwds: Any) -> _EnumDict: ... # type: ignore[override] def __iter__(self: type[_EnumMemberT]) -> Iterator[_EnumMemberT]: ... def __reversed__(self: type[_EnumMemberT]) -> Iterator[_EnumMemberT]: ... if sys.version_info >= (3, 12): diff --git a/mypy/typeshed/stdlib/fcntl.pyi b/mypy/typeshed/stdlib/fcntl.pyi index 71078b3b4579..2fe64eb53201 100644 --- a/mypy/typeshed/stdlib/fcntl.pyi +++ b/mypy/typeshed/stdlib/fcntl.pyi @@ -26,8 +26,7 @@ if sys.platform != "win32": if sys.platform == "darwin": F_FULLFSYNC: int F_NOCACHE: int - if sys.version_info >= (3, 9): - F_GETPATH: int + F_GETPATH: int if sys.platform == "linux": F_SETLKW64: int F_SETSIG: int @@ -43,10 +42,9 @@ if sys.platform != "win32": F_SEAL_SEAL: int F_SEAL_SHRINK: int F_SEAL_WRITE: int - if sys.version_info >= (3, 9): - F_OFD_GETLK: Final[int] - F_OFD_SETLK: Final[int] - F_OFD_SETLKW: Final[int] + F_OFD_GETLK: Final[int] + F_OFD_SETLK: Final[int] + F_OFD_SETLKW: Final[int] if sys.version_info >= (3, 10): F_GETPIPE_SZ: int diff --git a/mypy/typeshed/stdlib/filecmp.pyi b/mypy/typeshed/stdlib/filecmp.pyi index cb7b94596077..a2a2b235fdad 100644 --- a/mypy/typeshed/stdlib/filecmp.pyi +++ b/mypy/typeshed/stdlib/filecmp.pyi @@ -1,11 +1,9 @@ import sys from _typeshed import GenericPath, StrOrBytesPath from collections.abc import Callable, Iterable, Sequence +from types import GenericAlias from typing import Any, AnyStr, Final, Generic, Literal -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = ["clear_cache", "cmp", "dircmp", "cmpfiles", "DEFAULT_IGNORES"] DEFAULT_IGNORES: list[str] @@ -62,7 +60,6 @@ class dircmp(Generic[AnyStr]): def phase3(self) -> None: ... def phase4(self) -> None: ... def phase4_closure(self) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... def clear_cache() -> None: ... diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index 1e6aa78e2607..1d5f9cf00f36 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -1,13 +1,10 @@ import sys from _typeshed import AnyStr_co, StrOrBytesPath from collections.abc import Callable, Iterable, Iterator -from types import TracebackType +from types import GenericAlias, TracebackType from typing import IO, Any, AnyStr, Literal, Protocol, overload from typing_extensions import Self, TypeAlias -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = [ "input", "close", @@ -199,8 +196,7 @@ class FileInput(Iterator[AnyStr]): def fileno(self) -> int: ... def isfirstline(self) -> bool: ... def isstdin(self) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... if sys.version_info >= (3, 10): def hook_compressed( diff --git a/mypy/typeshed/stdlib/fractions.pyi b/mypy/typeshed/stdlib/fractions.pyi index aaa3a22087fc..4d5c2160e60a 100644 --- a/mypy/typeshed/stdlib/fractions.pyi +++ b/mypy/typeshed/stdlib/fractions.pyi @@ -1,24 +1,13 @@ import sys from collections.abc import Callable from decimal import Decimal -from numbers import Integral, Rational, Real +from numbers import Rational, Real from typing import Any, Literal, Protocol, SupportsIndex, overload from typing_extensions import Self, TypeAlias _ComparableNum: TypeAlias = int | float | Decimal | Real -if sys.version_info >= (3, 9): - __all__ = ["Fraction"] -else: - __all__ = ["Fraction", "gcd"] - @overload - def gcd(a: int, b: int) -> int: ... - @overload - def gcd(a: Integral, b: int) -> Integral: ... - @overload - def gcd(a: int, b: Integral) -> Integral: ... - @overload - def gcd(a: Integral, b: Integral) -> Integral: ... +__all__ = ["Fraction"] class _ConvertibleToIntegerRatio(Protocol): def as_integer_ratio(self) -> tuple[int | Rational, int | Rational]: ... diff --git a/mypy/typeshed/stdlib/ftplib.pyi b/mypy/typeshed/stdlib/ftplib.pyi index 3693d7c52a26..44bc2165fe0e 100644 --- a/mypy/typeshed/stdlib/ftplib.pyi +++ b/mypy/typeshed/stdlib/ftplib.pyi @@ -41,29 +41,17 @@ class FTP: self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None ) -> None: ... source_address: tuple[str, int] | None - if sys.version_info >= (3, 9): - def __init__( - self, - host: str = "", - user: str = "", - passwd: str = "", - acct: str = "", - timeout: float | None = ..., - source_address: tuple[str, int] | None = None, - *, - encoding: str = "utf-8", - ) -> None: ... - else: - def __init__( - self, - host: str = "", - user: str = "", - passwd: str = "", - acct: str = "", - timeout: float | None = ..., - source_address: tuple[str, int] | None = None, - ) -> None: ... - + def __init__( + self, + host: str = "", + user: str = "", + passwd: str = "", + acct: str = "", + timeout: float | None = ..., + source_address: tuple[str, int] | None = None, + *, + encoding: str = "utf-8", + ) -> None: ... def connect( self, host: str = "", port: int = 0, timeout: float = -999, source_address: tuple[str, int] | None = None ) -> str: ... @@ -131,7 +119,7 @@ class FTP_TLS(FTP): source_address: tuple[str, int] | None = None, encoding: str = "utf-8", ) -> None: ... - elif sys.version_info >= (3, 9): + else: def __init__( self, host: str = "", @@ -146,19 +134,6 @@ class FTP_TLS(FTP): *, encoding: str = "utf-8", ) -> None: ... - else: - def __init__( - self, - host: str = "", - user: str = "", - passwd: str = "", - acct: str = "", - keyfile: str | None = None, - certfile: str | None = None, - context: SSLContext | None = None, - timeout: float | None = ..., - source_address: tuple[str, int] | None = None, - ) -> None: ... ssl_version: int keyfile: str | None certfile: str | None diff --git a/mypy/typeshed/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index f786167e322d..d35c295754e5 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -2,12 +2,10 @@ import sys import types from _typeshed import SupportsAllComparisons, SupportsItems from collections.abc import Callable, Hashable, Iterable, Sized +from types import GenericAlias from typing import Any, Generic, Literal, NamedTuple, TypedDict, TypeVar, final, overload from typing_extensions import ParamSpec, Self, TypeAlias -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = [ "update_wrapper", "wraps", @@ -22,11 +20,9 @@ __all__ = [ "singledispatch", "cached_property", "singledispatchmethod", + "cache", ] -if sys.version_info >= (3, 9): - __all__ += ["cache"] - _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) _S = TypeVar("_S") @@ -46,10 +42,9 @@ class _CacheInfo(NamedTuple): maxsize: int | None currsize: int -if sys.version_info >= (3, 9): - class _CacheParameters(TypedDict): - maxsize: int - typed: bool +class _CacheParameters(TypedDict): + maxsize: int + typed: bool @final class _lru_cache_wrapper(Generic[_T]): @@ -57,9 +52,7 @@ class _lru_cache_wrapper(Generic[_T]): def __call__(self, *args: Hashable, **kwargs: Hashable) -> _T: ... def cache_info(self) -> _CacheInfo: ... def cache_clear(self) -> None: ... - if sys.version_info >= (3, 9): - def cache_parameters(self) -> _CacheParameters: ... - + def cache_parameters(self) -> _CacheParameters: ... def __copy__(self) -> _lru_cache_wrapper[_T]: ... def __deepcopy__(self, memo: Any, /) -> _lru_cache_wrapper[_T]: ... @@ -131,8 +124,7 @@ class partial(Generic[_T]): def keywords(self) -> dict[str, Any]: ... def __new__(cls, func: Callable[..., _T], /, *args: Any, **kwargs: Any) -> Self: ... def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... # With protocols, this could change into a generic protocol that defines __get__ and returns _T _Descriptor: TypeAlias = Any @@ -148,8 +140,7 @@ class partialmethod(Generic[_T]): def __get__(self, obj: Any, cls: type[Any] | None = None) -> Callable[..., _T]: ... @property def __isabstractmethod__(self) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... if sys.version_info >= (3, 11): _RegType: TypeAlias = type[Any] | types.UnionType @@ -200,12 +191,9 @@ class cached_property(Generic[_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] - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... - -if sys.version_info >= (3, 9): - def cache(user_function: Callable[..., _T], /) -> _lru_cache_wrapper[_T]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... +def cache(user_function: Callable[..., _T], /) -> _lru_cache_wrapper[_T]: ... def _make_key( args: tuple[Hashable, ...], kwds: SupportsItems[Any, Any], diff --git a/mypy/typeshed/stdlib/gc.pyi b/mypy/typeshed/stdlib/gc.pyi index 9d34e0d6213a..06fb6b47c2d1 100644 --- a/mypy/typeshed/stdlib/gc.pyi +++ b/mypy/typeshed/stdlib/gc.pyi @@ -1,4 +1,3 @@ -import sys from collections.abc import Callable from typing import Any, Final, Literal from typing_extensions import TypeAlias @@ -28,10 +27,7 @@ def get_referrers(*objs: Any) -> list[Any]: ... def get_stats() -> list[dict[str, Any]]: ... def get_threshold() -> tuple[int, int, int]: ... def is_tracked(obj: Any, /) -> bool: ... - -if sys.version_info >= (3, 9): - def is_finalized(obj: Any, /) -> bool: ... - +def is_finalized(obj: Any, /) -> bool: ... def isenabled() -> bool: ... def set_debug(flags: int, /) -> None: ... def set_threshold(threshold0: int, threshold1: int = ..., threshold2: int = ..., /) -> None: ... diff --git a/mypy/typeshed/stdlib/hashlib.pyi b/mypy/typeshed/stdlib/hashlib.pyi index 84666a7fa725..b32c0e992574 100644 --- a/mypy/typeshed/stdlib/hashlib.pyi +++ b/mypy/typeshed/stdlib/hashlib.pyi @@ -5,16 +5,22 @@ from _hashlib import ( _HashObject, openssl_md5 as md5, openssl_sha1 as sha1, + openssl_sha3_224 as sha3_224, + openssl_sha3_256 as sha3_256, + openssl_sha3_384 as sha3_384, + openssl_sha3_512 as sha3_512, openssl_sha224 as sha224, openssl_sha256 as sha256, openssl_sha384 as sha384, openssl_sha512 as sha512, + openssl_shake_128 as shake_128, + openssl_shake_256 as shake_256, pbkdf2_hmac as pbkdf2_hmac, scrypt as scrypt, ) from _typeshed import ReadableBuffer from collections.abc import Callable, Set as AbstractSet -from typing import Protocol, type_check_only +from typing import Protocol if sys.version_info >= (3, 11): __all__ = ( @@ -60,31 +66,7 @@ else: "pbkdf2_hmac", ) -if sys.version_info >= (3, 9): - def new(name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = ...) -> HASH: ... - from _hashlib import ( - openssl_sha3_224 as sha3_224, - openssl_sha3_256 as sha3_256, - openssl_sha3_384 as sha3_384, - openssl_sha3_512 as sha3_512, - openssl_shake_128 as shake_128, - openssl_shake_256 as shake_256, - ) - -else: - @type_check_only - class _VarLenHash(HASH): - def digest(self, length: int) -> bytes: ... # type: ignore[override] - def hexdigest(self, length: int) -> str: ... # type: ignore[override] - - def new(name: str, data: ReadableBuffer = b"") -> HASH: ... - # At runtime these aren't functions but classes imported from _sha3 - def sha3_224(string: ReadableBuffer = b"") -> HASH: ... - def sha3_256(string: ReadableBuffer = b"") -> HASH: ... - def sha3_384(string: ReadableBuffer = b"") -> HASH: ... - def sha3_512(string: ReadableBuffer = b"") -> HASH: ... - def shake_128(string: ReadableBuffer = b"") -> _VarLenHash: ... - def shake_256(string: ReadableBuffer = b"") -> _VarLenHash: ... +def new(name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = ...) -> HASH: ... algorithms_guaranteed: AbstractSet[str] algorithms_available: AbstractSet[str] diff --git a/mypy/typeshed/stdlib/hmac.pyi b/mypy/typeshed/stdlib/hmac.pyi index dfb574c177cd..300ed9eb26d8 100644 --- a/mypy/typeshed/stdlib/hmac.pyi +++ b/mypy/typeshed/stdlib/hmac.pyi @@ -1,9 +1,8 @@ -import sys -from _hashlib import _HashObject +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 AnyStr, overload +from typing import overload from typing_extensions import TypeAlias _DigestMod: TypeAlias = str | Callable[[], _HashObject] | ModuleType @@ -32,11 +31,3 @@ class HMAC: def copy(self) -> HMAC: ... def digest(key: SizedBuffer, msg: ReadableBuffer, digest: _DigestMod) -> bytes: ... - -if sys.version_info >= (3, 9): - from _hashlib import compare_digest as compare_digest -else: - @overload - def compare_digest(a: ReadableBuffer, b: ReadableBuffer, /) -> bool: ... - @overload - def compare_digest(a: AnyStr, b: AnyStr, /) -> bool: ... diff --git a/mypy/typeshed/stdlib/http/__init__.pyi b/mypy/typeshed/stdlib/http/__init__.pyi index ef413a349125..f60c3909736d 100644 --- a/mypy/typeshed/stdlib/http/__init__.pyi +++ b/mypy/typeshed/stdlib/http/__init__.pyi @@ -19,8 +19,7 @@ class HTTPStatus(IntEnum): CONTINUE = 100 SWITCHING_PROTOCOLS = 101 PROCESSING = 102 - if sys.version_info >= (3, 9): - EARLY_HINTS = 103 + EARLY_HINTS = 103 OK = 200 CREATED = 201 @@ -66,16 +65,14 @@ class HTTPStatus(IntEnum): RANGE_NOT_SATISFIABLE = 416 REQUESTED_RANGE_NOT_SATISFIABLE = 416 EXPECTATION_FAILED = 417 - if sys.version_info >= (3, 9): - IM_A_TEAPOT = 418 + IM_A_TEAPOT = 418 MISDIRECTED_REQUEST = 421 if sys.version_info >= (3, 13): UNPROCESSABLE_CONTENT = 422 UNPROCESSABLE_ENTITY = 422 LOCKED = 423 FAILED_DEPENDENCY = 424 - if sys.version_info >= (3, 9): - TOO_EARLY = 425 + TOO_EARLY = 425 UPGRADE_REQUIRED = 426 PRECONDITION_REQUIRED = 428 TOO_MANY_REQUESTS = 429 diff --git a/mypy/typeshed/stdlib/http/client.pyi b/mypy/typeshed/stdlib/http/client.pyi index cd2fc4f5a652..9e0f61598cb8 100644 --- a/mypy/typeshed/stdlib/http/client.pyi +++ b/mypy/typeshed/stdlib/http/client.pyi @@ -44,8 +44,7 @@ HTTPS_PORT: int CONTINUE: Literal[100] SWITCHING_PROTOCOLS: Literal[101] PROCESSING: Literal[102] -if sys.version_info >= (3, 9): - EARLY_HINTS: Literal[103] +EARLY_HINTS: Literal[103] OK: Literal[200] CREATED: Literal[201] @@ -91,16 +90,14 @@ if sys.version_info >= (3, 13): RANGE_NOT_SATISFIABLE: Literal[416] REQUESTED_RANGE_NOT_SATISFIABLE: Literal[416] EXPECTATION_FAILED: Literal[417] -if sys.version_info >= (3, 9): - IM_A_TEAPOT: Literal[418] +IM_A_TEAPOT: Literal[418] MISDIRECTED_REQUEST: Literal[421] if sys.version_info >= (3, 13): UNPROCESSABLE_CONTENT: Literal[422] UNPROCESSABLE_ENTITY: Literal[422] LOCKED: Literal[423] FAILED_DEPENDENCY: Literal[424] -if sys.version_info >= (3, 9): - TOO_EARLY: Literal[425] +TOO_EARLY: Literal[425] UPGRADE_REQUIRED: Literal[426] PRECONDITION_REQUIRED: Literal[428] TOO_MANY_REQUESTS: Literal[429] diff --git a/mypy/typeshed/stdlib/http/cookies.pyi b/mypy/typeshed/stdlib/http/cookies.pyi index c4af5256b5d8..4df12e3125d4 100644 --- a/mypy/typeshed/stdlib/http/cookies.pyi +++ b/mypy/typeshed/stdlib/http/cookies.pyi @@ -1,11 +1,8 @@ -import sys from collections.abc import Iterable, Mapping +from types import GenericAlias from typing import Any, Generic, TypeVar, overload from typing_extensions import TypeAlias -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = ["CookieError", "BaseCookie", "SimpleCookie"] _DataType: TypeAlias = str | Mapping[str, str | Morsel[Any]] @@ -44,8 +41,7 @@ class Morsel(dict[str, Any], Generic[_T]): def OutputString(self, attrs: list[str] | None = None) -> str: ... def __eq__(self, morsel: object) -> bool: ... def __setitem__(self, K: str, V: Any) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class BaseCookie(dict[str, Morsel[_T]], Generic[_T]): def __init__(self, input: _DataType | None = None) -> None: ... diff --git a/mypy/typeshed/stdlib/imaplib.pyi b/mypy/typeshed/stdlib/imaplib.pyi index 6a4d8b2e720a..ccee92bd5e88 100644 --- a/mypy/typeshed/stdlib/imaplib.pyi +++ b/mypy/typeshed/stdlib/imaplib.pyi @@ -40,13 +40,8 @@ class IMAP4: welcome: bytes capabilities: tuple[str, ...] PROTOCOL_VERSION: str - if sys.version_info >= (3, 9): - def __init__(self, host: str = "", port: int = 143, timeout: float | None = None) -> None: ... - def open(self, host: str = "", port: int = 143, timeout: float | None = None) -> None: ... - else: - def __init__(self, host: str = "", port: int = 143) -> None: ... - def open(self, host: str = "", port: int = 143) -> None: ... - + def __init__(self, host: str = "", port: int = 143, timeout: float | None = None) -> None: ... + def open(self, host: str = "", port: int = 143, timeout: float | None = None) -> None: ... def __getattr__(self, attr: str) -> Any: ... host: str port: int @@ -101,9 +96,7 @@ class IMAP4: def thread(self, threading_algorithm: str, charset: str, *search_criteria: str) -> _CommandResults: ... def uid(self, command: str, *args: str) -> _CommandResults: ... def unsubscribe(self, mailbox: str) -> _CommandResults: ... - if sys.version_info >= (3, 9): - def unselect(self) -> _CommandResults: ... - + def unselect(self) -> _CommandResults: ... def xatom(self, name: str, *args: str) -> _CommandResults: ... def print_log(self) -> None: ... @@ -115,16 +108,6 @@ class IMAP4_SSL(IMAP4): def __init__( self, host: str = "", port: int = 993, *, ssl_context: SSLContext | None = None, timeout: float | None = None ) -> None: ... - elif sys.version_info >= (3, 9): - def __init__( - self, - host: str = "", - port: int = 993, - keyfile: str | None = None, - certfile: str | None = None, - ssl_context: SSLContext | None = None, - timeout: float | None = None, - ) -> None: ... else: def __init__( self, @@ -133,14 +116,11 @@ class IMAP4_SSL(IMAP4): keyfile: str | None = None, certfile: str | None = None, ssl_context: SSLContext | None = None, + timeout: float | None = None, ) -> None: ... sslobj: SSLSocket file: IO[Any] - if sys.version_info >= (3, 9): - def open(self, host: str = "", port: int | None = 993, timeout: float | None = None) -> None: ... - else: - def open(self, host: str = "", port: int | None = 993) -> None: ... - + def open(self, host: str = "", port: int | None = 993, timeout: float | None = None) -> None: ... def ssl(self) -> SSLSocket: ... class IMAP4_stream(IMAP4): @@ -150,10 +130,7 @@ class IMAP4_stream(IMAP4): process: subprocess.Popen[bytes] writefile: IO[Any] readfile: IO[Any] - if sys.version_info >= (3, 9): - def open(self, host: str | None = None, port: int | None = None, timeout: float | None = None) -> None: ... - else: - def open(self, host: str | None = None, port: int | None = None) -> None: ... + def open(self, host: str | None = None, port: int | None = None, timeout: float | None = None) -> None: ... class _Authenticator: mech: Callable[[bytes], bytes | bytearray | memoryview | str | None] diff --git a/mypy/typeshed/stdlib/importlib/abc.pyi b/mypy/typeshed/stdlib/importlib/abc.pyi index 588377d7d871..8a106b3a64d7 100644 --- a/mypy/typeshed/stdlib/importlib/abc.pyi +++ b/mypy/typeshed/stdlib/importlib/abc.pyi @@ -125,49 +125,48 @@ class ResourceReader(metaclass=ABCMeta): @abstractmethod def contents(self) -> Iterator[str]: ... -if sys.version_info >= (3, 9): - @runtime_checkable - class Traversable(Protocol): - @abstractmethod - def is_dir(self) -> bool: ... - @abstractmethod - def is_file(self) -> bool: ... - @abstractmethod - def iterdir(self) -> Iterator[Traversable]: ... - if sys.version_info >= (3, 11): - @abstractmethod - def joinpath(self, *descendants: str) -> Traversable: ... - else: - @abstractmethod - def joinpath(self, child: str, /) -> Traversable: ... - - # The documentation and runtime protocol allows *args, **kwargs arguments, - # but this would mean that all implementers would have to support them, - # which is not the case. - @overload - @abstractmethod - def open(self, mode: Literal["r"] = "r", *, encoding: str | None = None, errors: str | None = None) -> IO[str]: ... - @overload +@runtime_checkable +class Traversable(Protocol): + @abstractmethod + def is_dir(self) -> bool: ... + @abstractmethod + def is_file(self) -> bool: ... + @abstractmethod + def iterdir(self) -> Iterator[Traversable]: ... + if sys.version_info >= (3, 11): @abstractmethod - def open(self, mode: Literal["rb"]) -> IO[bytes]: ... - @property + def joinpath(self, *descendants: str) -> Traversable: ... + else: @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 joinpath(self, child: str, /) -> Traversable: ... + # The documentation and runtime protocol allows *args, **kwargs arguments, + # but this would mean that all implementers would have to support them, + # which is not the case. + @overload + @abstractmethod + def open(self, mode: Literal["r"] = "r", *, encoding: str | None = None, errors: str | None = None) -> IO[str]: ... + @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 read_bytes(self) -> bytes: ... - @abstractmethod - def read_text(self, encoding: str | None = None) -> str: ... + def __truediv__(self, child: str, /) -> Traversable: ... - class TraversableResources(ResourceReader): - @abstractmethod - def files(self) -> Traversable: ... - def open_resource(self, resource: str) -> BufferedReader: ... - def resource_path(self, resource: Any) -> str: ... - def is_resource(self, path: str) -> bool: ... - def contents(self) -> Iterator[str]: ... + @abstractmethod + def read_bytes(self) -> bytes: ... + @abstractmethod + def read_text(self, encoding: str | None = None) -> str: ... + +class TraversableResources(ResourceReader): + @abstractmethod + def files(self) -> Traversable: ... + def open_resource(self, resource: str) -> BufferedReader: ... + def resource_path(self, resource: Any) -> str: ... + def is_resource(self, path: str) -> bool: ... + def contents(self) -> Iterator[str]: ... diff --git a/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi index 8ab7a0c4a9e8..15d8b50b09d2 100644 --- a/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi @@ -71,11 +71,10 @@ class EntryPoint(_EntryPointBase): def load(self) -> Any: ... # Callable[[], Any] or an importable module @property def extras(self) -> list[str]: ... - if sys.version_info >= (3, 9): - @property - def module(self) -> str: ... - @property - def attr(self) -> str: ... + @property + def module(self) -> str: ... + @property + def attr(self) -> str: ... if sys.version_info >= (3, 10): dist: ClassVar[Distribution | None] def matches( diff --git a/mypy/typeshed/stdlib/importlib/resources/__init__.pyi b/mypy/typeshed/stdlib/importlib/resources/__init__.pyi index a30e6cdce5c6..2cf6366b6cb3 100644 --- a/mypy/typeshed/stdlib/importlib/resources/__init__.pyi +++ b/mypy/typeshed/stdlib/importlib/resources/__init__.pyi @@ -2,6 +2,7 @@ import os import sys from collections.abc import Iterator from contextlib import AbstractContextManager +from importlib.abc import Traversable from pathlib import Path from types import ModuleType from typing import Any, BinaryIO, Literal, TextIO @@ -12,13 +13,18 @@ if sys.version_info >= (3, 11): else: Package: TypeAlias = str | ModuleType -if sys.version_info >= (3, 9): - from importlib.abc import Traversable - -__all__ = ["Package", "contents", "is_resource", "open_binary", "open_text", "path", "read_binary", "read_text"] - -if sys.version_info >= (3, 9): - __all__ += ["as_file", "files"] +__all__ = [ + "Package", + "as_file", + "contents", + "files", + "is_resource", + "open_binary", + "open_text", + "path", + "read_binary", + "read_text", +] if sys.version_info >= (3, 10): __all__ += ["ResourceReader"] @@ -31,11 +37,12 @@ if sys.version_info < (3, 11): elif sys.version_info < (3, 13): Resource: TypeAlias = str -if sys.version_info >= (3, 13): +if sys.version_info >= (3, 12): from importlib.resources._common import Anchor as Anchor __all__ += ["Anchor"] +if sys.version_info >= (3, 13): from importlib.resources._functional import ( contents as contents, is_resource as is_resource, @@ -57,13 +64,12 @@ else: if sys.version_info >= (3, 11): from importlib.resources._common import as_file as as_file -elif sys.version_info >= (3, 9): +else: def as_file(path: Traversable) -> AbstractContextManager[Path, Literal[False]]: ... if sys.version_info >= (3, 11): from importlib.resources._common import files as files - -elif sys.version_info >= (3, 9): +else: def files(package: Package) -> Traversable: ... if sys.version_info >= (3, 10): diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index 5bebe9bf4482..c525418c104b 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -616,8 +616,7 @@ class Attribute(NamedTuple): def classify_class_attrs(cls: type) -> list[Attribute]: ... -if sys.version_info >= (3, 9): - class ClassFoundException(Exception): ... +class ClassFoundException(Exception): ... if sys.version_info >= (3, 12): class BufferFlags(enum.IntFlag): diff --git a/mypy/typeshed/stdlib/ipaddress.pyi b/mypy/typeshed/stdlib/ipaddress.pyi index e8e81abc6f79..6883895fd219 100644 --- a/mypy/typeshed/stdlib/ipaddress.pyi +++ b/mypy/typeshed/stdlib/ipaddress.pyi @@ -36,9 +36,7 @@ class _BaseAddress(_IPAddressBase): def __hash__(self) -> int: ... def __int__(self) -> int: ... def __sub__(self, other: int) -> Self: ... - if sys.version_info >= (3, 9): - def __format__(self, fmt: str) -> str: ... - + def __format__(self, fmt: str) -> str: ... def __eq__(self, other: object) -> bool: ... def __lt__(self, other: Self) -> bool: ... if sys.version_info >= (3, 11): @@ -184,10 +182,8 @@ class IPv6Address(_BaseV6, _BaseAddress): def sixtofour(self) -> IPv4Address | None: ... @property def teredo(self) -> tuple[IPv4Address, IPv4Address] | None: ... - if sys.version_info >= (3, 9): - @property - def scope_id(self) -> str | None: ... - + @property + def scope_id(self) -> str | None: ... def __hash__(self) -> int: ... def __eq__(self, other: object) -> bool: ... diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index 675533d44a68..7d05b1318680 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -1,12 +1,10 @@ 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 -if sys.version_info >= (3, 9): - from types import GenericAlias - _T = TypeVar("_T") _S = TypeVar("_S") _N = TypeVar("_N", int, float, SupportsFloat, SupportsInt, SupportsIndex, SupportsComplex) @@ -68,8 +66,7 @@ class chain(Iterator[_T]): @classmethod # We use type[Any] and not type[_S] to not lose the type inference from __iterable def from_iterable(cls: type[Any], iterable: Iterable[Iterable[_S]], /) -> chain[_S]: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class compress(Iterator[_T]): def __new__(cls, data: Iterable[_T], selectors: Iterable[Any]) -> Self: ... diff --git a/mypy/typeshed/stdlib/keyword.pyi b/mypy/typeshed/stdlib/keyword.pyi index 960dfd2fa155..6b8bdad6beb6 100644 --- a/mypy/typeshed/stdlib/keyword.pyi +++ b/mypy/typeshed/stdlib/keyword.pyi @@ -1,11 +1,7 @@ -import sys from collections.abc import Sequence from typing import Final -if sys.version_info >= (3, 9): - __all__ = ["iskeyword", "issoftkeyword", "kwlist", "softkwlist"] -else: - __all__ = ["iskeyword", "kwlist"] +__all__ = ["iskeyword", "issoftkeyword", "kwlist", "softkwlist"] def iskeyword(s: str, /) -> bool: ... @@ -13,9 +9,8 @@ def iskeyword(s: str, /) -> bool: ... # type it as a sequence kwlist: Final[Sequence[str]] -if sys.version_info >= (3, 9): - def issoftkeyword(s: str, /) -> bool: ... +def issoftkeyword(s: str, /) -> bool: ... - # a list at runtime, but you're not meant to mutate it; - # type it as a sequence - softkwlist: Final[Sequence[str]] +# a list at runtime, but you're not meant to mutate it; +# type it as a sequence +softkwlist: Final[Sequence[str]] diff --git a/mypy/typeshed/stdlib/linecache.pyi b/mypy/typeshed/stdlib/linecache.pyi index 2e050e13b621..5379a21e7d12 100644 --- a/mypy/typeshed/stdlib/linecache.pyi +++ b/mypy/typeshed/stdlib/linecache.pyi @@ -1,12 +1,8 @@ -import sys from collections.abc import Callable from typing import Any from typing_extensions import TypeAlias -if sys.version_info >= (3, 9): - __all__ = ["getline", "clearcache", "checkcache", "lazycache"] -else: - __all__ = ["getline", "clearcache", "checkcache"] +__all__ = ["getline", "clearcache", "checkcache", "lazycache"] _ModuleGlobals: TypeAlias = dict[str, Any] _ModuleMetadata: TypeAlias = tuple[int, float | None, list[str], str] diff --git a/mypy/typeshed/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index 9a4827a8f626..e555f74a81af 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -6,13 +6,10 @@ from io import TextIOWrapper from re import Pattern from string import Template from time import struct_time -from types import FrameType, TracebackType +from types import FrameType, GenericAlias, TracebackType from typing import Any, ClassVar, Final, Generic, Literal, Protocol, TextIO, TypeVar, overload from typing_extensions import Self, TypeAlias, deprecated -if sys.version_info >= (3, 11): - from types import GenericAlias - __all__ = [ "BASIC_FORMAT", "BufferingFormatter", @@ -273,10 +270,7 @@ class Formatter: datefmt: str | None # undocumented _style: PercentStyle # undocumented default_time_format: str - if sys.version_info >= (3, 9): - default_msec_format: str | None - else: - default_msec_format: str + default_msec_format: str | None if sys.version_info >= (3, 10): def __init__( @@ -577,37 +571,20 @@ if sys.version_info >= (3, 11): def getLevelNamesMapping() -> dict[str, int]: ... def makeLogRecord(dict: Mapping[str, object]) -> LogRecord: ... - -if sys.version_info >= (3, 9): - def basicConfig( - *, - filename: StrPath | None = ..., - filemode: str = ..., - format: str = ..., - datefmt: str | None = ..., - style: _FormatStyle = ..., - level: _Level | None = ..., - stream: SupportsWrite[str] | None = ..., - handlers: Iterable[Handler] | None = ..., - force: bool | None = ..., - encoding: str | None = ..., - errors: str | None = ..., - ) -> None: ... - -else: - def basicConfig( - *, - filename: StrPath | None = ..., - filemode: str = ..., - format: str = ..., - datefmt: str | None = ..., - style: _FormatStyle = ..., - level: _Level | None = ..., - stream: SupportsWrite[str] | None = ..., - handlers: Iterable[Handler] | None = ..., - force: bool = ..., - ) -> None: ... - +def basicConfig( + *, + filename: StrPath | None = ..., + filemode: str = ..., + format: str = ..., + datefmt: str | None = ..., + style: _FormatStyle = ..., + level: _Level | None = ..., + stream: SupportsWrite[str] | None = ..., + handlers: Iterable[Handler] | None = ..., + force: bool | None = ..., + encoding: str | None = ..., + errors: str | None = ..., +) -> None: ... def shutdown(handlerList: Sequence[Any] = ...) -> None: ... # handlerList is undocumented def setLoggerClass(klass: type[Logger]) -> None: ... def captureWarnings(capture: bool) -> None: ... @@ -633,14 +610,10 @@ class FileHandler(StreamHandler[TextIOWrapper]): mode: str # undocumented encoding: str | None # undocumented delay: bool # undocumented - if sys.version_info >= (3, 9): - errors: str | None # undocumented - def __init__( - self, filename: StrPath, mode: str = "a", encoding: str | None = None, delay: bool = False, errors: str | None = None - ) -> None: ... - else: - def __init__(self, filename: StrPath, mode: str = "a", encoding: str | None = None, delay: bool = False) -> None: ... - + errors: str | None # undocumented + def __init__( + self, filename: StrPath, mode: str = "a", encoding: str | None = None, delay: bool = False, errors: str | None = None + ) -> None: ... def _open(self) -> TextIOWrapper: ... # undocumented class NullHandler(Handler): ... diff --git a/mypy/typeshed/stdlib/logging/handlers.pyi b/mypy/typeshed/stdlib/logging/handlers.pyi index d594d6569a7e..2c7ec05afe9a 100644 --- a/mypy/typeshed/stdlib/logging/handlers.pyi +++ b/mypy/typeshed/stdlib/logging/handlers.pyi @@ -22,54 +22,34 @@ SYSLOG_TCP_PORT: Final[int] class WatchedFileHandler(FileHandler): dev: int # undocumented ino: int # undocumented - if sys.version_info >= (3, 9): - def __init__( - self, filename: StrPath, mode: str = "a", encoding: str | None = None, delay: bool = False, errors: str | None = None - ) -> None: ... - else: - def __init__(self, filename: StrPath, mode: str = "a", encoding: str | None = None, delay: bool = False) -> None: ... - + def __init__( + self, filename: StrPath, mode: str = "a", encoding: str | None = None, delay: bool = False, errors: str | None = None + ) -> None: ... def _statstream(self) -> None: ... # undocumented def reopenIfNeeded(self) -> None: ... class BaseRotatingHandler(FileHandler): namer: Callable[[str], str] | None rotator: Callable[[str, str], None] | None - if sys.version_info >= (3, 9): - def __init__( - self, filename: StrPath, mode: str, encoding: str | None = None, delay: bool = False, errors: str | None = None - ) -> None: ... - else: - def __init__(self, filename: StrPath, mode: str, encoding: str | None = None, delay: bool = False) -> None: ... - + def __init__( + self, filename: StrPath, mode: str, encoding: str | None = None, delay: bool = False, errors: str | None = None + ) -> None: ... def rotation_filename(self, default_name: str) -> str: ... def rotate(self, source: str, dest: str) -> None: ... class RotatingFileHandler(BaseRotatingHandler): maxBytes: int # undocumented backupCount: int # undocumented - if sys.version_info >= (3, 9): - def __init__( - self, - filename: StrPath, - mode: str = "a", - maxBytes: int = 0, - backupCount: int = 0, - encoding: str | None = None, - delay: bool = False, - errors: str | None = None, - ) -> None: ... - else: - def __init__( - self, - filename: StrPath, - mode: str = "a", - maxBytes: int = 0, - backupCount: int = 0, - encoding: str | None = None, - delay: bool = False, - ) -> None: ... - + def __init__( + self, + filename: StrPath, + mode: str = "a", + maxBytes: int = 0, + backupCount: int = 0, + encoding: str | None = None, + delay: bool = False, + errors: str | None = None, + ) -> None: ... def doRollover(self) -> None: ... def shouldRollover(self, record: LogRecord) -> int: ... # undocumented @@ -83,32 +63,18 @@ class TimedRotatingFileHandler(BaseRotatingHandler): dayOfWeek: int # undocumented rolloverAt: int # undocumented extMatch: Pattern[str] # undocumented - if sys.version_info >= (3, 9): - def __init__( - self, - filename: StrPath, - when: str = "h", - interval: int = 1, - backupCount: int = 0, - encoding: str | None = None, - delay: bool = False, - utc: bool = False, - atTime: datetime.time | None = None, - errors: str | None = None, - ) -> None: ... - else: - def __init__( - self, - filename: StrPath, - when: str = "h", - interval: int = 1, - backupCount: int = 0, - encoding: str | None = None, - delay: bool = False, - utc: bool = False, - atTime: datetime.time | None = None, - ) -> None: ... - + def __init__( + self, + filename: StrPath, + when: str = "h", + interval: int = 1, + backupCount: int = 0, + encoding: str | None = None, + delay: bool = False, + utc: bool = False, + atTime: datetime.time | None = None, + errors: str | None = None, + ) -> None: ... def doRollover(self) -> None: ... def shouldRollover(self, record: LogRecord) -> int: ... # undocumented def computeRollover(self, currentTime: int) -> int: ... # undocumented @@ -155,13 +121,10 @@ class SysLogHandler(Handler): LOG_CRON: int LOG_AUTHPRIV: int LOG_FTP: int - - if sys.version_info >= (3, 9): - LOG_NTP: int - LOG_SECURITY: int - LOG_CONSOLE: int - LOG_SOLCRON: int - + LOG_NTP: int + LOG_SECURITY: int + LOG_CONSOLE: int + LOG_SOLCRON: int LOG_LOCAL0: int LOG_LOCAL1: int LOG_LOCAL2: int @@ -191,7 +154,7 @@ class SysLogHandler(Handler): class NTEventLogHandler(Handler): def __init__(self, appname: str, dllname: str | None = None, logtype: str = "Application") -> None: ... def getEventCategory(self, record: LogRecord) -> int: ... - # TODO correct return value? + # TODO: correct return value? def getEventType(self, record: LogRecord) -> int: ... def getMessageID(self, record: LogRecord) -> int: ... @@ -248,8 +211,7 @@ class HTTPHandler(Handler): context: ssl.SSLContext | None = None, ) -> None: ... def mapLogRecord(self, record: LogRecord) -> dict[str, Any]: ... - if sys.version_info >= (3, 9): - def getConnection(self, host: str, secure: bool) -> http.client.HTTPConnection: ... # undocumented + def getConnection(self, host: str, secure: bool) -> http.client.HTTPConnection: ... # undocumented class _QueueLike(Protocol[_T]): def get(self) -> _T: ... diff --git a/mypy/typeshed/stdlib/mailbox.pyi b/mypy/typeshed/stdlib/mailbox.pyi index a98a00a42853..dc2fbd593d67 100644 --- a/mypy/typeshed/stdlib/mailbox.pyi +++ b/mypy/typeshed/stdlib/mailbox.pyi @@ -4,13 +4,10 @@ import sys from _typeshed import StrPath, SupportsNoArgReadline, SupportsRead from abc import ABCMeta, abstractmethod from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence -from types import TracebackType +from types import GenericAlias, TracebackType from typing import IO, Any, AnyStr, Generic, Literal, Protocol, TypeVar, overload from typing_extensions import Self, TypeAlias -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = [ "Mailbox", "Maildir", @@ -101,8 +98,7 @@ class Mailbox(Generic[_MessageT]): def unlock(self) -> None: ... @abstractmethod def close(self) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class Maildir(Mailbox[MaildirMessage]): colon: str @@ -251,8 +247,7 @@ class _ProxyFile(Generic[AnyStr]): def flush(self) -> None: ... @property def closed(self) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + 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: ... diff --git a/mypy/typeshed/stdlib/math.pyi b/mypy/typeshed/stdlib/math.pyi index f73429cf6940..9e77f0cd7e06 100644 --- a/mypy/typeshed/stdlib/math.pyi +++ b/mypy/typeshed/stdlib/math.pyi @@ -61,13 +61,7 @@ def fmod(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... def frexp(x: _SupportsFloatOrIndex, /) -> tuple[float, int]: ... def fsum(seq: Iterable[_SupportsFloatOrIndex], /) -> float: ... def gamma(x: _SupportsFloatOrIndex, /) -> float: ... - -if sys.version_info >= (3, 9): - def gcd(*integers: SupportsIndex) -> int: ... - -else: - def gcd(x: SupportsIndex, y: SupportsIndex, /) -> int: ... - +def gcd(*integers: SupportsIndex) -> int: ... def hypot(*coordinates: _SupportsFloatOrIndex) -> float: ... def isclose( a: _SupportsFloatOrIndex, @@ -80,10 +74,7 @@ def isinf(x: _SupportsFloatOrIndex, /) -> bool: ... def isfinite(x: _SupportsFloatOrIndex, /) -> bool: ... def isnan(x: _SupportsFloatOrIndex, /) -> bool: ... def isqrt(n: SupportsIndex, /) -> int: ... - -if sys.version_info >= (3, 9): - def lcm(*integers: SupportsIndex) -> int: ... - +def lcm(*integers: SupportsIndex) -> int: ... def ldexp(x: _SupportsFloatOrIndex, i: int, /) -> float: ... def lgamma(x: _SupportsFloatOrIndex, /) -> float: ... def log(x: _SupportsFloatOrIndex, base: _SupportsFloatOrIndex = ...) -> float: ... @@ -95,7 +86,7 @@ def modf(x: _SupportsFloatOrIndex, /) -> tuple[float, float]: ... if sys.version_info >= (3, 12): def nextafter(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /, *, steps: SupportsIndex | None = None) -> float: ... -elif sys.version_info >= (3, 9): +else: def nextafter(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ... def perm(n: SupportsIndex, k: SupportsIndex | None = None, /) -> int: ... @@ -140,9 +131,7 @@ class _SupportsTrunc(Protocol[_T_co]): def __trunc__(self) -> _T_co: ... def trunc(x: _SupportsTrunc[_T], /) -> _T: ... - -if sys.version_info >= (3, 9): - def ulp(x: _SupportsFloatOrIndex, /) -> float: ... +def ulp(x: _SupportsFloatOrIndex, /) -> float: ... if sys.version_info >= (3, 13): def fma(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, z: _SupportsFloatOrIndex, /) -> float: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi index ad5697e0ab1c..50e4f1c1fe66 100644 --- a/mypy/typeshed/stdlib/multiprocessing/managers.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/managers.pyi @@ -3,7 +3,7 @@ import sys import threading from _typeshed import SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence -from types import TracebackType +from types import GenericAlias, TracebackType from typing import Any, AnyStr, ClassVar, Generic, SupportsIndex, TypeVar, overload from typing_extensions import Self, TypeAlias @@ -15,9 +15,6 @@ from .util import Finalize as _Finalize __all__ = ["BaseManager", "SyncManager", "BaseProxy", "Token", "SharedMemoryManager"] -if sys.version_info >= (3, 9): - from types import GenericAlias - _T = TypeVar("_T") _KT = TypeVar("_KT") _VT = TypeVar("_VT") @@ -59,8 +56,7 @@ class ValueProxy(BaseProxy, Generic[_T]): def get(self) -> _T: ... def set(self, value: _T) -> None: ... value: _T - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... if sys.version_info >= (3, 13): class _BaseDictProxy(BaseProxy, MutableMapping[_KT, _VT]): diff --git a/mypy/typeshed/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi index 93197e5d4265..f276372d0903 100644 --- a/mypy/typeshed/stdlib/multiprocessing/pool.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/pool.pyi @@ -1,13 +1,9 @@ -import sys from collections.abc import Callable, Iterable, Iterator, Mapping from multiprocessing.context import DefaultContext, Process -from types import TracebackType +from types import GenericAlias, TracebackType from typing import Any, Final, Generic, TypeVar from typing_extensions import Self -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = ["Pool", "ThreadPool"] _S = TypeVar("_S") @@ -21,8 +17,7 @@ class ApplyResult(Generic[_T]): def wait(self, timeout: float | None = None) -> None: ... def ready(self) -> bool: ... def successful(self) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... # alias created during issue #17805 AsyncResult = ApplyResult diff --git a/mypy/typeshed/stdlib/multiprocessing/queues.pyi b/mypy/typeshed/stdlib/multiprocessing/queues.pyi index 581a46ea0bc8..a6b00d744c42 100644 --- a/mypy/typeshed/stdlib/multiprocessing/queues.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/queues.pyi @@ -1,9 +1,7 @@ import sys +from types import GenericAlias from typing import Any, Generic, TypeVar -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = ["Queue", "SimpleQueue", "JoinableQueue"] _T = TypeVar("_T") @@ -31,11 +29,8 @@ class JoinableQueue(Queue[_T]): class SimpleQueue(Generic[_T]): def __init__(self, *, ctx: Any = ...) -> None: ... - if sys.version_info >= (3, 9): - def close(self) -> None: ... - + def close(self) -> None: ... def empty(self) -> bool: ... def get(self) -> _T: ... def put(self, obj: _T) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/resource_tracker.pyi b/mypy/typeshed/stdlib/multiprocessing/resource_tracker.pyi index 61da7fdf1ceb..cb2f27a62861 100644 --- a/mypy/typeshed/stdlib/multiprocessing/resource_tracker.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/resource_tracker.pyi @@ -1,3 +1,4 @@ +import sys from _typeshed import FileDescriptorOrPath from collections.abc import Sized @@ -8,6 +9,8 @@ class ResourceTracker: def ensure_running(self) -> None: ... def register(self, name: Sized, rtype: str) -> None: ... def unregister(self, name: Sized, rtype: str) -> None: ... + if sys.version_info >= (3, 12): + def __del__(self) -> None: ... _resource_tracker: ResourceTracker ensure_running = _resource_tracker.ensure_running diff --git a/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi index b63cedf85867..1a12812c27e4 100644 --- a/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi @@ -1,11 +1,9 @@ import sys from collections.abc import Iterable +from types import GenericAlias from typing import Any, Generic, TypeVar, overload from typing_extensions import Self -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = ["SharedMemory", "ShareableList"] _SLT = TypeVar("_SLT", int, float, bool, str, bytes, None) @@ -40,5 +38,4 @@ class ShareableList(Generic[_SLT]): def format(self) -> str: ... def count(self, value: _SLT) -> int: ... def index(self, value: _SLT) -> int: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/nntplib.pyi b/mypy/typeshed/stdlib/nntplib.pyi index 85dfbff1cb50..1fb1e79f69a1 100644 --- a/mypy/typeshed/stdlib/nntplib.pyi +++ b/mypy/typeshed/stdlib/nntplib.pyi @@ -1,7 +1,6 @@ import datetime import socket import ssl -import sys from _typeshed import Unused from builtins import list as _list # conflicts with a method named "list" from collections.abc import Iterable @@ -98,10 +97,6 @@ class NNTP: def over( self, message_spec: None | str | _list[Any] | tuple[Any, ...], *, file: _File = None ) -> tuple[str, _list[tuple[int, dict[str, str]]]]: ... - if sys.version_info < (3, 9): - def xgtitle(self, group: str, *, file: _File = None) -> tuple[str, _list[tuple[str, str]]]: ... - def xpath(self, id: Any) -> tuple[str, str]: ... - def date(self) -> tuple[str, datetime.datetime]: ... def post(self, data: bytes | Iterable[bytes]) -> str: ... def ihave(self, message_id: Any, data: bytes | Iterable[bytes]) -> str: ... diff --git a/mypy/typeshed/stdlib/nt.pyi b/mypy/typeshed/stdlib/nt.pyi index e1d57d09a9bd..3ed8f8af379b 100644 --- a/mypy/typeshed/stdlib/nt.pyi +++ b/mypy/typeshed/stdlib/nt.pyi @@ -89,14 +89,14 @@ if sys.platform == "win32": umask as umask, uname_result as uname_result, unlink as unlink, + unsetenv as unsetenv, urandom as urandom, utime as utime, waitpid as waitpid, + waitstatus_to_exitcode as waitstatus_to_exitcode, write as write, ) - if sys.version_info >= (3, 9): - from os import unsetenv as unsetenv, waitstatus_to_exitcode as waitstatus_to_exitcode if sys.version_info >= (3, 11): from os import EX_OK as EX_OK if sys.version_info >= (3, 12): diff --git a/mypy/typeshed/stdlib/opcode.pyi b/mypy/typeshed/stdlib/opcode.pyi index f9f76962f876..a5a3a79c323b 100644 --- a/mypy/typeshed/stdlib/opcode.pyi +++ b/mypy/typeshed/stdlib/opcode.pyi @@ -23,23 +23,7 @@ else: if sys.version_info >= (3, 13): __all__ += ["hasjump"] -if sys.version_info >= (3, 9): - cmp_op: tuple[Literal["<"], Literal["<="], Literal["=="], Literal["!="], Literal[">"], Literal[">="]] -else: - cmp_op: tuple[ - Literal["<"], - Literal["<="], - Literal["=="], - Literal["!="], - Literal[">"], - Literal[">="], - Literal["in"], - Literal["not in"], - Literal["is"], - Literal["is not"], - Literal["exception match"], - Literal["BAD"], - ] +cmp_op: tuple[Literal["<"], Literal["<="], Literal["=="], Literal["!="], Literal[">"], Literal[">="]] hasconst: list[int] hasname: list[int] hasjrel: list[int] diff --git a/mypy/typeshed/stdlib/optparse.pyi b/mypy/typeshed/stdlib/optparse.pyi index 56a4574bdba8..8b7fcd82e5a5 100644 --- a/mypy/typeshed/stdlib/optparse.pyi +++ b/mypy/typeshed/stdlib/optparse.pyi @@ -239,7 +239,7 @@ class Values: # __getattr__ doesn't exist, but anything passed as a default to __init__ # is set on the instance. def __getattr__(self, name: str) -> Any: ... - # TODO mypy infers -> object for __getattr__ if __setattr__ has `value: object` + # TODO: mypy infers -> object for __getattr__ if __setattr__ has `value: object` def __setattr__(self, name: str, value: Any, /) -> None: ... def __eq__(self, other: object) -> bool: ... diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 4a7c03632a67..d0ef614abbce 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -24,7 +24,7 @@ from builtins import OSError from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping, Sequence from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper from subprocess import Popen -from types import TracebackType +from types import GenericAlias, TracebackType from typing import ( IO, Any, @@ -44,9 +44,6 @@ from typing_extensions import Self, TypeAlias, Unpack, deprecated from . import path as _path -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = [ "F_OK", "O_APPEND", @@ -155,14 +152,14 @@ __all__ = [ "umask", "uname_result", "unlink", + "unsetenv", "urandom", "utime", "waitpid", + "waitstatus_to_exitcode", "walk", "write", ] -if sys.version_info >= (3, 9): - __all__ += ["waitstatus_to_exitcode"] 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): @@ -194,6 +191,7 @@ if sys.platform == "linux": "O_PATH", "O_RSYNC", "O_TMPFILE", + "P_PIDFD", "RTLD_DEEPBIND", "SCHED_BATCH", "SCHED_IDLE", @@ -206,6 +204,7 @@ if sys.platform == "linux": "getxattr", "listxattr", "memfd_create", + "pidfd_open", "removexattr", "setxattr", ] @@ -256,8 +255,6 @@ if sys.platform == "linux" and sys.version_info >= (3, 10): "eventfd_write", "splice", ] -if sys.platform == "linux" and sys.version_info >= (3, 9): - __all__ += ["P_PIDFD", "pidfd_open"] if sys.platform == "win32": __all__ += [ "O_BINARY", @@ -280,6 +277,8 @@ if sys.platform != "win32": "CLD_CONTINUED", "CLD_DUMPED", "CLD_EXITED", + "CLD_KILLED", + "CLD_STOPPED", "CLD_TRAPPED", "EX_CANTCREAT", "EX_CONFIG", @@ -431,8 +430,6 @@ if sys.platform != "win32" and sys.version_info >= (3, 11): __all__ += ["login_tty"] if sys.platform != "win32" and sys.version_info >= (3, 10): __all__ += ["O_FSYNC"] -if sys.platform != "win32" and sys.version_info >= (3, 9): - __all__ += ["CLD_KILLED", "CLD_STOPPED"] if sys.platform != "darwin" and sys.platform != "win32": __all__ += [ "POSIX_FADV_DONTNEED", @@ -486,8 +483,6 @@ if sys.platform != "win32" or sys.version_info >= (3, 12): __all__ += ["get_blocking", "set_blocking"] if sys.platform != "win32" or sys.version_info >= (3, 11): __all__ += ["EX_OK"] -if sys.platform != "win32" or sys.version_info >= (3, 9): - __all__ += ["unsetenv"] # This unnecessary alias is to work around various errors path = _path @@ -550,7 +545,7 @@ if sys.platform != "win32": P_PGID: int P_ALL: int - if sys.platform == "linux" and sys.version_info >= (3, 9): + if sys.platform == "linux": P_PIDFD: int WEXITED: int @@ -561,10 +556,8 @@ if sys.platform != "win32": CLD_DUMPED: int CLD_TRAPPED: int CLD_CONTINUED: int - - if sys.version_info >= (3, 9): - CLD_KILLED: int - CLD_STOPPED: int + CLD_KILLED: int + CLD_STOPPED: int SCHED_OTHER: int SCHED_FIFO: int @@ -698,29 +691,14 @@ class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): decodekey: _EnvironCodeFunc[AnyStr] encodevalue: _EnvironCodeFunc[AnyStr] decodevalue: _EnvironCodeFunc[AnyStr] - if sys.version_info >= (3, 9): - def __init__( - self, - data: MutableMapping[AnyStr, AnyStr], - encodekey: _EnvironCodeFunc[AnyStr], - decodekey: _EnvironCodeFunc[AnyStr], - encodevalue: _EnvironCodeFunc[AnyStr], - decodevalue: _EnvironCodeFunc[AnyStr], - ) -> None: ... - else: - putenv: Callable[[AnyStr, AnyStr], object] - unsetenv: Callable[[AnyStr, AnyStr], object] - def __init__( - self, - data: MutableMapping[AnyStr, AnyStr], - encodekey: _EnvironCodeFunc[AnyStr], - decodekey: _EnvironCodeFunc[AnyStr], - encodevalue: _EnvironCodeFunc[AnyStr], - decodevalue: _EnvironCodeFunc[AnyStr], - putenv: Callable[[AnyStr, AnyStr], object], - unsetenv: Callable[[AnyStr, AnyStr], object], - ) -> None: ... - + def __init__( + self, + data: MutableMapping[AnyStr, AnyStr], + encodekey: _EnvironCodeFunc[AnyStr], + decodekey: _EnvironCodeFunc[AnyStr], + encodevalue: _EnvironCodeFunc[AnyStr], + decodevalue: _EnvironCodeFunc[AnyStr], + ) -> None: ... def setdefault(self, key: AnyStr, value: AnyStr) -> AnyStr: ... def copy(self) -> dict[AnyStr, AnyStr]: ... def __delitem__(self, key: AnyStr) -> None: ... @@ -728,16 +706,15 @@ class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): def __setitem__(self, key: AnyStr, value: AnyStr) -> None: ... def __iter__(self) -> Iterator[AnyStr]: ... def __len__(self) -> int: ... - if sys.version_info >= (3, 9): - 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 - @overload # type: ignore[misc] - def __ior__(self, other: Mapping[AnyStr, AnyStr]) -> Self: ... - @overload - def __ior__(self, other: Iterable[tuple[AnyStr, AnyStr]]) -> Self: ... + 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 + @overload # type: ignore[misc] + def __ior__(self, other: Mapping[AnyStr, AnyStr]) -> Self: ... + @overload + def __ior__(self, other: Iterable[tuple[AnyStr, AnyStr]]) -> Self: ... environ: _Environ[str] if sys.platform != "win32": @@ -900,8 +877,7 @@ class DirEntry(Generic[AnyStr]): def is_symlink(self) -> bool: ... def stat(self, *, follow_symlinks: bool = True) -> stat_result: ... def __fspath__(self) -> AnyStr: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... if sys.version_info >= (3, 12): def is_junction(self) -> bool: ... @@ -1024,9 +1000,7 @@ if sys.platform != "win32": else: def putenv(name: str, value: str, /) -> None: ... - - if sys.version_info >= (3, 9): - def unsetenv(name: str, /) -> None: ... + def unsetenv(name: str, /) -> None: ... _Opener: TypeAlias = Callable[[str, int], int] @@ -1598,11 +1572,10 @@ if sys.platform == "linux": def memfd_create(name: str, flags: int = ...) -> int: ... def copy_file_range(src: int, dst: int, count: int, offset_src: int | None = ..., offset_dst: int | None = ...) -> int: ... -if sys.version_info >= (3, 9): - def waitstatus_to_exitcode(status: int) -> int: ... +def waitstatus_to_exitcode(status: int) -> int: ... - if sys.platform == "linux": - def pidfd_open(pid: int, flags: int = ...) -> int: ... +if sys.platform == "linux": + def pidfd_open(pid: int, flags: int = ...) -> int: ... if sys.version_info >= (3, 12) and sys.platform == "linux": PIDFD_NONBLOCK: Final = 2048 diff --git a/mypy/typeshed/stdlib/pathlib.pyi b/mypy/typeshed/stdlib/pathlib.pyi index a18aed4ba57a..1e4d97770b7b 100644 --- a/mypy/typeshed/stdlib/pathlib.pyi +++ b/mypy/typeshed/stdlib/pathlib.pyi @@ -14,13 +14,10 @@ from _typeshed import ( from collections.abc import Callable, Generator, Iterator, Sequence from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper from os import PathLike, stat_result -from types import TracebackType +from types import GenericAlias, TracebackType from typing import IO, Any, BinaryIO, ClassVar, Literal, overload from typing_extensions import Never, Self, deprecated -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = ["PurePath", "PurePosixPath", "PureWindowsPath", "Path", "PosixPath", "WindowsPath"] if sys.version_info >= (3, 13): @@ -68,7 +65,7 @@ class PurePath(PathLike[str]): def is_reserved(self) -> bool: ... if sys.version_info >= (3, 12): def is_relative_to(self, other: StrPath, /, *_deprecated: StrPath) -> bool: ... - elif sys.version_info >= (3, 9): + else: def is_relative_to(self, *other: StrPath) -> bool: ... if sys.version_info >= (3, 12): @@ -82,16 +79,14 @@ class PurePath(PathLike[str]): def relative_to(self, *other: StrPath) -> Self: ... def with_name(self, name: str) -> Self: ... - if sys.version_info >= (3, 9): - def with_stem(self, stem: str) -> Self: ... - + def with_stem(self, stem: str) -> Self: ... def with_suffix(self, suffix: str) -> Self: ... def joinpath(self, *other: StrPath) -> Self: ... @property def parents(self) -> Sequence[Self]: ... @property def parent(self) -> Self: ... - if sys.version_info >= (3, 9) and sys.version_info < (3, 11): + if sys.version_info < (3, 11): def __class_getitem__(cls, type: Any) -> GenericAlias: ... if sys.version_info >= (3, 12): @@ -247,8 +242,7 @@ class Path(PurePath): else: def is_mount(self) -> bool: ... - if sys.version_info >= (3, 9): - def readlink(self) -> Self: ... + def readlink(self) -> Self: ... if sys.version_info >= (3, 10): def rename(self, target: StrPath) -> Self: ... diff --git a/mypy/typeshed/stdlib/pkgutil.pyi b/mypy/typeshed/stdlib/pkgutil.pyi index 59d70779c72f..d60e9bad53ae 100644 --- a/mypy/typeshed/stdlib/pkgutil.pyi +++ b/mypy/typeshed/stdlib/pkgutil.pyi @@ -48,6 +48,4 @@ 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: ... - -if sys.version_info >= (3, 9): - def resolve_name(name: str) -> Any: ... +def resolve_name(name: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/platform.pyi b/mypy/typeshed/stdlib/platform.pyi index 73393eada02c..19fac26134eb 100644 --- a/mypy/typeshed/stdlib/platform.pyi +++ b/mypy/typeshed/stdlib/platform.pyi @@ -15,40 +15,29 @@ def java_ver( 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]: ... -if sys.version_info >= (3, 9): - # This class is not exposed. It calls itself platform.uname_result_base. - # At runtime it only has 5 fields. - @type_check_only - class _uname_result_base(NamedTuple): - system: str - node: str - release: str - version: str - machine: str - # This base class doesn't have this field at runtime, but claiming it - # does is the least bad way to handle the situation. Nobody really - # sees this class anyway. See #13068 - processor: str - - # uname_result emulates a 6-field named tuple, but the processor field - # is lazily evaluated rather than being passed in to the constructor. - class uname_result(_uname_result_base): - if sys.version_info >= (3, 10): - __match_args__ = ("system", "node", "release", "version", "machine") # pyright: ignore[reportAssignmentType] +# This class is not exposed. It calls itself platform.uname_result_base. +# At runtime it only has 5 fields. +@type_check_only +class _uname_result_base(NamedTuple): + system: str + node: str + release: str + version: str + machine: str + # This base class doesn't have this field at runtime, but claiming it + # does is the least bad way to handle the situation. Nobody really + # sees this class anyway. See #13068 + processor: str - def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self: ... - @property - def processor(self) -> str: ... +# uname_result emulates a 6-field named tuple, but the processor field +# is lazily evaluated rather than being passed in to the constructor. +class uname_result(_uname_result_base): + if sys.version_info >= (3, 10): + __match_args__ = ("system", "node", "release", "version", "machine") # pyright: ignore[reportAssignmentType] -else: - # On 3.8, uname_result is actually just a regular NamedTuple. - class uname_result(NamedTuple): - system: str - node: str - release: str - version: str - machine: str - processor: str + def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self: ... + @property + def processor(self) -> str: ... def uname() -> uname_result: ... def system() -> str: ... diff --git a/mypy/typeshed/stdlib/plistlib.pyi b/mypy/typeshed/stdlib/plistlib.pyi index 72b5398f0a52..8b39b4217eae 100644 --- a/mypy/typeshed/stdlib/plistlib.pyi +++ b/mypy/typeshed/stdlib/plistlib.pyi @@ -3,12 +3,10 @@ from _typeshed import ReadableBuffer from collections.abc import Mapping, MutableMapping from datetime import datetime from enum import Enum -from typing import IO, Any, ClassVar +from typing import IO, Any from typing_extensions import Self __all__ = ["InvalidFileException", "FMT_XML", "FMT_BINARY", "load", "dump", "loads", "dumps", "UID"] -if sys.version_info < (3, 9): - __all__ += ["readPlist", "writePlist", "readPlistFromBytes", "writePlistToBytes", "Data"] class PlistFormat(Enum): FMT_XML = 1 @@ -32,28 +30,12 @@ if sys.version_info >= (3, 13): aware_datetime: bool = False, ) -> Any: ... -elif sys.version_info >= (3, 9): +else: def load(fp: IO[bytes], *, fmt: PlistFormat | None = None, dict_type: type[MutableMapping[str, Any]] = ...) -> Any: ... def loads( value: ReadableBuffer, *, fmt: PlistFormat | None = None, dict_type: type[MutableMapping[str, Any]] = ... ) -> Any: ... -else: - def load( - fp: IO[bytes], - *, - fmt: PlistFormat | None = None, - use_builtin_types: bool = True, - dict_type: type[MutableMapping[str, Any]] = ..., - ) -> Any: ... - def loads( - value: ReadableBuffer, - *, - fmt: PlistFormat | None = None, - use_builtin_types: bool = True, - dict_type: type[MutableMapping[str, Any]] = ..., - ) -> Any: ... - if sys.version_info >= (3, 13): def dump( value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime, @@ -90,18 +72,6 @@ else: sort_keys: bool = True, ) -> bytes: ... -if sys.version_info < (3, 9): - def readPlist(pathOrFile: str | IO[bytes]) -> Any: ... - def writePlist(value: Mapping[str, Any], pathOrFile: str | IO[bytes]) -> None: ... - def readPlistFromBytes(data: ReadableBuffer) -> Any: ... - def writePlistToBytes(value: Mapping[str, Any]) -> bytes: ... - -if sys.version_info < (3, 9): - class Data: - data: bytes - def __init__(self, data: bytes) -> None: ... - __hash__: ClassVar[None] # type: ignore[assignment] - class UID: data: int def __init__(self, data: int) -> None: ... diff --git a/mypy/typeshed/stdlib/posix.pyi b/mypy/typeshed/stdlib/posix.pyi index e7223842ace5..88f4135af2a7 100644 --- a/mypy/typeshed/stdlib/posix.pyi +++ b/mypy/typeshed/stdlib/posix.pyi @@ -6,6 +6,8 @@ if sys.platform != "win32": CLD_CONTINUED as CLD_CONTINUED, CLD_DUMPED as CLD_DUMPED, CLD_EXITED as CLD_EXITED, + CLD_KILLED as CLD_KILLED, + CLD_STOPPED as CLD_STOPPED, CLD_TRAPPED as CLD_TRAPPED, EX_CANTCREAT as EX_CANTCREAT, EX_CONFIG as EX_CONFIG, @@ -220,13 +222,11 @@ if sys.platform != "win32": wait3 as wait3, wait4 as wait4, waitpid as waitpid, + waitstatus_to_exitcode as waitstatus_to_exitcode, write as write, writev as writev, ) - if sys.version_info >= (3, 9): - from os import CLD_KILLED as CLD_KILLED, CLD_STOPPED as CLD_STOPPED, waitstatus_to_exitcode as waitstatus_to_exitcode - if sys.version_info >= (3, 10): from os import O_FSYNC as O_FSYNC @@ -330,6 +330,7 @@ if sys.platform != "win32": O_PATH as O_PATH, O_RSYNC as O_RSYNC, O_TMPFILE as O_TMPFILE, + P_PIDFD as P_PIDFD, RTLD_DEEPBIND as RTLD_DEEPBIND, SCHED_BATCH as SCHED_BATCH, SCHED_IDLE as SCHED_IDLE, @@ -342,13 +343,11 @@ if sys.platform != "win32": getxattr as getxattr, listxattr as listxattr, memfd_create as memfd_create, + pidfd_open as pidfd_open, removexattr as removexattr, setxattr as setxattr, ) - if sys.version_info >= (3, 9): - from os import P_PIDFD as P_PIDFD, pidfd_open as pidfd_open - if sys.version_info >= (3, 10): from os import ( EFD_CLOEXEC as EFD_CLOEXEC, diff --git a/mypy/typeshed/stdlib/pstats.pyi b/mypy/typeshed/stdlib/pstats.pyi index d41fa202cf77..c4dee1f6b8f6 100644 --- a/mypy/typeshed/stdlib/pstats.pyi +++ b/mypy/typeshed/stdlib/pstats.pyi @@ -2,6 +2,7 @@ import sys from _typeshed import StrOrBytesPath 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 @@ -11,10 +12,7 @@ if sys.version_info >= (3, 11): else: from enum import Enum -if sys.version_info >= (3, 9): - __all__ = ["Stats", "SortKey", "FunctionProfile", "StatsProfile"] -else: - __all__ = ["Stats", "SortKey"] +__all__ = ["Stats", "SortKey", "FunctionProfile", "StatsProfile"] _Selector: TypeAlias = str | float | int @@ -42,23 +40,20 @@ else: STDNAME = "stdname" TIME = "time" -if sys.version_info >= (3, 9): - from dataclasses import dataclass - - @dataclass(unsafe_hash=True) - class FunctionProfile: - ncalls: str - tottime: float - percall_tottime: float - cumtime: float - percall_cumtime: float - file_name: str - line_number: int +@dataclass(unsafe_hash=True) +class FunctionProfile: + ncalls: str + tottime: float + percall_tottime: float + cumtime: float + percall_cumtime: float + file_name: str + line_number: int - @dataclass(unsafe_hash=True) - class StatsProfile: - total_tt: float - func_profiles: dict[str, FunctionProfile] +@dataclass(unsafe_hash=True) +class StatsProfile: + total_tt: float + func_profiles: dict[str, FunctionProfile] _SortArgDict: TypeAlias = dict[str, tuple[tuple[tuple[int, int], ...], str]] @@ -85,9 +80,7 @@ class Stats: def strip_dirs(self) -> Self: ... def calc_callees(self) -> None: ... def eval_print_amount(self, sel: _Selector, list: list[str], msg: str) -> tuple[list[str], str]: ... - if sys.version_info >= (3, 9): - def get_stats_profile(self) -> StatsProfile: ... - + def get_stats_profile(self) -> StatsProfile: ... def get_print_list(self, sel_list: Iterable[_Selector]) -> tuple[int, list[str]]: ... def print_stats(self, *amount: _Selector) -> Self: ... def print_callees(self, *amount: _Selector) -> Self: ... diff --git a/mypy/typeshed/stdlib/queue.pyi b/mypy/typeshed/stdlib/queue.pyi index 4fb49cb6102b..f5d9179e079d 100644 --- a/mypy/typeshed/stdlib/queue.pyi +++ b/mypy/typeshed/stdlib/queue.pyi @@ -1,11 +1,9 @@ import sys from _queue import Empty as Empty, SimpleQueue as SimpleQueue from threading import Condition, Lock +from types import GenericAlias from typing import Any, Generic, TypeVar -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = ["Empty", "Full", "Queue", "PriorityQueue", "LifoQueue", "SimpleQueue"] if sys.version_info >= (3, 13): __all__ += ["ShutDown"] @@ -47,8 +45,7 @@ class Queue(Generic[_T]): def qsize(self) -> int: ... def _qsize(self) -> int: ... def task_done(self) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class PriorityQueue(Queue[_T]): queue: list[_T] diff --git a/mypy/typeshed/stdlib/random.pyi b/mypy/typeshed/stdlib/random.pyi index e7320369c377..83e37113a941 100644 --- a/mypy/typeshed/stdlib/random.pyi +++ b/mypy/typeshed/stdlib/random.pyi @@ -30,10 +30,9 @@ __all__ = [ "getrandbits", "choices", "SystemRandom", + "randbytes", ] -if sys.version_info >= (3, 9): - __all__ += ["randbytes"] if sys.version_info >= (3, 12): __all__ += ["binomialvariate"] @@ -41,25 +40,16 @@ _T = TypeVar("_T") class Random(_random.Random): VERSION: ClassVar[int] - if sys.version_info >= (3, 9): - def __init__(self, x: int | float | str | bytes | bytearray | None = None) -> None: ... # noqa: Y041 - else: - def __init__(self, x: Any = None) -> None: ... + def __init__(self, x: int | float | str | bytes | bytearray | None = None) -> None: ... # noqa: Y041 # 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, 9): - def seed(self, a: int | float | str | bytes | bytearray | None = None, version: int = 2) -> None: ... # type: ignore[override] # noqa: Y041 - else: - def seed(self, a: Any = None, version: int = 2) -> None: ... - + 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, ...]: ... def setstate(self, state: tuple[Any, ...]) -> None: ... def randrange(self, start: int, stop: int | None = None, step: int = 1) -> int: ... def randint(self, a: int, b: int) -> int: ... - if sys.version_info >= (3, 9): - def randbytes(self, n: int) -> bytes: ... - + def randbytes(self, n: int) -> bytes: ... def choice(self, seq: SupportsLenAndGetItem[_T]) -> _T: ... def choices( self, @@ -75,12 +65,10 @@ class Random(_random.Random): 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]: ... - elif sys.version_info >= (3, 9): + else: def sample( self, population: Sequence[_T] | AbstractSet[_T], k: int, *, counts: Iterable[int] | None = None ) -> list[_T]: ... - else: - def sample(self, population: Sequence[_T] | AbstractSet[_T], k: int) -> list[_T]: ... def uniform(self, a: float, b: float) -> float: ... def triangular(self, low: float = 0.0, high: float = 1.0, mode: float | None = None) -> float: ... @@ -137,5 +125,4 @@ weibullvariate = _inst.weibullvariate getstate = _inst.getstate setstate = _inst.setstate getrandbits = _inst.getrandbits -if sys.version_info >= (3, 9): - randbytes = _inst.randbytes +randbytes = _inst.randbytes diff --git a/mypy/typeshed/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi index fccdedae9436..f25a0a376704 100644 --- a/mypy/typeshed/stdlib/re.pyi +++ b/mypy/typeshed/stdlib/re.pyi @@ -4,12 +4,10 @@ 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 -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = [ "match", "fullmatch", @@ -117,8 +115,7 @@ class Match(Generic[AnyStr]): def __getitem__(self, key: int | str, /) -> AnyStr | MaybeNone: ... def __copy__(self) -> Match[AnyStr]: ... def __deepcopy__(self, memo: Any, /) -> Match[AnyStr]: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @final class Pattern(Generic[AnyStr]): @@ -197,8 +194,7 @@ class Pattern(Generic[AnyStr]): def __deepcopy__(self, memo: Any, /) -> Pattern[AnyStr]: ... def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... # ----- re variables and constants ----- diff --git a/mypy/typeshed/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi index 0fe560fd9b6a..ea2c29d4625f 100644 --- a/mypy/typeshed/stdlib/shutil.pyi +++ b/mypy/typeshed/stdlib/shutil.pyi @@ -1,6 +1,6 @@ import os import sys -from _typeshed import BytesPath, ExcInfo, FileDescriptorOrPath, StrOrBytesPath, StrPath, SupportsRead, SupportsWrite +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 @@ -36,9 +36,8 @@ __all__ = [ ] _StrOrBytesPathT = TypeVar("_StrOrBytesPathT", bound=StrOrBytesPath) -# Return value of some functions that may either return a path-like object that was passed in or -# a string -_PathReturn: TypeAlias = Any +_StrPathT = TypeVar("_StrPathT", bound=StrPath) +_BytesPathT = TypeVar("_BytesPathT", bound=BytesPath) class Error(OSError): ... class SameFileError(Error): ... @@ -52,23 +51,23 @@ def copyfile(src: StrOrBytesPath, dst: _StrOrBytesPathT, *, follow_symlinks: boo 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: StrPath, *, follow_symlinks: bool = True) -> _PathReturn: ... +def copy(src: StrPath, dst: _StrPathT, *, follow_symlinks: bool = True) -> _StrPathT | str: ... @overload -def copy(src: BytesPath, dst: BytesPath, *, follow_symlinks: bool = True) -> _PathReturn: ... +def copy(src: BytesPath, dst: _BytesPathT, *, follow_symlinks: bool = True) -> _BytesPathT | bytes: ... @overload -def copy2(src: StrPath, dst: StrPath, *, follow_symlinks: bool = True) -> _PathReturn: ... +def copy2(src: StrPath, dst: _StrPathT, *, follow_symlinks: bool = True) -> _StrPathT | str: ... @overload -def copy2(src: BytesPath, dst: BytesPath, *, follow_symlinks: bool = True) -> _PathReturn: ... +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, - dst: StrPath, + dst: _StrPathT, symlinks: bool = False, ignore: None | Callable[[str, list[str]], Iterable[str]] | Callable[[StrPath, list[str]], Iterable[str]] = None, copy_function: Callable[[str, str], object] = ..., ignore_dangling_symlinks: bool = False, dirs_exist_ok: bool = False, -) -> _PathReturn: ... +) -> _StrPathT: ... _OnErrorCallback: TypeAlias = Callable[[Callable[..., Any], str, ExcInfo], object] _OnExcCallback: TypeAlias = Callable[[Callable[..., Any], str, BaseException], object] @@ -129,12 +128,7 @@ _CopyFn: TypeAlias = Callable[[str, str], object] | Callable[[StrPath, StrPath], # N.B. shutil.move appears to take bytes arguments, however, # this does not work when dst is (or is within) an existing directory. # (#6832) -if sys.version_info >= (3, 9): - def move(src: StrPath, dst: StrPath, copy_function: _CopyFn = ...) -> _PathReturn: ... - -else: - # See https://bugs.python.org/issue32689 - def move(src: str, dst: StrPath, copy_function: _CopyFn = ...) -> _PathReturn: ... +def move(src: StrPath, dst: _StrPathT, copy_function: _CopyFn = ...) -> _StrPathT | str | MaybeNone: ... class _ntuple_diskusage(NamedTuple): total: int diff --git a/mypy/typeshed/stdlib/signal.pyi b/mypy/typeshed/stdlib/signal.pyi index 8fc853b25cc1..d50565d1c8ac 100644 --- a/mypy/typeshed/stdlib/signal.pyi +++ b/mypy/typeshed/stdlib/signal.pyi @@ -183,6 +183,5 @@ def valid_signals() -> set[Signals]: ... def raise_signal(signalnum: _SIGNUM, /) -> None: ... def set_wakeup_fd(fd: int, /, *, warn_on_full_buffer: bool = ...) -> int: ... -if sys.version_info >= (3, 9): - if sys.platform == "linux": - def pidfd_send_signal(pidfd: int, sig: int, siginfo: None = None, flags: int = ..., /) -> None: ... +if sys.platform == "linux": + def pidfd_send_signal(pidfd: int, sig: int, siginfo: None = None, flags: int = ..., /) -> None: ... diff --git a/mypy/typeshed/stdlib/smtplib.pyi b/mypy/typeshed/stdlib/smtplib.pyi index a762427bcab3..609b3e6426c4 100644 --- a/mypy/typeshed/stdlib/smtplib.pyi +++ b/mypy/typeshed/stdlib/smtplib.pyi @@ -185,20 +185,11 @@ class SMTP_SSL(SMTP): LMTP_PORT: int class LMTP(SMTP): - if sys.version_info >= (3, 9): - def __init__( - self, - host: str = "", - port: int = 2003, - local_hostname: str | None = None, - source_address: _SourceAddress | None = None, - timeout: float = ..., - ) -> None: ... - else: - def __init__( - self, - host: str = "", - port: int = 2003, - local_hostname: str | None = None, - source_address: _SourceAddress | None = None, - ) -> None: ... + def __init__( + self, + host: str = "", + port: int = 2003, + local_hostname: str | None = None, + source_address: _SourceAddress | None = None, + timeout: float = ..., + ) -> None: ... diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index 1c996ac32278..ff89dcc72209 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -53,12 +53,18 @@ from _socket import ( IPPROTO_TCP as IPPROTO_TCP, IPPROTO_UDP as IPPROTO_UDP, IPV6_CHECKSUM as IPV6_CHECKSUM, + IPV6_DONTFRAG as IPV6_DONTFRAG, + IPV6_HOPLIMIT as IPV6_HOPLIMIT, + IPV6_HOPOPTS as IPV6_HOPOPTS, IPV6_JOIN_GROUP as IPV6_JOIN_GROUP, IPV6_LEAVE_GROUP as IPV6_LEAVE_GROUP, IPV6_MULTICAST_HOPS as IPV6_MULTICAST_HOPS, IPV6_MULTICAST_IF as IPV6_MULTICAST_IF, IPV6_MULTICAST_LOOP as IPV6_MULTICAST_LOOP, + IPV6_PKTINFO as IPV6_PKTINFO, + IPV6_RECVRTHDR as IPV6_RECVRTHDR, IPV6_RECVTCLASS as IPV6_RECVTCLASS, + IPV6_RTHDR as IPV6_RTHDR, IPV6_TCLASS as IPV6_TCLASS, IPV6_UNICAST_HOPS as IPV6_UNICAST_HOPS, IPV6_V6ONLY as IPV6_V6ONLY, @@ -195,12 +201,18 @@ __all__ = [ "IPPROTO_TCP", "IPPROTO_UDP", "IPV6_CHECKSUM", + "IPV6_DONTFRAG", + "IPV6_HOPLIMIT", + "IPV6_HOPOPTS", "IPV6_JOIN_GROUP", "IPV6_LEAVE_GROUP", "IPV6_MULTICAST_HOPS", "IPV6_MULTICAST_IF", "IPV6_MULTICAST_LOOP", + "IPV6_PKTINFO", + "IPV6_RECVRTHDR", "IPV6_RECVTCLASS", + "IPV6_RTHDR", "IPV6_TCLASS", "IPV6_UNICAST_HOPS", "IPV6_V6ONLY", @@ -335,18 +347,6 @@ if sys.platform == "win32": "MSG_MCAST", ] -if sys.platform != "darwin" or sys.version_info >= (3, 9): - from _socket import ( - IPV6_DONTFRAG as IPV6_DONTFRAG, - IPV6_HOPLIMIT as IPV6_HOPLIMIT, - IPV6_HOPOPTS as IPV6_HOPOPTS, - IPV6_PKTINFO as IPV6_PKTINFO, - IPV6_RECVRTHDR as IPV6_RECVRTHDR, - IPV6_RTHDR as IPV6_RTHDR, - ) - - __all__ += ["IPV6_DONTFRAG", "IPV6_HOPLIMIT", "IPV6_HOPOPTS", "IPV6_PKTINFO", "IPV6_RECVRTHDR", "IPV6_RTHDR"] - if sys.platform == "darwin": from _socket import PF_SYSTEM as PF_SYSTEM, SYSPROTO_CONTROL as SYSPROTO_CONTROL @@ -490,41 +490,39 @@ if sys.platform != "win32": "MSG_NOSIGNAL", ] - if sys.platform != "darwin" or sys.version_info >= (3, 9): - from _socket import ( - IPV6_DSTOPTS as IPV6_DSTOPTS, - IPV6_NEXTHOP as IPV6_NEXTHOP, - IPV6_PATHMTU as IPV6_PATHMTU, - IPV6_RECVDSTOPTS as IPV6_RECVDSTOPTS, - IPV6_RECVHOPLIMIT as IPV6_RECVHOPLIMIT, - IPV6_RECVHOPOPTS as IPV6_RECVHOPOPTS, - IPV6_RECVPATHMTU as IPV6_RECVPATHMTU, - IPV6_RECVPKTINFO as IPV6_RECVPKTINFO, - IPV6_RTHDRDSTOPTS as IPV6_RTHDRDSTOPTS, - ) + from _socket import ( + IPV6_DSTOPTS as IPV6_DSTOPTS, + IPV6_NEXTHOP as IPV6_NEXTHOP, + IPV6_PATHMTU as IPV6_PATHMTU, + IPV6_RECVDSTOPTS as IPV6_RECVDSTOPTS, + IPV6_RECVHOPLIMIT as IPV6_RECVHOPLIMIT, + IPV6_RECVHOPOPTS as IPV6_RECVHOPOPTS, + IPV6_RECVPATHMTU as IPV6_RECVPATHMTU, + IPV6_RECVPKTINFO as IPV6_RECVPKTINFO, + IPV6_RTHDRDSTOPTS as IPV6_RTHDRDSTOPTS, + ) - __all__ += [ - "IPV6_DSTOPTS", - "IPV6_NEXTHOP", - "IPV6_PATHMTU", - "IPV6_RECVDSTOPTS", - "IPV6_RECVHOPLIMIT", - "IPV6_RECVHOPOPTS", - "IPV6_RECVPATHMTU", - "IPV6_RECVPKTINFO", - "IPV6_RTHDRDSTOPTS", - ] + __all__ += [ + "IPV6_DSTOPTS", + "IPV6_NEXTHOP", + "IPV6_PATHMTU", + "IPV6_RECVDSTOPTS", + "IPV6_RECVHOPLIMIT", + "IPV6_RECVHOPOPTS", + "IPV6_RECVPATHMTU", + "IPV6_RECVPKTINFO", + "IPV6_RTHDRDSTOPTS", + ] - if sys.platform != "darwin": + if sys.platform != "darwin" or sys.version_info >= (3, 13): from _socket import SO_BINDTODEVICE as SO_BINDTODEVICE __all__ += ["SO_BINDTODEVICE"] if sys.platform != "darwin" and sys.platform != "linux": - if sys.platform != "win32" or sys.version_info >= (3, 9): - from _socket import BDADDR_ANY as BDADDR_ANY, BDADDR_LOCAL as BDADDR_LOCAL, BTPROTO_RFCOMM as BTPROTO_RFCOMM + from _socket import BDADDR_ANY as BDADDR_ANY, BDADDR_LOCAL as BDADDR_LOCAL, BTPROTO_RFCOMM as BTPROTO_RFCOMM - __all__ += ["BDADDR_ANY", "BDADDR_LOCAL", "BTPROTO_RFCOMM"] + __all__ += ["BDADDR_ANY", "BDADDR_LOCAL", "BTPROTO_RFCOMM"] if sys.platform == "darwin" and sys.version_info >= (3, 10): from _socket import TCP_KEEPALIVE as TCP_KEEPALIVE @@ -777,7 +775,7 @@ if sys.platform == "linux": __all__ += ["CAN_RAW_ERR_FILTER"] -if sys.platform == "linux" and sys.version_info >= (3, 9): +if sys.platform == "linux": from _socket import ( CAN_J1939 as CAN_J1939, CAN_RAW_JOIN_FILTERS as CAN_RAW_JOIN_FILTERS, @@ -959,14 +957,13 @@ if sys.version_info >= (3, 12): __all__ += ["PF_DIVERT", "AF_DIVERT"] -if sys.platform != "win32" and sys.version_info >= (3, 9): +if sys.platform != "win32": __all__ += ["send_fds", "recv_fds"] -if sys.platform != "win32" or sys.version_info >= (3, 9): - if sys.platform != "linux": - __all__ += ["AF_LINK"] - if sys.platform != "darwin" and sys.platform != "linux": - __all__ += ["AF_BLUETOOTH"] +if sys.platform != "linux": + __all__ += ["AF_LINK"] +if sys.platform != "darwin" and sys.platform != "linux": + __all__ += ["AF_BLUETOOTH"] if sys.platform == "win32" and sys.version_info >= (3, 12): __all__ += ["AF_HYPERV"] @@ -980,6 +977,7 @@ if sys.platform != "win32" and sys.platform != "linux": IPPROTO_HELLO as IPPROTO_HELLO, IPPROTO_IPCOMP as IPPROTO_IPCOMP, IPPROTO_XTP as IPPROTO_XTP, + IPV6_USE_MIN_MTU as IPV6_USE_MIN_MTU, LOCAL_PEERCRED as LOCAL_PEERCRED, SCM_CREDS as SCM_CREDS, ) @@ -992,6 +990,7 @@ if sys.platform != "win32" and sys.platform != "linux": "IPPROTO_HELLO", "IPPROTO_IPCOMP", "IPPROTO_XTP", + "IPV6_USE_MIN_MTU", "LOCAL_PEERCRED", "SCM_CREDS", "AI_DEFAULT", @@ -999,10 +998,6 @@ if sys.platform != "win32" and sys.platform != "linux": "AI_V4MAPPED_CFG", "MSG_EOF", ] - if sys.platform != "darwin" or sys.version_info >= (3, 9): - from _socket import IPV6_USE_MIN_MTU as IPV6_USE_MIN_MTU - - __all__ += ["IPV6_USE_MIN_MTU"] if sys.platform != "win32" and sys.platform != "darwin" and sys.platform != "linux": from _socket import ( @@ -1084,11 +1079,10 @@ class AddressFamily(IntEnum): AF_NETLINK = 16 AF_VSOCK = 40 AF_QIPCRTR = 42 - if sys.platform != "win32" or sys.version_info >= (3, 9): - if sys.platform != "linux": - AF_LINK = 33 - if sys.platform != "darwin" and sys.platform != "linux": - AF_BLUETOOTH = 32 + if sys.platform != "linux": + AF_LINK = 33 + if sys.platform != "darwin" and sys.platform != "linux": + AF_BLUETOOTH = 32 if sys.platform == "win32" and sys.version_info >= (3, 12): AF_HYPERV = 34 if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin" and sys.version_info >= (3, 12): @@ -1140,12 +1134,10 @@ if sys.platform == "linux": AF_VSOCK = AddressFamily.AF_VSOCK AF_QIPCRTR = AddressFamily.AF_QIPCRTR -if sys.platform != "win32" or sys.version_info >= (3, 9): - if sys.platform != "linux": - AF_LINK = AddressFamily.AF_LINK - if sys.platform != "darwin" and sys.platform != "linux": - AF_BLUETOOTH = AddressFamily.AF_BLUETOOTH - +if sys.platform != "linux": + AF_LINK = AddressFamily.AF_LINK +if sys.platform != "darwin" and sys.platform != "linux": + AF_BLUETOOTH = AddressFamily.AF_BLUETOOTH if sys.platform == "win32" and sys.version_info >= (3, 12): AF_HYPERV = AddressFamily.AF_HYPERV if sys.platform != "linux" and sys.platform != "win32" and sys.platform != "darwin" and sys.version_info >= (3, 12): @@ -1352,11 +1344,10 @@ class socket(_socket.socket): def fromfd(fd: SupportsIndex, family: AddressFamily | int, type: SocketKind | int, proto: int = 0) -> socket: ... if sys.platform != "win32": - if sys.version_info >= (3, 9): - def send_fds( - sock: socket, buffers: Iterable[ReadableBuffer], fds: Iterable[int], flags: Unused = 0, address: Unused = None - ) -> int: ... - def recv_fds(sock: socket, bufsize: int, maxfds: int, flags: int = 0) -> tuple[bytes, list[int], int, Any]: ... + def send_fds( + sock: socket, buffers: Iterable[ReadableBuffer], fds: Iterable[int], flags: Unused = 0, address: Unused = None + ) -> int: ... + def recv_fds(sock: socket, bufsize: int, maxfds: int, flags: int = 0) -> tuple[bytes, list[int], int, Any]: ... if sys.platform == "win32": def fromshare(info: bytes) -> socket: ... diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index 388e521c1ef5..9fbf5e8dfa84 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -28,7 +28,7 @@ from _ssl import ( from _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer from collections.abc import Callable, Iterable from typing import Any, Literal, NamedTuple, TypedDict, overload, type_check_only -from typing_extensions import Never, Self, TypeAlias +from typing_extensions import Never, Self, TypeAlias, deprecated if sys.version_info >= (3, 13): from _ssl import HAS_PSK as HAS_PSK @@ -369,7 +369,12 @@ class SSLSocket(socket.socket): def compression(self) -> str | None: ... def get_channel_binding(self, cb_type: str = "tls-unique") -> bytes | None: ... def selected_alpn_protocol(self) -> str | None: ... - def selected_npn_protocol(self) -> str | None: ... + if sys.version_info >= (3, 10): + @deprecated("Deprecated in 3.10. Use ALPN instead.") + def selected_npn_protocol(self) -> str | None: ... + else: + def selected_npn_protocol(self) -> str | None: ... + def accept(self) -> tuple[SSLSocket, socket._RetAddress]: ... def unwrap(self) -> socket.socket: ... def version(self) -> str | None: ... @@ -434,7 +439,12 @@ class SSLContext(_SSLContext): def set_default_verify_paths(self) -> None: ... def set_ciphers(self, cipherlist: str, /) -> None: ... def set_alpn_protocols(self, alpn_protocols: Iterable[str]) -> None: ... - def set_npn_protocols(self, npn_protocols: Iterable[str]) -> None: ... + if sys.version_info >= (3, 10): + @deprecated("Deprecated in 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: ... + 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: ... @@ -475,7 +485,12 @@ class SSLObject: @overload def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... def selected_alpn_protocol(self) -> str | None: ... - def selected_npn_protocol(self) -> str | None: ... + if sys.version_info >= (3, 10): + @deprecated("Deprecated in 3.10. Use ALPN instead.") + def selected_npn_protocol(self) -> str | None: ... + else: + 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: ... @@ -512,8 +527,6 @@ SSL_ERROR_ZERO_RETURN: SSLErrorNumber # undocumented def get_protocol_name(protocol_code: int) -> str: ... -if sys.version_info < (3, 9): - AF_INET: int PEM_FOOTER: str PEM_HEADER: str SOCK_STREAM: int diff --git a/mypy/typeshed/stdlib/statistics.pyi b/mypy/typeshed/stdlib/statistics.pyi index 9418bdea9d6d..6d7d3fbb4956 100644 --- a/mypy/typeshed/stdlib/statistics.pyi +++ b/mypy/typeshed/stdlib/statistics.pyi @@ -98,9 +98,7 @@ class NormalDist: def inv_cdf(self, p: float) -> float: ... def overlap(self, other: NormalDist) -> float: ... def quantiles(self, n: int = 4) -> list[float]: ... - if sys.version_info >= (3, 9): - def zscore(self, x: float) -> float: ... - + def zscore(self, x: float) -> float: ... def __eq__(x1, x2: object) -> bool: ... def __add__(x1, x2: float | NormalDist) -> NormalDist: ... def __sub__(x1, x2: float | NormalDist) -> NormalDist: ... diff --git a/mypy/typeshed/stdlib/string.pyi b/mypy/typeshed/stdlib/string.pyi index 35a76e9c8628..da752327d3f7 100644 --- a/mypy/typeshed/stdlib/string.pyi +++ b/mypy/typeshed/stdlib/string.pyi @@ -3,7 +3,7 @@ from _typeshed import StrOrLiteralStr from collections.abc import Iterable, Mapping, Sequence from re import Pattern, RegexFlag from typing import Any, ClassVar, overload -from typing_extensions import LiteralString, TypeAlias +from typing_extensions import LiteralString __all__ = [ "ascii_letters", @@ -32,14 +32,7 @@ whitespace: LiteralString def capwords(s: StrOrLiteralStr, sep: StrOrLiteralStr | None = None) -> StrOrLiteralStr: ... -if sys.version_info >= (3, 9): - _TemplateMetaclass: TypeAlias = type -else: - class _TemplateMetaclass(type): - pattern: ClassVar[str] - def __init__(cls, name: str, bases: tuple[type, ...], dct: dict[str, Any]) -> None: ... - -class Template(metaclass=_TemplateMetaclass): +class Template(metaclass=type): template: str delimiter: ClassVar[str] idpattern: ClassVar[str] diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index fef35b56945a..8b72e2ec7ae2 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -1,13 +1,10 @@ import sys from _typeshed import MaybeNone, ReadableBuffer, StrOrBytesPath from collections.abc import Callable, Collection, Iterable, Mapping, Sequence -from types import TracebackType +from types import GenericAlias, TracebackType from typing import IO, Any, AnyStr, Final, Generic, Literal, TypeVar, overload from typing_extensions import Self, TypeAlias -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = [ "Popen", "PIPE", @@ -87,8 +84,7 @@ class CompletedProcess(Generic[_T]): stderr: _T def __init__(self, args: _CMD, returncode: int, stdout: _T | None = None, stderr: _T | None = None) -> None: ... def check_returncode(self) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... if sys.version_info >= (3, 11): # 3.11 adds "process_group" argument @@ -500,7 +496,7 @@ elif sys.version_info >= (3, 10): pipesize: int = -1, ) -> CompletedProcess[Any]: ... -elif sys.version_info >= (3, 9): +else: # 3.9 adds arguments "user", "group", "extra_groups" and "umask" @overload def run( @@ -696,177 +692,6 @@ elif sys.version_info >= (3, 9): umask: 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[[], Any] | 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, - ) -> 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[[], Any] | 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, - ) -> 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[[], Any] | 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, - ) -> 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[[], Any] | 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, - ) -> 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[[], Any] | 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, - ) -> 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[[], Any] | 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, - ) -> CompletedProcess[Any]: ... - # Same args as Popen.__init__ if sys.version_info >= (3, 11): # 3.11 adds "process_group" argument @@ -931,8 +756,7 @@ elif sys.version_info >= (3, 10): pipesize: int = -1, ) -> int: ... -elif sys.version_info >= (3, 9): - # 3.9 adds arguments "user", "group", "extra_groups" and "umask" +else: def call( args: _CMD, bufsize: int = -1, @@ -961,31 +785,6 @@ elif sys.version_info >= (3, 9): umask: 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[[], Any] | 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, - ) -> int: ... - # Same args as Popen.__init__ if sys.version_info >= (3, 11): # 3.11 adds "process_group" argument @@ -1050,8 +849,7 @@ elif sys.version_info >= (3, 10): pipesize: int = -1, ) -> int: ... -elif sys.version_info >= (3, 9): - # 3.9 adds arguments "user", "group", "extra_groups" and "umask" +else: def check_call( args: _CMD, bufsize: int = -1, @@ -1080,31 +878,6 @@ elif sys.version_info >= (3, 9): umask: 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[[], Any] | 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 = ..., - *, - encoding: str | None = None, - text: bool | None = None, - ) -> int: ... - if sys.version_info >= (3, 11): # 3.11 adds "process_group" argument @overload @@ -1479,8 +1252,7 @@ elif sys.version_info >= (3, 10): pipesize: int = -1, ) -> Any: ... # morally: -> str | bytes -elif sys.version_info >= (3, 9): - # 3.9 adds arguments "user", "group", "extra_groups" and "umask" +else: @overload def check_output( args: _CMD, @@ -1657,159 +1429,6 @@ elif sys.version_info >= (3, 9): umask: int = -1, ) -> Any: ... # morally: -> str | bytes -else: - @overload - def check_output( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], Any] | 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 = ..., - encoding: str | None = None, - errors: str | None = None, - text: Literal[True], - ) -> str: ... - @overload - def check_output( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], Any] | 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 = ..., - encoding: str, - errors: str | None = None, - text: bool | 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[[], Any] | 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 = ..., - encoding: str | None = None, - errors: str, - text: bool | 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[[], Any] | 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 ones start - timeout: float | None = None, - input: _InputString | None = ..., - encoding: str | None = None, - errors: str | None = None, - text: bool | 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[[], Any] | 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] = ..., - *, - timeout: float | None = None, - input: _InputString | None = ..., - encoding: None = None, - errors: None = None, - text: Literal[False] | None = None, - ) -> bytes: ... - @overload - def check_output( - args: _CMD, - bufsize: int = -1, - executable: StrOrBytesPath | None = None, - stdin: _FILE = None, - stderr: _FILE = None, - preexec_fn: Callable[[], Any] | 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 = ..., - encoding: str | None = None, - errors: str | None = None, - text: bool | None = None, - ) -> Any: ... # morally: -> str | bytes - PIPE: Final[int] STDOUT: Final[int] DEVNULL: Final[int] @@ -2223,8 +1842,7 @@ class Popen(Generic[AnyStr]): umask: int = -1, pipesize: int = -1, ) -> None: ... - elif sys.version_info >= (3, 9): - # user, group, extra_groups, umask were added in 3.9 + else: @overload def __init__( self: Popen[str], @@ -2400,163 +2018,11 @@ class Popen(Generic[AnyStr]): extra_groups: Iterable[str | int] | None = None, umask: 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[[], Any] | 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, - ) -> 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[[], Any] | 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: ... - @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[[], Any] | 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, - ) -> 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[[], Any] | 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, - ) -> 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[[], Any] | 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, - ) -> 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[[], Any] | 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, - ) -> None: ... def poll(self) -> int | None: ... def wait(self, timeout: float | None = None) -> int: ... # morally the members of the returned tuple should be optional - # TODO this should allow ReadableBuffer for Popen[bytes], but adding + # TODO: this should allow ReadableBuffer for Popen[bytes], but adding # overloads for that runs into a mypy bug (python/mypy#14070). def communicate(self, input: AnyStr | None = None, timeout: float | None = None) -> tuple[AnyStr, AnyStr]: ... def send_signal(self, sig: int) -> None: ... @@ -2567,8 +2033,7 @@ class Popen(Generic[AnyStr]): self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... def __del__(self) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... # The result really is always a str. if sys.version_info >= (3, 11): diff --git a/mypy/typeshed/stdlib/sunau.pyi b/mypy/typeshed/stdlib/sunau.pyi index 9b051e82b64b..d81645cb5687 100644 --- a/mypy/typeshed/stdlib/sunau.pyi +++ b/mypy/typeshed/stdlib/sunau.pyi @@ -1,4 +1,3 @@ -import sys from _typeshed import Unused from typing import IO, Any, Literal, NamedTuple, NoReturn, overload from typing_extensions import Self, TypeAlias @@ -81,6 +80,3 @@ def open(f: _File, mode: Literal["r", "rb"]) -> Au_read: ... def open(f: _File, mode: Literal["w", "wb"]) -> Au_write: ... @overload def open(f: _File, mode: str | None = None) -> Any: ... - -if sys.version_info < (3, 9): - openfp = open diff --git a/mypy/typeshed/stdlib/symtable.pyi b/mypy/typeshed/stdlib/symtable.pyi index ee0a1eb2f1cb..d5f2be04b600 100644 --- a/mypy/typeshed/stdlib/symtable.pyi +++ b/mypy/typeshed/stdlib/symtable.pyi @@ -36,9 +36,6 @@ class SymbolTable: def is_optimized(self) -> bool: ... def is_nested(self) -> bool: ... def has_children(self) -> bool: ... - if sys.version_info < (3, 9): - def has_exec(self) -> bool: ... - def get_identifiers(self) -> dict_keys[str, int]: ... def lookup(self, name: str) -> Symbol: ... def get_symbols(self) -> list[Symbol]: ... @@ -52,9 +49,8 @@ class Function(SymbolTable): def get_nonlocals(self) -> tuple[str, ...]: ... class Class(SymbolTable): - if sys.version_info < (3, 16): - @deprecated("deprecated in Python 3.14, will be removed in Python 3.16") - def get_methods(self) -> tuple[str, ...]: ... + @deprecated("deprecated in Python 3.14, will be removed in Python 3.16") + def get_methods(self) -> tuple[str, ...]: ... class Symbol: def __init__( diff --git a/mypy/typeshed/stdlib/sys/__init__.pyi b/mypy/typeshed/stdlib/sys/__init__.pyi index 4aa1699e8b42..2d894674c4af 100644 --- a/mypy/typeshed/stdlib/sys/__init__.pyi +++ b/mypy/typeshed/stdlib/sys/__init__.pyi @@ -46,8 +46,7 @@ path: list[str] path_hooks: list[Callable[[str], PathEntryFinderProtocol]] path_importer_cache: dict[str, PathEntryFinderProtocol | None] platform: LiteralString -if sys.version_info >= (3, 9): - platlibdir: str +platlibdir: str prefix: str pycache_prefix: str | None ps1: object @@ -97,7 +96,7 @@ flags: _flags # This can be re-visited when typeshed drops support for 3.10, # at which point all supported versions will include int_max_str_digits # in all patch versions. -# 3.8 and 3.9 are 15 or 16-tuple +# 3.9 is 15 or 16-tuple # 3.10 is 16 or 17-tuple # 3.11+ is an 18-tuple. @final @@ -185,7 +184,7 @@ class _flags(_UninstantiableStructseq, tuple[int, ...]): # Whether or not this exists on lower versions of Python # may depend on which patch release you're using # (it was backported to all Python versions on 3.8+ as a security fix) - # Added in: 3.8.14, 3.9.14, 3.10.7 + # Added in: 3.9.14, 3.10.7 # and present in all versions of 3.11 and later. @property def int_max_str_digits(self) -> int: ... @@ -397,6 +396,7 @@ def intern(string: str, /) -> str: ... if sys.version_info >= (3, 13): def _is_gil_enabled() -> bool: ... def _clear_internal_caches() -> None: ... + def _is_interned(string: str, /) -> bool: ... def is_finalizing() -> bool: ... def breakpointhook(*args: Any, **kwargs: Any) -> Any: ... @@ -410,14 +410,6 @@ def setrecursionlimit(limit: int, /) -> None: ... def setswitchinterval(interval: float, /) -> None: ... def gettotalrefcount() -> int: ... # Debug builds only -if sys.version_info < (3, 9): - def getcheckinterval() -> int: ... # deprecated - def setcheckinterval(n: int, /) -> None: ... # deprecated - -if sys.version_info < (3, 9): - # An 11-tuple or None - def callstats() -> tuple[int, int, int, int, int, int, int, int, int, int, int] | None: ... - # Doesn't exist at runtime, but exported in the stubs so pytest etc. can annotate their code more easily. @type_check_only class UnraisableHookArgs(Protocol): @@ -456,7 +448,7 @@ if sys.platform == "win32": def get_coroutine_origin_tracking_depth() -> int: ... def set_coroutine_origin_tracking_depth(depth: int) -> None: ... -# The following two functions were added in 3.11.0, 3.10.7, 3.9.14, and 3.8.14, +# The following two functions were added in 3.11.0, 3.10.7, and 3.9.14, # as part of the response to CVE-2020-10735 def set_int_max_str_digits(maxdigits: int) -> None: ... def get_int_max_str_digits() -> int: ... diff --git a/mypy/typeshed/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi index 6a00e070aee9..cd31b101c886 100644 --- a/mypy/typeshed/stdlib/tarfile.pyi +++ b/mypy/typeshed/stdlib/tarfile.pyi @@ -304,6 +304,25 @@ class TarFile: ) -> Self: ... @overload @classmethod + def open( + cls, + name: StrOrBytesPath | ReadableBuffer | None, + mode: Literal["r|*", "r|", "r|gz", "r|bz2", "r|xz"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: int | None = ..., + errorlevel: int | None = ..., + ) -> Self: ... + @overload + @classmethod def open( cls, name: StrOrBytesPath | ReadableBuffer | None = None, @@ -323,6 +342,25 @@ class TarFile: ) -> Self: ... @overload @classmethod + def open( + cls, + name: StrOrBytesPath | WriteableBuffer | None, + mode: Literal["w|", "w|xz"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: int | None = ..., + errorlevel: int | None = ..., + ) -> Self: ... + @overload + @classmethod def open( cls, name: StrOrBytesPath | WriteableBuffer | None = None, @@ -342,6 +380,26 @@ class TarFile: ) -> Self: ... @overload @classmethod + def open( + cls, + name: StrOrBytesPath | WriteableBuffer | None, + mode: Literal["w|gz", "w|bz2"], + fileobj: _Fileobj | None = None, + bufsize: int = 10240, + *, + format: int | None = ..., + tarinfo: type[TarInfo] | None = ..., + dereference: bool | None = ..., + ignore_zeros: bool | None = ..., + encoding: str | None = ..., + errors: str = ..., + pax_headers: Mapping[str, str] | None = ..., + debug: int | None = ..., + errorlevel: int | None = ..., + compresslevel: int = 9, + ) -> Self: ... + @overload + @classmethod def open( cls, name: StrOrBytesPath | WriteableBuffer | None = None, @@ -520,11 +578,7 @@ class TarFile: open = TarFile.open -if sys.version_info >= (3, 9): - def is_tarfile(name: StrOrBytesPath | IO[bytes]) -> bool: ... - -else: - def is_tarfile(name: StrOrBytesPath) -> bool: ... +def is_tarfile(name: StrOrBytesPath | IO[bytes]) -> bool: ... class TarError(Exception): ... class ReadError(TarError): ... diff --git a/mypy/typeshed/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi index 0c19d56fc7a6..c4861f7c6f39 100644 --- a/mypy/typeshed/stdlib/tempfile.pyi +++ b/mypy/typeshed/stdlib/tempfile.pyi @@ -13,13 +13,10 @@ from _typeshed import ( WriteableBuffer, ) from collections.abc import Iterable, Iterator -from types import TracebackType +from types import GenericAlias, TracebackType from typing import IO, Any, AnyStr, Generic, Literal, overload from typing_extensions import Self -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = [ "NamedTemporaryFile", "TemporaryFile", @@ -399,8 +396,7 @@ class SpooledTemporaryFile(IO[AnyStr], _SpooledTemporaryFileBase): def seekable(self) -> bool: ... def writable(self) -> bool: ... def __next__(self) -> AnyStr: ... # type: ignore[override] - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class TemporaryDirectory(Generic[AnyStr]): name: AnyStr @@ -458,8 +454,7 @@ class TemporaryDirectory(Generic[AnyStr]): def cleanup(self) -> None: ... def __enter__(self) -> AnyStr: ... def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... # The overloads overlap, but they should still work fine. @overload diff --git a/mypy/typeshed/stdlib/threading.pyi b/mypy/typeshed/stdlib/threading.pyi index efeea69d0234..e3965fab0e80 100644 --- a/mypy/typeshed/stdlib/threading.pyi +++ b/mypy/typeshed/stdlib/threading.pyi @@ -89,8 +89,6 @@ class Thread: @property def native_id(self) -> int | None: ... # only available on some platforms def is_alive(self) -> bool: ... - if sys.version_info < (3, 9): - def isAlive(self) -> bool: ... # the following methods are all deprecated def getName(self) -> str: ... def setName(self, name: str) -> None: ... @@ -134,10 +132,7 @@ class Semaphore: def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... def acquire(self, blocking: bool = True, timeout: float | None = None) -> bool: ... def __enter__(self, blocking: bool = True, timeout: float | None = None) -> bool: ... - if sys.version_info >= (3, 9): - def release(self, n: int = 1) -> None: ... - else: - def release(self) -> None: ... + def release(self, n: int = 1) -> None: ... class BoundedSemaphore(Semaphore): ... diff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi index 71cdc4d78fdc..6d2538ea7e3e 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -31,7 +31,7 @@ if sys.platform == "darwin": CLOCK_UPTIME_RAW_APPROX: int CLOCK_MONOTONIC_RAW_APPROX: int -if sys.version_info >= (3, 9) and sys.platform == "linux": +if sys.platform == "linux": CLOCK_TAI: int # Constructor takes an iterable of any type, of length between 9 and 11 elements. diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 73c1e0400fe8..291e2fc5108f 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -13,140 +13,139 @@ if sys.version_info >= (3, 11): else: from enum import Enum -if sys.version_info >= (3, 9): - __all__ = [ - "TclError", - "NO", - "FALSE", - "OFF", - "YES", - "TRUE", - "ON", - "N", - "S", - "W", - "E", - "NW", - "SW", - "NE", - "SE", - "NS", - "EW", - "NSEW", - "CENTER", - "NONE", - "X", - "Y", - "BOTH", - "LEFT", - "TOP", - "RIGHT", - "BOTTOM", - "RAISED", - "SUNKEN", - "FLAT", - "RIDGE", - "GROOVE", - "SOLID", - "HORIZONTAL", - "VERTICAL", - "NUMERIC", - "CHAR", - "WORD", - "BASELINE", - "INSIDE", - "OUTSIDE", - "SEL", - "SEL_FIRST", - "SEL_LAST", - "END", - "INSERT", - "CURRENT", - "ANCHOR", - "ALL", - "NORMAL", - "DISABLED", - "ACTIVE", - "HIDDEN", - "CASCADE", - "CHECKBUTTON", - "COMMAND", - "RADIOBUTTON", - "SEPARATOR", - "SINGLE", - "BROWSE", - "MULTIPLE", - "EXTENDED", - "DOTBOX", - "UNDERLINE", - "PIESLICE", - "CHORD", - "ARC", - "FIRST", - "LAST", - "BUTT", - "PROJECTING", - "ROUND", - "BEVEL", - "MITER", - "MOVETO", - "SCROLL", - "UNITS", - "PAGES", - "TkVersion", - "TclVersion", - "READABLE", - "WRITABLE", - "EXCEPTION", - "EventType", - "Event", - "NoDefaultRoot", - "Variable", - "StringVar", - "IntVar", - "DoubleVar", - "BooleanVar", - "mainloop", - "getint", - "getdouble", - "getboolean", - "Misc", - "CallWrapper", - "XView", - "YView", - "Wm", - "Tk", - "Tcl", - "Pack", - "Place", - "Grid", - "BaseWidget", - "Widget", - "Toplevel", - "Button", - "Canvas", - "Checkbutton", - "Entry", - "Frame", - "Label", - "Listbox", - "Menu", - "Menubutton", - "Message", - "Radiobutton", - "Scale", - "Scrollbar", - "Text", - "OptionMenu", - "Image", - "PhotoImage", - "BitmapImage", - "image_names", - "image_types", - "Spinbox", - "LabelFrame", - "PanedWindow", - ] +__all__ = [ + "TclError", + "NO", + "FALSE", + "OFF", + "YES", + "TRUE", + "ON", + "N", + "S", + "W", + "E", + "NW", + "SW", + "NE", + "SE", + "NS", + "EW", + "NSEW", + "CENTER", + "NONE", + "X", + "Y", + "BOTH", + "LEFT", + "TOP", + "RIGHT", + "BOTTOM", + "RAISED", + "SUNKEN", + "FLAT", + "RIDGE", + "GROOVE", + "SOLID", + "HORIZONTAL", + "VERTICAL", + "NUMERIC", + "CHAR", + "WORD", + "BASELINE", + "INSIDE", + "OUTSIDE", + "SEL", + "SEL_FIRST", + "SEL_LAST", + "END", + "INSERT", + "CURRENT", + "ANCHOR", + "ALL", + "NORMAL", + "DISABLED", + "ACTIVE", + "HIDDEN", + "CASCADE", + "CHECKBUTTON", + "COMMAND", + "RADIOBUTTON", + "SEPARATOR", + "SINGLE", + "BROWSE", + "MULTIPLE", + "EXTENDED", + "DOTBOX", + "UNDERLINE", + "PIESLICE", + "CHORD", + "ARC", + "FIRST", + "LAST", + "BUTT", + "PROJECTING", + "ROUND", + "BEVEL", + "MITER", + "MOVETO", + "SCROLL", + "UNITS", + "PAGES", + "TkVersion", + "TclVersion", + "READABLE", + "WRITABLE", + "EXCEPTION", + "EventType", + "Event", + "NoDefaultRoot", + "Variable", + "StringVar", + "IntVar", + "DoubleVar", + "BooleanVar", + "mainloop", + "getint", + "getdouble", + "getboolean", + "Misc", + "CallWrapper", + "XView", + "YView", + "Wm", + "Tk", + "Tcl", + "Pack", + "Place", + "Grid", + "BaseWidget", + "Widget", + "Toplevel", + "Button", + "Canvas", + "Checkbutton", + "Entry", + "Frame", + "Label", + "Listbox", + "Menu", + "Menubutton", + "Message", + "Radiobutton", + "Scale", + "Scrollbar", + "Text", + "OptionMenu", + "Image", + "PhotoImage", + "BitmapImage", + "image_names", + "image_types", + "Spinbox", + "LabelFrame", + "PanedWindow", +] # Using anything from tkinter.font in this file means that 'import tkinter' # seems to also load tkinter.font. That's not how it actually works, but diff --git a/mypy/typeshed/stdlib/tkinter/colorchooser.pyi b/mypy/typeshed/stdlib/tkinter/colorchooser.pyi index 09bc8cbb4f1e..d0d6de842656 100644 --- a/mypy/typeshed/stdlib/tkinter/colorchooser.pyi +++ b/mypy/typeshed/stdlib/tkinter/colorchooser.pyi @@ -1,20 +1,12 @@ -import sys from tkinter import Misc from tkinter.commondialog import Dialog from typing import ClassVar -if sys.version_info >= (3, 9): - __all__ = ["Chooser", "askcolor"] +__all__ = ["Chooser", "askcolor"] class Chooser(Dialog): command: ClassVar[str] -if sys.version_info >= (3, 9): - def askcolor( - color: str | bytes | None = None, *, initialcolor: str = ..., parent: Misc = ..., title: str = ... - ) -> tuple[None, None] | tuple[tuple[int, int, int], str]: ... - -else: - def askcolor( - color: str | bytes | None = None, *, initialcolor: str = ..., parent: Misc = ..., title: str = ... - ) -> tuple[None, None] | tuple[tuple[float, float, float], str]: ... +def askcolor( + color: str | bytes | None = None, *, initialcolor: str = ..., parent: Misc = ..., title: str = ... +) -> tuple[None, None] | tuple[tuple[int, int, int], str]: ... diff --git a/mypy/typeshed/stdlib/tkinter/commondialog.pyi b/mypy/typeshed/stdlib/tkinter/commondialog.pyi index d06c08df5b76..201ca13ddd9c 100644 --- a/mypy/typeshed/stdlib/tkinter/commondialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/commondialog.pyi @@ -1,10 +1,8 @@ -import sys from _typeshed import Incomplete from collections.abc import Mapping from typing import ClassVar -if sys.version_info >= (3, 9): - __all__ = ["Dialog"] +__all__ = ["Dialog"] class Dialog: command: ClassVar[str | None] diff --git a/mypy/typeshed/stdlib/tkinter/dialog.pyi b/mypy/typeshed/stdlib/tkinter/dialog.pyi index b7d74c0fa71e..3dc059940964 100644 --- a/mypy/typeshed/stdlib/tkinter/dialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/dialog.pyi @@ -1,11 +1,9 @@ -import sys from _typeshed import Incomplete from collections.abc import Mapping from tkinter import Widget from typing import Any, Final -if sys.version_info >= (3, 9): - __all__ = ["Dialog"] +__all__ = ["Dialog"] DIALOG_ICON: Final = "questhead" diff --git a/mypy/typeshed/stdlib/tkinter/dnd.pyi b/mypy/typeshed/stdlib/tkinter/dnd.pyi index d806be74068e..fe2961701c61 100644 --- a/mypy/typeshed/stdlib/tkinter/dnd.pyi +++ b/mypy/typeshed/stdlib/tkinter/dnd.pyi @@ -1,9 +1,7 @@ -import sys from tkinter import Event, Misc, Tk, Widget from typing import ClassVar, Protocol -if sys.version_info >= (3, 9): - __all__ = ["dnd_start", "DndHandler"] +__all__ = ["dnd_start", "DndHandler"] class _DndSource(Protocol): def dnd_end(self, target: Widget | None, event: Event[Misc] | None, /) -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/filedialog.pyi b/mypy/typeshed/stdlib/tkinter/filedialog.pyi index 03f89cfbe3e6..cafcf61e8635 100644 --- a/mypy/typeshed/stdlib/tkinter/filedialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/filedialog.pyi @@ -1,25 +1,23 @@ -import sys from _typeshed import Incomplete, StrOrBytesPath from collections.abc import Iterable from tkinter import Button, Entry, Frame, Listbox, Misc, Scrollbar, StringVar, Toplevel, commondialog from typing import IO, ClassVar, Literal -if sys.version_info >= (3, 9): - __all__ = [ - "FileDialog", - "LoadFileDialog", - "SaveFileDialog", - "Open", - "SaveAs", - "Directory", - "askopenfilename", - "asksaveasfilename", - "askopenfilenames", - "askopenfile", - "askopenfiles", - "asksaveasfile", - "askdirectory", - ] +__all__ = [ + "FileDialog", + "LoadFileDialog", + "SaveFileDialog", + "Open", + "SaveAs", + "Directory", + "askopenfilename", + "asksaveasfilename", + "askopenfilenames", + "askopenfile", + "askopenfiles", + "asksaveasfile", + "askdirectory", +] dialogstates: dict[Incomplete, tuple[Incomplete, Incomplete]] diff --git a/mypy/typeshed/stdlib/tkinter/font.pyi b/mypy/typeshed/stdlib/tkinter/font.pyi index 3b73f982c4ca..cab97490be34 100644 --- a/mypy/typeshed/stdlib/tkinter/font.pyi +++ b/mypy/typeshed/stdlib/tkinter/font.pyi @@ -5,8 +5,7 @@ import tkinter from typing import Any, ClassVar, Final, Literal, TypedDict, overload from typing_extensions import TypeAlias, Unpack -if sys.version_info >= (3, 9): - __all__ = ["NORMAL", "ROMAN", "BOLD", "ITALIC", "nametofont", "Font", "families", "names"] +__all__ = ["NORMAL", "ROMAN", "BOLD", "ITALIC", "nametofont", "Font", "families", "names"] NORMAL: Final = "normal" ROMAN: Final = "roman" diff --git a/mypy/typeshed/stdlib/tkinter/messagebox.pyi b/mypy/typeshed/stdlib/tkinter/messagebox.pyi index 5cdfe512f9b7..902fab62ac05 100644 --- a/mypy/typeshed/stdlib/tkinter/messagebox.pyi +++ b/mypy/typeshed/stdlib/tkinter/messagebox.pyi @@ -1,18 +1,7 @@ -import sys from tkinter.commondialog import Dialog from typing import ClassVar, Final -if sys.version_info >= (3, 9): - __all__ = [ - "showinfo", - "showwarning", - "showerror", - "askquestion", - "askokcancel", - "askyesno", - "askyesnocancel", - "askretrycancel", - ] +__all__ = ["showinfo", "showwarning", "showerror", "askquestion", "askokcancel", "askyesno", "askyesnocancel", "askretrycancel"] ERROR: Final = "error" INFO: Final = "info" diff --git a/mypy/typeshed/stdlib/tokenize.pyi b/mypy/typeshed/stdlib/tokenize.pyi index a1c4b412da83..86e87704eb02 100644 --- a/mypy/typeshed/stdlib/tokenize.pyi +++ b/mypy/typeshed/stdlib/tokenize.pyi @@ -125,7 +125,7 @@ class Untokenizer: prev_col: int encoding: str | None def add_whitespace(self, start: _Position) -> None: ... - if sys.version_info >= (3, 13): + if sys.version_info >= (3, 12): def add_backslash_continuation(self, start: _Position) -> None: ... def untokenize(self, iterable: Iterable[_Token]) -> str: ... diff --git a/mypy/typeshed/stdlib/trace.pyi b/mypy/typeshed/stdlib/trace.pyi index 04390f119195..7e7cc1e9ac54 100644 --- a/mypy/typeshed/stdlib/trace.pyi +++ b/mypy/typeshed/stdlib/trace.pyi @@ -75,11 +75,7 @@ class Trace: def runctx( self, cmd: str | types.CodeType, globals: Mapping[str, Any] | None = None, locals: Mapping[str, Any] | None = None ) -> None: ... - if sys.version_info >= (3, 9): - def runfunc(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ... - else: - def runfunc(self, func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... - + def runfunc(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ... def file_module_function_of(self, frame: types.FrameType) -> _FileModuleFunction: ... def globaltrace_trackcallers(self, frame: types.FrameType, why: str, arg: Any) -> None: ... def globaltrace_countfuncs(self, frame: types.FrameType, why: str, arg: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/tracemalloc.pyi b/mypy/typeshed/stdlib/tracemalloc.pyi index e721e414138b..05d98ae127d8 100644 --- a/mypy/typeshed/stdlib/tracemalloc.pyi +++ b/mypy/typeshed/stdlib/tracemalloc.pyi @@ -69,10 +69,7 @@ class Frame: def __ge__(self, other: Frame, NotImplemented: Any = ...) -> bool: ... def __le__(self, other: Frame, NotImplemented: Any = ...) -> bool: ... -if sys.version_info >= (3, 9): - _TraceTuple: TypeAlias = tuple[int, int, Sequence[_FrameTuple], int | None] | tuple[int, int, Sequence[_FrameTuple]] -else: - _TraceTuple: TypeAlias = tuple[int, int, Sequence[_FrameTuple]] +_TraceTuple: TypeAlias = tuple[int, int, Sequence[_FrameTuple], int | None] | tuple[int, int, Sequence[_FrameTuple]] class Trace: @property @@ -86,13 +83,9 @@ class Trace: def __hash__(self) -> int: ... class Traceback(Sequence[Frame]): - if sys.version_info >= (3, 9): - @property - def total_nframe(self) -> int | None: ... - def __init__(self, frames: Sequence[_FrameTuple], total_nframe: int | None = None) -> None: ... - else: - def __init__(self, frames: Sequence[_FrameTuple]) -> None: ... - + @property + 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: ... diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index 542979d4afc5..fe443be27121 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -11,13 +11,12 @@ from collections.abc import ( Iterable, Iterator, KeysView, + Mapping, MutableSequence, ValuesView, ) from importlib.machinery import ModuleSpec - -# pytype crashes if types.MappingProxyType inherits from collections.abc.Mapping instead of typing.Mapping -from typing import Any, ClassVar, Literal, Mapping, TypeVar, final, overload # noqa: Y022 +from typing import Any, ClassVar, Literal, TypeVar, final, overload from typing_extensions import ParamSpec, Self, TypeAliasType, TypeVarTuple, deprecated __all__ = [ @@ -47,11 +46,9 @@ __all__ = [ "WrapperDescriptorType", "resolve_bases", "CellType", + "GenericAlias", ] -if sys.version_info >= (3, 9): - __all__ += ["GenericAlias"] - if sys.version_info >= (3, 10): __all__ += ["EllipsisType", "NoneType", "NotImplementedType", "UnionType"] @@ -320,11 +317,10 @@ class MappingProxyType(Mapping[_KT, _VT_co]): def get(self, key: _KT, /) -> _VT_co | None: ... @overload def get(self, key: _KT, default: _VT_co | _T2, /) -> _VT_co | _T2: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... - def __reversed__(self) -> Iterator[_KT]: ... - def __or__(self, value: Mapping[_T1, _T2], /) -> dict[_KT | _T1, _VT_co | _T2]: ... - def __ror__(self, value: Mapping[_T1, _T2], /) -> dict[_KT | _T1, _VT_co | _T2]: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __reversed__(self) -> Iterator[_KT]: ... + def __or__(self, value: Mapping[_T1, _T2], /) -> dict[_KT | _T1, _VT_co | _T2]: ... + def __ror__(self, value: Mapping[_T1, _T2], /) -> dict[_KT | _T1, _VT_co | _T2]: ... class SimpleNamespace: __hash__: ClassVar[None] # type: ignore[assignment] @@ -425,8 +421,7 @@ class AsyncGeneratorType(AsyncGenerator[_YieldT_co, _SendT_contra]): @overload async def athrow(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ... def aclose(self) -> Coroutine[Any, Any, None]: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... @final class CoroutineType(Coroutine[_YieldT_co, _SendT_contra, _ReturnT_co]): @@ -647,30 +642,29 @@ def coroutine(func: Callable[_P, Generator[Any, Any, _R]]) -> Callable[_P, Await @overload def coroutine(func: _Fn) -> _Fn: ... -if sys.version_info >= (3, 9): - class GenericAlias: - @property - def __origin__(self) -> type | TypeAliasType: ... +class GenericAlias: + @property + def __origin__(self) -> type | TypeAliasType: ... + @property + def __args__(self) -> tuple[Any, ...]: ... + @property + def __parameters__(self) -> tuple[Any, ...]: ... + def __new__(cls, origin: type, args: Any, /) -> Self: ... + def __getitem__(self, typeargs: Any, /) -> GenericAlias: ... + def __eq__(self, value: object, /) -> bool: ... + def __hash__(self) -> int: ... + def __mro_entries__(self, bases: Iterable[object], /) -> tuple[type, ...]: ... + if sys.version_info >= (3, 11): @property - def __args__(self) -> tuple[Any, ...]: ... + def __unpacked__(self) -> bool: ... @property - def __parameters__(self) -> tuple[Any, ...]: ... - def __new__(cls, origin: type, args: Any, /) -> Self: ... - def __getitem__(self, typeargs: Any, /) -> GenericAlias: ... - def __eq__(self, value: object, /) -> bool: ... - def __hash__(self) -> int: ... - def __mro_entries__(self, bases: Iterable[object], /) -> tuple[type, ...]: ... - if sys.version_info >= (3, 11): - @property - 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: ... - - # GenericAlias delegates attr access to `__origin__` - def __getattr__(self, name: str) -> Any: ... + 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: ... + + # GenericAlias delegates attr access to `__origin__` + def __getattr__(self, name: str) -> Any: ... if sys.version_info >= (3, 10): @final diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index bc8f342ef46b..df753cfd9bca 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -13,6 +13,7 @@ from types import ( BuiltinFunctionType, CodeType, FunctionType, + GenericAlias, MethodDescriptorType, MethodType, MethodWrapperType, @@ -22,13 +23,12 @@ from types import ( ) from typing_extensions import Never as _Never, ParamSpec as _ParamSpec, deprecated -if sys.version_info >= (3, 9): - from types import GenericAlias if sys.version_info >= (3, 10): from types import UnionType __all__ = [ "AbstractSet", + "Annotated", "Any", "AnyStr", "AsyncContextManager", @@ -36,6 +36,7 @@ __all__ = [ "AsyncIterable", "AsyncIterator", "Awaitable", + "BinaryIO", "ByteString", "Callable", "ChainMap", @@ -49,10 +50,12 @@ __all__ = [ "Deque", "Dict", "Final", + "ForwardRef", "FrozenSet", "Generator", "Generic", "Hashable", + "IO", "ItemsView", "Iterable", "Iterator", @@ -61,12 +64,16 @@ __all__ = [ "Literal", "Mapping", "MappingView", + "Match", "MutableMapping", "MutableSequence", "MutableSet", "NamedTuple", "NewType", + "NoReturn", "Optional", + "OrderedDict", + "Pattern", "Protocol", "Reversible", "Sequence", @@ -80,6 +87,7 @@ __all__ = [ "SupportsInt", "SupportsRound", "Text", + "TextIO", "Tuple", "Type", "TypeVar", @@ -96,14 +104,8 @@ __all__ = [ "no_type_check_decorator", "overload", "runtime_checkable", - "ForwardRef", - "NoReturn", - "OrderedDict", ] -if sys.version_info >= (3, 9): - __all__ += ["Annotated", "BinaryIO", "IO", "Match", "Pattern", "TextIO"] - if sys.version_info >= (3, 10): __all__ += ["Concatenate", "ParamSpec", "ParamSpecArgs", "ParamSpecKwargs", "TypeAlias", "TypeGuard", "is_typeddict"] @@ -203,7 +205,6 @@ class _SpecialForm(_Final): Union: _SpecialForm Generic: _SpecialForm -# Protocol is only present in 3.8 and later, but mypy needs it unconditionally Protocol: _SpecialForm Callable: _SpecialForm Type: _SpecialForm @@ -386,8 +387,7 @@ ChainMap = _Alias() OrderedDict = _Alias() -if sys.version_info >= (3, 9): - Annotated: _SpecialForm +Annotated: _SpecialForm # Predefined type variables. AnyStr = TypeVar("AnyStr", str, bytes) # noqa: Y001 @@ -858,19 +858,12 @@ _get_type_hints_obj_allowed_types: typing_extensions.TypeAlias = ( # noqa: Y042 | MethodDescriptorType ) -if sys.version_info >= (3, 9): - def get_type_hints( - obj: _get_type_hints_obj_allowed_types, - globalns: dict[str, Any] | None = None, - localns: Mapping[str, Any] | None = None, - include_extras: bool = False, - ) -> dict[str, Any]: ... - -else: - def get_type_hints( - obj: _get_type_hints_obj_allowed_types, globalns: dict[str, Any] | None = None, localns: Mapping[str, Any] | None = None - ) -> dict[str, Any]: ... - +def get_type_hints( + obj: _get_type_hints_obj_allowed_types, + globalns: dict[str, Any] | None = None, + localns: Mapping[str, Any] | None = None, + include_extras: bool = False, +) -> dict[str, Any]: ... def get_args(tp: Any) -> tuple[Any, ...]: ... if sys.version_info >= (3, 10): @@ -879,15 +872,10 @@ if sys.version_info >= (3, 10): @overload def get_origin(tp: UnionType) -> type[UnionType]: ... -if sys.version_info >= (3, 9): - @overload - def get_origin(tp: GenericAlias) -> type: ... - @overload - def get_origin(tp: Any) -> Any | None: ... - -else: - def get_origin(tp: Any) -> Any | None: ... - +@overload +def get_origin(tp: GenericAlias) -> type: ... +@overload +def get_origin(tp: Any) -> Any | None: ... @overload def cast(typ: type[_T], val: Any) -> _T: ... @overload @@ -914,8 +902,6 @@ if sys.version_info >= (3, 11): # Type constructors class NamedTuple(tuple[Any, ...]): - if sys.version_info < (3, 9): - _field_types: ClassVar[dict[str, type]] _field_defaults: ClassVar[dict[str, Any]] _fields: ClassVar[tuple[str, ...]] # __orig_bases__ sometimes exists on <3.12, but not consistently @@ -942,9 +928,8 @@ class NamedTuple(tuple[Any, ...]): @type_check_only class _TypedDict(Mapping[str, object], metaclass=ABCMeta): __total__: ClassVar[bool] - if sys.version_info >= (3, 9): - __required_keys__: ClassVar[frozenset[str]] - __optional_keys__: ClassVar[frozenset[str]] + __required_keys__: ClassVar[frozenset[str]] + __optional_keys__: ClassVar[frozenset[str]] # __orig_bases__ sometimes exists on <3.12, but not consistently, # so we only add it to the stub on 3.12+ if sys.version_info >= (3, 12): @@ -964,17 +949,16 @@ 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]: ... - if sys.version_info >= (3, 9): - @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] + @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] @final class ForwardRef(_Final): @@ -985,11 +969,8 @@ class ForwardRef(_Final): __forward_is_argument__: bool __forward_is_class__: bool __forward_module__: Any | None - if sys.version_info >= (3, 9): - # The module and is_class arguments were added in later Python 3.9 versions. - def __init__(self, arg: str, is_argument: bool = True, module: Any | None = None, *, is_class: bool = False) -> None: ... - else: - def __init__(self, arg: str, is_argument: bool = True) -> None: ... + + def __init__(self, arg: str, is_argument: bool = True, module: Any | None = None, *, is_class: bool = False) -> None: ... if sys.version_info >= (3, 13): @overload @@ -1019,12 +1000,10 @@ class ForwardRef(_Final): *, recursive_guard: frozenset[str], ) -> Any | None: ... - elif sys.version_info >= (3, 9): + else: def _evaluate( self, globalns: dict[str, Any] | None, localns: Mapping[str, Any] | None, recursive_guard: frozenset[str] ) -> Any | None: ... - else: - def _evaluate(self, globalns: dict[str, Any] | None, localns: Mapping[str, Any] | None) -> Any | None: ... def __eq__(self, other: object) -> bool: ... def __hash__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index f3b7b8ddf5b1..bad5fae880c0 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -1,62 +1,63 @@ import abc import enum import sys -import typing from _collections_abc import dict_items, dict_keys, dict_values from _typeshed import IdentityFunction, Incomplete, Unused -from contextlib import AbstractAsyncContextManager as AsyncContextManager, AbstractContextManager as ContextManager -from types import ModuleType -from typing import ( # noqa: Y022,Y037,Y038,Y039 - IO as IO, - TYPE_CHECKING as TYPE_CHECKING, - AbstractSet as AbstractSet, - Any as Any, - AnyStr as AnyStr, +from collections.abc import ( AsyncGenerator as AsyncGenerator, AsyncIterable as AsyncIterable, AsyncIterator as AsyncIterator, Awaitable as Awaitable, - BinaryIO as BinaryIO, - Callable as Callable, - ChainMap as ChainMap, - ClassVar as ClassVar, Collection as Collection, Container as Container, Coroutine as Coroutine, - Counter as Counter, - DefaultDict as DefaultDict, - Deque as Deque, - Dict as Dict, - ForwardRef as ForwardRef, - FrozenSet as FrozenSet, Generator as Generator, - Generic as Generic, Hashable as Hashable, ItemsView as ItemsView, Iterable as Iterable, Iterator as Iterator, KeysView as KeysView, - List as List, Mapping as Mapping, MappingView as MappingView, - Match as Match, MutableMapping as MutableMapping, MutableSequence as MutableSequence, MutableSet as MutableSet, - NoReturn as NoReturn, - Optional as Optional, - Pattern as Pattern, Reversible as Reversible, Sequence as Sequence, - Set as Set, Sized as Sized, + ValuesView as ValuesView, +) +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 + IO as IO, + TYPE_CHECKING as TYPE_CHECKING, + AbstractSet as AbstractSet, + Any as Any, + AnyStr as AnyStr, + BinaryIO as BinaryIO, + Callable as Callable, + ChainMap as ChainMap, + ClassVar as ClassVar, + Counter as Counter, + DefaultDict as DefaultDict, + Deque as Deque, + Dict as Dict, + ForwardRef as ForwardRef, + FrozenSet as FrozenSet, + Generic as Generic, + List as List, + NoReturn as NoReturn, + Optional as Optional, + Set as Set, Text as Text, TextIO as TextIO, Tuple as Tuple, Type as Type, TypedDict as TypedDict, + TypeVar as _TypeVar, Union as Union, - ValuesView as ValuesView, _Alias, cast as cast, no_type_check as no_type_check, @@ -67,8 +68,6 @@ from typing import ( # noqa: Y022,Y037,Y038,Y039 if sys.version_info >= (3, 10): from types import UnionType -if sys.version_info >= (3, 9): - from types import GenericAlias # Please keep order the same as at runtime. __all__ = [ @@ -196,10 +195,10 @@ __all__ = [ "CapsuleType", ] -_T = typing.TypeVar("_T") -_F = typing.TypeVar("_F", bound=Callable[..., Any]) -_TC = typing.TypeVar("_TC", bound=type[object]) -_T_co = typing.TypeVar("_T_co", covariant=True) # Any type covariant containers. +_T = _TypeVar("_T") +_F = _TypeVar("_F", bound=Callable[..., Any]) +_TC = _TypeVar("_TC", bound=type[object]) +_T_co = _TypeVar("_T_co", covariant=True) # Any type covariant containers. class _Final: ... # This should be imported from typing but that breaks pytype @@ -254,18 +253,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: ... - if sys.version_info >= (3, 9): - @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] + @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] OrderedDict = _Alias() @@ -281,10 +279,8 @@ if sys.version_info >= (3, 10): @overload def get_origin(tp: UnionType) -> type[UnionType]: ... -if sys.version_info >= (3, 9): - @overload - def get_origin(tp: GenericAlias) -> type: ... - +@overload +def get_origin(tp: GenericAlias) -> type: ... @overload def get_origin(tp: ParamSpecArgs | ParamSpecKwargs) -> ParamSpec: ... @overload @@ -364,8 +360,6 @@ else: ) -> IdentityFunction: ... class NamedTuple(tuple[Any, ...]): - if sys.version_info < (3, 9): - _field_types: ClassVar[dict[str, type]] _field_defaults: ClassVar[dict[str, Any]] _fields: ClassVar[tuple[str, ...]] __orig_bases__: ClassVar[tuple[Any, ...]] diff --git a/mypy/typeshed/stdlib/unittest/async_case.pyi b/mypy/typeshed/stdlib/unittest/async_case.pyi index 565dd91c0fda..0b3fb9122c7b 100644 --- a/mypy/typeshed/stdlib/unittest/async_case.pyi +++ b/mypy/typeshed/stdlib/unittest/async_case.pyi @@ -21,5 +21,5 @@ class IsolatedAsyncioTestCase(TestCase): def addAsyncCleanup(self, func: Callable[_P, Awaitable[object]], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... if sys.version_info >= (3, 11): async def enterAsyncContext(self, cm: AbstractAsyncContextManager[_T]) -> _T: ... - if sys.version_info >= (3, 9): - def __del__(self) -> None: ... + + def __del__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/unittest/case.pyi b/mypy/typeshed/stdlib/unittest/case.pyi index 33cd556d2e3b..7d1a382a54a4 100644 --- a/mypy/typeshed/stdlib/unittest/case.pyi +++ b/mypy/typeshed/stdlib/unittest/case.pyi @@ -5,27 +5,12 @@ from _typeshed import SupportsDunderGE, SupportsDunderGT, SupportsDunderLE, Supp from collections.abc import Callable, Container, Iterable, Mapping, Sequence, Set as AbstractSet from contextlib import AbstractContextManager from re import Pattern -from types import TracebackType -from typing import ( - Any, - AnyStr, - ClassVar, - Final, - Generic, - NamedTuple, - NoReturn, - Protocol, - SupportsAbs, - SupportsRound, - TypeVar, - overload, -) +from types import GenericAlias, TracebackType +from typing import Any, AnyStr, Final, Generic, NoReturn, Protocol, SupportsAbs, SupportsRound, TypeVar, overload from typing_extensions import Never, ParamSpec, Self, TypeAlias +from unittest._log import _AssertLogsContext, _LoggingWatcher from warnings import WarningMessage -if sys.version_info >= (3, 9): - from types import GenericAlias - if sys.version_info >= (3, 10): from types import UnionType @@ -58,29 +43,6 @@ class _AssertRaisesBaseContext(_BaseTestCaseContext): # but it's not possible to construct an overload which expresses that def handle(self, name: str, args: list[Any], kwargs: dict[str, Any]) -> Any: ... -if sys.version_info >= (3, 9): - from unittest._log import _AssertLogsContext, _LoggingWatcher -else: - # Unused dummy for _AssertLogsContext. Starting with Python 3.10, - # this is generic over the logging watcher, but in lower versions - # the watcher is hard-coded. - _L = TypeVar("_L") - - class _LoggingWatcher(NamedTuple): - records: list[logging.LogRecord] - output: list[str] - - class _AssertLogsContext(_BaseTestCaseContext, Generic[_L]): - LOGGING_FORMAT: ClassVar[str] - logger_name: str - level: int - msg: None - def __init__(self, test_case: TestCase, logger_name: str, level: int) -> None: ... - def __enter__(self) -> _LoggingWatcher: ... - def __exit__( - self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None - ) -> bool | None: ... - def addModuleCleanup(function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... def doModuleCleanups() -> None: ... @@ -345,8 +307,7 @@ class _AssertRaisesContext(_AssertRaisesBaseContext, Generic[_E]): def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None ) -> bool: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class _AssertWarnsContext(_AssertRaisesBaseContext): warning: WarningMessage diff --git a/mypy/typeshed/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi index 4b32f15095d6..d2664465097f 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -51,9 +51,6 @@ else: "seal", ) -if sys.version_info < (3, 9): - __version__: Final[str] - FILTER_DIR: Any class _SentinelObject: diff --git a/mypy/typeshed/stdlib/urllib/parse.pyi b/mypy/typeshed/stdlib/urllib/parse.pyi index 785bb9678ec7..a5ed616d25af 100644 --- a/mypy/typeshed/stdlib/urllib/parse.pyi +++ b/mypy/typeshed/stdlib/urllib/parse.pyi @@ -1,11 +1,9 @@ import sys -from collections.abc import Callable, Iterable, Mapping, Sequence -from typing import Any, AnyStr, Generic, Literal, NamedTuple, TypeVar, overload +from collections.abc import Iterable, Mapping, Sequence +from types import GenericAlias +from typing import Any, AnyStr, Generic, Literal, NamedTuple, Protocol, overload, type_check_only from typing_extensions import TypeAlias -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = [ "urlparse", "urlunparse", @@ -55,8 +53,7 @@ class _NetlocResultMixinBase(Generic[AnyStr]): def hostname(self) -> AnyStr | None: ... @property def port(self) -> int | None: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... class _NetlocResultMixinStr(_NetlocResultMixinBase[str], _ResultMixinStr): ... class _NetlocResultMixinBytes(_NetlocResultMixinBase[bytes], _ResultMixinBytes): ... @@ -127,13 +124,7 @@ def quote_from_bytes(bs: bytes | bytearray, safe: str | Iterable[int] = "/") -> 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: ... - -if sys.version_info >= (3, 9): - def unquote(string: str | bytes, encoding: str = "utf-8", errors: str = "replace") -> str: ... - -else: - def unquote(string: str, encoding: str = "utf-8", errors: str = "replace") -> 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 @@ -141,38 +132,32 @@ def urldefrag(url: str) -> DefragResult: ... @overload def urldefrag(url: bytes | bytearray | None) -> DefragResultBytes: ... -_Q = TypeVar("_Q", bound=str | Iterable[int]) +# The values are passed through `str()` (unless they are bytes), so anything is valid. _QueryType: TypeAlias = ( - Mapping[Any, Any] | Mapping[Any, Sequence[Any]] | Sequence[tuple[Any, Any]] | Sequence[tuple[Any, Sequence[Any]]] + Mapping[str, object] + | Mapping[bytes, object] + | Mapping[str | bytes, object] + | Mapping[str, Sequence[object]] + | Mapping[bytes, Sequence[object]] + | Mapping[str | bytes, Sequence[object]] + | Sequence[tuple[str | bytes, object]] + | Sequence[tuple[str | bytes, Sequence[object]]] ) -@overload -def urlencode( - query: _QueryType, - doseq: bool = False, - safe: str = "", - encoding: str | None = None, - errors: str | None = None, - quote_via: Callable[[AnyStr, str, str, str], str] = ..., -) -> str: ... -@overload -def urlencode( - query: _QueryType, - doseq: bool, - safe: _Q, - encoding: str | None = None, - errors: str | None = None, - quote_via: Callable[[AnyStr, _Q, str, str], str] = ..., -) -> str: ... -@overload +@type_check_only +class _QuoteVia(Protocol): + @overload + def __call__(self, string: str, safe: str | bytes, encoding: str, errors: str, /) -> str: ... + @overload + def __call__(self, string: bytes, safe: str | bytes, /) -> str: ... + def urlencode( query: _QueryType, doseq: bool = False, - *, - safe: _Q, + safe: str | bytes = "", encoding: str | None = None, errors: str | None = None, - quote_via: Callable[[AnyStr, _Q, str, str], str] = ..., + quote_via: _QuoteVia = ..., ) -> str: ... def urljoin(base: AnyStr, url: AnyStr | None, allow_fragments: bool = True) -> AnyStr: ... @overload diff --git a/mypy/typeshed/stdlib/urllib/request.pyi b/mypy/typeshed/stdlib/urllib/request.pyi index ad4f91fc31ae..1f453fd1e1d6 100644 --- a/mypy/typeshed/stdlib/urllib/request.pyi +++ b/mypy/typeshed/stdlib/urllib/request.pyi @@ -175,7 +175,7 @@ class HTTPCookieProcessor(BaseHandler): class ProxyHandler(BaseHandler): def __init__(self, proxies: dict[str, str] | None = None) -> None: ... def proxy_open(self, req: Request, proxy: str, type: str) -> _UrlopenRet | None: ... # undocumented - # TODO add a method for every (common) proxy protocol + # TODO: add a method for every (common) proxy protocol class HTTPPasswordMgr: def add_password(self, realm: str, uri: str | Sequence[str], user: str, passwd: str) -> None: ... diff --git a/mypy/typeshed/stdlib/urllib/response.pyi b/mypy/typeshed/stdlib/urllib/response.pyi index bbec4cacc750..65df9cdff58f 100644 --- a/mypy/typeshed/stdlib/urllib/response.pyi +++ b/mypy/typeshed/stdlib/urllib/response.pyi @@ -1,4 +1,3 @@ -import sys import tempfile from _typeshed import ReadableBuffer from collections.abc import Callable, Iterable @@ -34,10 +33,8 @@ class addinfo(addbase): class addinfourl(addinfo): url: str code: int | None - if sys.version_info >= (3, 9): - @property - def status(self) -> int | None: ... - + @property + def status(self) -> int | None: ... def __init__(self, fp: IO[bytes], headers: Message, url: str, code: int | None = None) -> None: ... def geturl(self) -> str: ... def getcode(self) -> int | None: ... diff --git a/mypy/typeshed/stdlib/uuid.pyi b/mypy/typeshed/stdlib/uuid.pyi index 1be7a5ef009f..3202ae212cae 100644 --- a/mypy/typeshed/stdlib/uuid.pyi +++ b/mypy/typeshed/stdlib/uuid.pyi @@ -1,6 +1,5 @@ import builtins import sys -from _typeshed import Unused from enum import Enum from typing_extensions import TypeAlias @@ -65,12 +64,7 @@ class UUID: def __ge__(self, other: UUID) -> bool: ... def __hash__(self) -> builtins.int: ... -if sys.version_info >= (3, 9): - def getnode() -> int: ... - -else: - def getnode(*, getters: Unused = None) -> int: ... # undocumented - +def getnode() -> int: ... def uuid1(node: int | None = None, clock_seq: int | None = None) -> UUID: ... if sys.version_info >= (3, 12): diff --git a/mypy/typeshed/stdlib/venv/__init__.pyi b/mypy/typeshed/stdlib/venv/__init__.pyi index 0490c35b44f2..0f71f0e073f5 100644 --- a/mypy/typeshed/stdlib/venv/__init__.pyi +++ b/mypy/typeshed/stdlib/venv/__init__.pyi @@ -6,8 +6,7 @@ from types import SimpleNamespace logger: logging.Logger -if sys.version_info >= (3, 9): - CORE_VENV_DEPS: tuple[str, ...] +CORE_VENV_DEPS: tuple[str, ...] class EnvBuilder: system_site_packages: bool @@ -30,17 +29,6 @@ class EnvBuilder: *, scm_ignore_files: Iterable[str] = ..., ) -> None: ... - elif sys.version_info >= (3, 9): - def __init__( - self, - system_site_packages: bool = False, - clear: bool = False, - symlinks: bool = False, - upgrade: bool = False, - with_pip: bool = False, - prompt: str | None = None, - upgrade_deps: bool = False, - ) -> None: ... else: def __init__( self, @@ -50,6 +38,7 @@ class EnvBuilder: upgrade: bool = False, with_pip: bool = False, prompt: str | None = None, + upgrade_deps: bool = False, ) -> None: ... def create(self, env_dir: StrOrBytesPath) -> None: ... @@ -65,8 +54,7 @@ class EnvBuilder: def post_setup(self, context: SimpleNamespace) -> None: ... def replace_variables(self, text: str, context: SimpleNamespace) -> str: ... # undocumented def install_scripts(self, context: SimpleNamespace, path: str) -> None: ... - if sys.version_info >= (3, 9): - def upgrade_dependencies(self, context: SimpleNamespace) -> None: ... + def upgrade_dependencies(self, context: SimpleNamespace) -> None: ... if sys.version_info >= (3, 13): def create_git_ignore_file(self, context: SimpleNamespace) -> None: ... @@ -83,17 +71,6 @@ if sys.version_info >= (3, 13): scm_ignore_files: Iterable[str] = ..., ) -> None: ... -elif sys.version_info >= (3, 9): - def create( - env_dir: StrOrBytesPath, - system_site_packages: bool = False, - clear: bool = False, - symlinks: bool = False, - with_pip: bool = False, - prompt: str | None = None, - upgrade_deps: bool = False, - ) -> None: ... - else: def create( env_dir: StrOrBytesPath, @@ -102,6 +79,7 @@ else: symlinks: bool = False, with_pip: bool = False, prompt: str | None = None, + upgrade_deps: bool = False, ) -> None: ... def main(args: Sequence[str] | None = None) -> None: ... diff --git a/mypy/typeshed/stdlib/wave.pyi b/mypy/typeshed/stdlib/wave.pyi index 9319d5347c79..ddc6f6bd02a5 100644 --- a/mypy/typeshed/stdlib/wave.pyi +++ b/mypy/typeshed/stdlib/wave.pyi @@ -1,12 +1,8 @@ -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 -if sys.version_info >= (3, 9): - __all__ = ["open", "Error", "Wave_read", "Wave_write"] -else: - __all__ = ["open", "openfp", "Error", "Wave_read", "Wave_write"] +__all__ = ["open", "Error", "Wave_read", "Wave_write"] _File: TypeAlias = str | IO[bytes] @@ -80,6 +76,3 @@ def open(f: _File, mode: Literal["r", "rb"]) -> Wave_read: ... def open(f: _File, mode: Literal["w", "wb"]) -> Wave_write: ... @overload def open(f: _File, mode: str | None = None) -> Any: ... - -if sys.version_info < (3, 9): - openfp = open diff --git a/mypy/typeshed/stdlib/weakref.pyi b/mypy/typeshed/stdlib/weakref.pyi index 05a7b2bcda66..593eb4615c8f 100644 --- a/mypy/typeshed/stdlib/weakref.pyi +++ b/mypy/typeshed/stdlib/weakref.pyi @@ -1,14 +1,11 @@ -import sys from _typeshed import SupportsKeysAndGetItem from _weakref import getweakrefcount as getweakrefcount, getweakrefs as getweakrefs, proxy as proxy 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 -if sys.version_info >= (3, 9): - from types import GenericAlias - __all__ = [ "ref", "proxy", @@ -61,8 +58,7 @@ class ReferenceType(Generic[_T]): # "weakref" def __call__(self) -> _T | None: ... def __eq__(self, value: object, /) -> bool: ... def __hash__(self) -> int: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... + def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... ref = ReferenceType @@ -123,14 +119,13 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): def update(self, other: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None: ... @overload def update(self, other: None = None, /, **kwargs: _VT) -> None: ... - if sys.version_info >= (3, 9): - 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: ... - @overload - def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... + 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: ... + @overload + def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... class KeyedRef(ref[_T], Generic[_KT, _T]): key: _KT @@ -177,14 +172,13 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def update(self, dict: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None: ... @overload def update(self, dict: None = None, /, **kwargs: _VT) -> None: ... - if sys.version_info >= (3, 9): - 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: ... - @overload - def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... + 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: ... + @overload + def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... class finalize(Generic[_P, _T]): def __init__(self, obj: _T, func: Callable[_P, Any], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/dom/minidom.pyi b/mypy/typeshed/stdlib/xml/dom/minidom.pyi index 51bbf4993657..ab2ef87e38a8 100644 --- a/mypy/typeshed/stdlib/xml/dom/minidom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/minidom.pyi @@ -1,4 +1,3 @@ -import sys import xml.dom from _collections_abc import dict_keys, dict_values from _typeshed import Incomplete, ReadableBuffer, SupportsRead, SupportsWrite @@ -88,71 +87,39 @@ class Node(xml.dom.Node): @property def localName(self) -> str | None: ... # non-null only for Element and Attr def __bool__(self) -> Literal[True]: ... - if sys.version_info >= (3, 9): - @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, - indent: str = "\t", - newl: str = "\n", - # Handle any case where encoding is not provided or where it is passed with None - encoding: None = None, - standalone: bool | None = None, - ) -> str: ... - @overload - def toprettyxml( - self, - indent: str, - newl: str, - # Handle cases where encoding is passed as str *positionally* - encoding: str, - standalone: bool | None = None, - ) -> bytes: ... - @overload - def toprettyxml( - self, - indent: str = "\t", - newl: str = "\n", - # Handle all cases where encoding is passed as a keyword argument; because standalone - # comes after, it will also have to be a keyword arg if encoding is - *, - encoding: str, - standalone: bool | None = None, - ) -> bytes: ... - else: - @overload - def toxml(self, encoding: str) -> bytes: ... - @overload - def toxml(self, encoding: None = None) -> str: ... - @overload - def toprettyxml( - self, - indent: str = "\t", - newl: str = "\n", - # Handle any case where encoding is not provided or where it is passed with None - encoding: None = None, - ) -> str: ... - @overload - def toprettyxml( - self, - indent: str, - newl: str, - # Handle cases where encoding is passed as str *positionally* - encoding: str, - ) -> bytes: ... - @overload - def toprettyxml( - self, - indent: str = "\t", - newl: str = "\n", - # Handle all cases where encoding is passed as a keyword argument - *, - encoding: str, - ) -> bytes: ... - + @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, + indent: str = "\t", + newl: str = "\n", + # Handle any case where encoding is not provided or where it is passed with None + encoding: None = None, + standalone: bool | None = None, + ) -> str: ... + @overload + def toprettyxml( + self, + indent: str, + newl: str, + # Handle cases where encoding is passed as str *positionally* + encoding: str, + standalone: bool | None = None, + ) -> bytes: ... + @overload + def toprettyxml( + self, + indent: str = "\t", + newl: str = "\n", + # Handle all cases where encoding is passed as a keyword argument; because standalone + # comes after, it will also have to be a keyword arg if encoding is + *, + encoding: str, + standalone: bool | None = None, + ) -> bytes: ... def hasChildNodes(self) -> bool: ... def insertBefore( # type: ignore[misc] self: _NodesWithChildren, # pyright: ignore[reportGeneralTypeIssues] @@ -657,26 +624,15 @@ class Document(Node, DocumentLS): def getElementsByTagNameNS(self, namespaceURI: str | None, localName: str) -> NodeList[Element]: ... def isSupported(self, feature: str, version: str | None) -> bool: ... def importNode(self, node: _ImportableNodeVar, deep: bool) -> _ImportableNodeVar: ... - if sys.version_info >= (3, 9): - def writexml( - self, - writer: SupportsWrite[str], - indent: str = "", - addindent: str = "", - newl: str = "", - encoding: str | None = None, - standalone: bool | None = None, - ) -> None: ... - else: - def writexml( - self, - writer: SupportsWrite[str], - indent: str = "", - addindent: str = "", - newl: str = "", - encoding: Incomplete | None = None, - ) -> None: ... - + def writexml( + self, + writer: SupportsWrite[str], + indent: str = "", + addindent: str = "", + newl: str = "", + encoding: str | None = None, + standalone: bool | None = None, + ) -> None: ... @overload def renameNode(self, n: Element, namespaceURI: str, name: str) -> Element: ... @overload diff --git a/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi b/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi index 10c305826453..8f20ee15a14e 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi @@ -1,4 +1,3 @@ -import sys from _typeshed import FileDescriptorOrPath from typing import Final, Literal, Protocol, overload from xml.etree.ElementTree import Element @@ -13,8 +12,7 @@ XINCLUDE: Final[str] XINCLUDE_INCLUDE: Final[str] XINCLUDE_FALLBACK: Final[str] -if sys.version_info >= (3, 9): - DEFAULT_MAX_INCLUSION_DEPTH: Final = 6 +DEFAULT_MAX_INCLUSION_DEPTH: Final = 6 class FatalIncludeError(SyntaxError): ... @@ -22,11 +20,6 @@ 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: ... -if sys.version_info >= (3, 9): - def include(elem: Element, loader: _Loader | None = None, base_url: str | None = None, max_depth: int | None = 6) -> None: ... - - class LimitedRecursiveIncludeError(FatalIncludeError): ... - -else: - def include(elem: Element, loader: _Loader | None = None) -> None: ... +class LimitedRecursiveIncludeError(FatalIncludeError): ... diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index 4a9113868d7e..4c55a1a7452e 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -15,6 +15,7 @@ __all__ = [ "canonicalize", "fromstring", "fromstringlist", + "indent", "iselement", "iterparse", "parse", @@ -34,9 +35,6 @@ __all__ = [ "register_namespace", ] -if sys.version_info >= (3, 9): - __all__ += ["indent"] - _T = TypeVar("_T") _FileRead: TypeAlias = FileDescriptorOrPath | SupportsRead[bytes] | SupportsRead[str] _FileWriteC14N: TypeAlias = FileDescriptorOrPath | SupportsWrite[bytes] @@ -138,9 +136,6 @@ class Element(Generic[_Tag]): # Doesn't really exist in earlier versions, where __len__ is called implicitly instead @deprecated("Testing an element's truth value is deprecated.") def __bool__(self) -> bool: ... - if sys.version_info < (3, 9): - def getchildren(self) -> list[Element]: ... - def getiterator(self, tag: str | None = None) -> list[Element]: ... def SubElement(parent: Element, tag: str, attrib: dict[str, str] = ..., **extra: str) -> Element: ... def Comment(text: str | None = None) -> _CallableElement: ... @@ -165,9 +160,6 @@ class ElementTree(Generic[_Root]): def getroot(self) -> _Root: ... def parse(self, source: _FileRead, parser: XMLParser | None = None) -> Element: ... def iter(self, tag: str | None = None) -> Generator[Element, None, None]: ... - if sys.version_info < (3, 9): - def getiterator(self, tag: str | None = None) -> list[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: ... @@ -254,10 +246,7 @@ def tostringlist( short_empty_elements: bool = True, ) -> list[Any]: ... def dump(elem: Element | ElementTree[Any]) -> None: ... - -if sys.version_info >= (3, 9): - def indent(tree: Element | ElementTree[Any], space: str = " ", level: int = 0) -> None: ... - +def indent(tree: Element | 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 @@ -366,7 +355,7 @@ _E = TypeVar("_E", default=Element) class XMLParser(Generic[_E]): parser: XMLParserType target: _Target - # TODO-what is entity used for??? + # TODO: what is entity used for??? entity: dict[str, str] version: str def __init__(self, *, target: _Target | None = None, encoding: str | None = None) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/sax/expatreader.pyi b/mypy/typeshed/stdlib/xml/sax/expatreader.pyi index 6a68f52f0e99..012d6c03e121 100644 --- a/mypy/typeshed/stdlib/xml/sax/expatreader.pyi +++ b/mypy/typeshed/stdlib/xml/sax/expatreader.pyi @@ -53,11 +53,7 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator): ) -> None: ... @overload def setProperty(self, name: str, value: object) -> None: ... - if sys.version_info >= (3, 9): - def feed(self, data: str | ReadableBuffer, isFinal: bool = False) -> None: ... - else: - def feed(self, data: str | ReadableBuffer, isFinal: _BoolType = 0) -> None: ... - + def feed(self, data: str | ReadableBuffer, isFinal: bool = False) -> None: ... def flush(self) -> None: ... def close(self) -> None: ... def reset(self) -> None: ... diff --git a/mypy/typeshed/stdlib/zipfile/__init__.pyi b/mypy/typeshed/stdlib/zipfile/__init__.pyi index 91bc051df686..ede732c0f86a 100644 --- a/mypy/typeshed/stdlib/zipfile/__init__.pyi +++ b/mypy/typeshed/stdlib/zipfile/__init__.pyi @@ -30,7 +30,6 @@ _DateTuple = tuple[int, int, int, int, int, int] # noqa: Y026 _ZipFileMode = Literal["r", "w", "x", "a"] # noqa: Y026 _ReadWriteMode: TypeAlias = Literal["r", "w"] -_ReadWriteBinaryMode: TypeAlias = Literal["r", "w", "rb", "wb"] class BadZipFile(Exception): ... @@ -321,25 +320,20 @@ else: @property def stem(self) -> str: ... - if sys.version_info >= (3, 9): - @overload - def open( - self, - mode: Literal["r", "w"] = "r", - encoding: str | None = None, - errors: str | None = None, - newline: str | None = None, - line_buffering: bool = ..., - write_through: bool = ..., - *, - pwd: bytes | None = None, - ) -> TextIOWrapper: ... - @overload - def open(self, mode: Literal["rb", "wb"], *, pwd: bytes | None = None) -> IO[bytes]: ... - else: - def open( - self, mode: _ReadWriteBinaryMode = "r", pwd: bytes | None = None, *, force_zip64: bool = False - ) -> IO[bytes]: ... + @overload + def open( + self, + mode: Literal["r", "w"] = "r", + encoding: str | None = None, + errors: str | None = None, + newline: str | None = None, + line_buffering: bool = ..., + write_through: bool = ..., + *, + pwd: bytes | None = None, + ) -> TextIOWrapper: ... + @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]: ... diff --git a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi index fb21b00c45dc..35381758a1b7 100644 --- a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi +++ b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi @@ -1,35 +1,28 @@ -import sys from collections.abc import Iterable from datetime import datetime, timedelta, tzinfo from typing_extensions import Self +from zoneinfo._common import ZoneInfoNotFoundError as ZoneInfoNotFoundError, _IOBytes +from zoneinfo._tzpath import ( + TZPATH as TZPATH, + InvalidTZPathWarning as InvalidTZPathWarning, + available_timezones as available_timezones, + reset_tzpath as reset_tzpath, +) -# TODO: remove this version check -# In theory we shouldn't need this version check. Pyright complains about the imports -# from zoneinfo.* when run on 3.8 and 3.7 without this. Updates to typeshed's -# pyright test script are probably needed, see #11189 -if sys.version_info >= (3, 9): - from zoneinfo._common import ZoneInfoNotFoundError as ZoneInfoNotFoundError, _IOBytes - from zoneinfo._tzpath import ( - TZPATH as TZPATH, - InvalidTZPathWarning as InvalidTZPathWarning, - available_timezones as available_timezones, - reset_tzpath as reset_tzpath, - ) +__all__ = ["ZoneInfo", "reset_tzpath", "available_timezones", "TZPATH", "ZoneInfoNotFoundError", "InvalidTZPathWarning"] - __all__ = ["ZoneInfo", "reset_tzpath", "available_timezones", "TZPATH", "ZoneInfoNotFoundError", "InvalidTZPathWarning"] +class ZoneInfo(tzinfo): + @property + def key(self) -> str: ... + def __new__(cls, key: str) -> Self: ... + @classmethod + def no_cache(cls, key: str) -> Self: ... + @classmethod + def from_file(cls, fobj: _IOBytes, /, key: str | None = None) -> Self: ... + @classmethod + def clear_cache(cls, *, only_keys: Iterable[str] | None = None) -> None: ... + def tzname(self, dt: datetime | None, /) -> str | None: ... + def utcoffset(self, dt: datetime | None, /) -> timedelta | None: ... + def dst(self, dt: datetime | None, /) -> timedelta | None: ... - class ZoneInfo(tzinfo): - @property - def key(self) -> str: ... - def __new__(cls, key: str) -> Self: ... - @classmethod - def no_cache(cls, key: str) -> Self: ... - @classmethod - def from_file(cls, fobj: _IOBytes, /, key: str | None = None) -> Self: ... - @classmethod - def clear_cache(cls, *, only_keys: Iterable[str] | None = None) -> None: ... - def tzname(self, dt: datetime | None, /) -> str | None: ... - def utcoffset(self, dt: datetime | None, /) -> timedelta | None: ... - def dst(self, dt: datetime | None, /) -> timedelta | None: ... - - def __dir__() -> list[str]: ... +def __dir__() -> list[str]: ...