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 6794731274d14..5933de3fb4b6d 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,26 +1,26 @@ -From 83cf9b2dcc569149510c3a9118b9a7dc44144232 Mon Sep 17 00:00:00 2001 +From 2c74a0f55cf0314339a855f6a37297298d73e0e4 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Mon, 26 Sep 2022 12:55:07 -0700 Subject: [PATCH] Remove use of LiteralString in builtins (#13743) --- - mypy/typeshed/stdlib/builtins.pyi | 127 +----------------------------- - 1 file changed, 1 insertion(+), 126 deletions(-) + mypy/typeshed/stdlib/builtins.pyi | 130 +----------------------------- + 1 file changed, 2 insertions(+), 128 deletions(-) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi -index 0fe6d9a69..1808e28e2 100644 +index 6feba7ea2..8e25d8aea 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi -@@ -65,7 +65,7 @@ from typing import ( # noqa: Y022,UP035 - ) +@@ -66,7 +66,7 @@ from typing import ( # noqa: Y022 # ruff: ignore[deprecated-import] # we can't import `Literal` from typing or mypy crashes: see #11247 --from typing_extensions import Literal, LiteralString, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023, UP035 -+from typing_extensions import Literal, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023, UP035 + # ruff: ignore[deprecated-import] +-from typing_extensions import Literal, LiteralString, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023 ++from typing_extensions import Literal, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023 if sys.version_info >= (3, 14): from _typeshed import AnnotateFunc -@@ -489,20 +489,8 @@ class str(Sequence[str]): +@@ -484,20 +484,8 @@ class str(Sequence[str]): def __new__(cls, object: object = "") -> Self: ... @overload def __new__(cls, object: ReadableBuffer, encoding: str = "utf-8", errors: str = "strict") -> Self: ... @@ -41,7 +41,7 @@ index 0fe6d9a69..1808e28e2 100644 def center(self, width: SupportsIndex, fillchar: str = " ", /) -> str: ... # type: ignore[misc] def count(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ... -@@ -510,17 +498,9 @@ class str(Sequence[str]): +@@ -505,17 +493,9 @@ class str(Sequence[str]): def endswith( self, suffix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, / ) -> bool: ... @@ -59,7 +59,7 @@ index 0fe6d9a69..1808e28e2 100644 def format(self, *args: object, **kwargs: object) -> str: ... def format_map(self, mapping: _FormatMapMapping, /) -> str: ... -@@ -537,119 +517,38 @@ class str(Sequence[str]): +@@ -532,119 +512,38 @@ class str(Sequence[str]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... @@ -179,7 +179,7 @@ index 0fe6d9a69..1808e28e2 100644 def zfill(self, width: SupportsIndex, /) -> str: ... # type: ignore[misc] if sys.version_info >= (3, 15): -@@ -677,49 +576,25 @@ class str(Sequence[str]): +@@ -672,51 +571,26 @@ class str(Sequence[str]): @staticmethod @overload def maketrans(x: str, y: str, z: str, /) -> dict[int, int | None]: ... @@ -214,7 +214,10 @@ index 0fe6d9a69..1808e28e2 100644 - @overload - def __mod__(self: LiteralString, value: LiteralString | tuple[LiteralString, ...], /) -> LiteralString: ... - @overload - def __mod__(self, value: Any, /) -> str: ... +- def __mod__(self, value: object, /) -> str: ... +- ++ def __mod__(self, value: Any, /) -> str: ... + def __rmod__(self, value: str, /) -> str: ... - - @overload - def __mul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ... @@ -230,5 +233,5 @@ index 0fe6d9a69..1808e28e2 100644 def __getnewargs__(self) -> tuple[str]: ... -- -2.54.0 +2.56.0 diff --git a/mypy/typeshed/stdlib/_codecs.pyi b/mypy/typeshed/stdlib/_codecs.pyi index 449e9e24af9b1..e854c80ff375d 100644 --- a/mypy/typeshed/stdlib/_codecs.pyi +++ b/mypy/typeshed/stdlib/_codecs.pyi @@ -13,7 +13,7 @@ class _EncodingMap: _DecodeCharMap: TypeAlias = SupportsGetItem[int, str | int | None] _EncodeCharMap: TypeAlias = SupportsGetItem[int, bytes | int | None] | _EncodingMap -_Handler: TypeAlias = Callable[[UnicodeError], tuple[str | bytes, int]] +_Handler: TypeAlias = Callable[[UnicodeEncodeError | UnicodeDecodeError | UnicodeTranslateError], tuple[str | bytes, int]] _SearchFunction: TypeAlias = Callable[[str], codecs.CodecInfo | None] def register(search_function: _SearchFunction, /) -> None: ... diff --git a/mypy/typeshed/stdlib/_collections_abc.pyi b/mypy/typeshed/stdlib/_collections_abc.pyi index 6fc32078532e0..363098df80589 100644 --- a/mypy/typeshed/stdlib/_collections_abc.pyi +++ b/mypy/typeshed/stdlib/_collections_abc.pyi @@ -1,7 +1,7 @@ import sys from abc import abstractmethod from types import MappingProxyType -from typing import ( # noqa: Y022,Y038,UP035,Y057 +from typing import ( # noqa: Y022,Y038,Y057 # ruff: ignore[deprecated-import] AbstractSet as Set, AsyncGenerator as AsyncGenerator, AsyncIterable as AsyncIterable, diff --git a/mypy/typeshed/stdlib/_hashlib.pyi b/mypy/typeshed/stdlib/_hashlib.pyi index b98edc5757c39..5b8050ebc8d42 100644 --- a/mypy/typeshed/stdlib/_hashlib.pyi +++ b/mypy/typeshed/stdlib/_hashlib.pyi @@ -2,10 +2,39 @@ import sys from _typeshed import ReadableBuffer from collections.abc import Callable from types import ModuleType -from typing import AnyStr, Protocol, TypeAlias, final, overload, type_check_only +from typing import AnyStr, Literal, Protocol, TypeAlias, final, overload, type_check_only from typing_extensions import Self, disjoint_base _DigestMod: TypeAlias = str | Callable[[], _HashObject] | ModuleType | None +_FixedDigestName: TypeAlias = Literal[ + "md5", + "MD5", + "sha1", + "SHA1", + "sha224", + "SHA224", + "sha256", + "SHA256", + "sha384", + "SHA384", + "sha512", + "SHA512", + "sha3_224", + "sha3-224", + "SHA3-224", + "sha3_256", + "sha3-256", + "SHA3-256", + "sha3_384", + "sha3-384", + "SHA3-384", + "sha3_512", + "sha3-512", + "SHA3-512", +] +_XofDigestName: TypeAlias = Literal[ + "shake_128", "shake128", "SHAKE128", "shake-128", "SHAKE-128", "shake_256", "shake256", "SHAKE256", "shake-256", "SHAKE-256" +] openssl_md_meth_names: frozenset[str] @@ -22,8 +51,22 @@ class _HashObject(Protocol): def hexdigest(self) -> str: ... def update(self, obj: ReadableBuffer, /) -> None: ... +@type_check_only +class _HashObjectWithOptionalLength(Protocol): + @property + def digest_size(self) -> int: ... + @property + def block_size(self) -> int: ... + @property + def name(self) -> str: ... + def copy(self) -> Self: ... + # Depending on the algorithm, length is either required or not accepted. + def digest(self, length: int = ...) -> bytes: ... + def hexdigest(self, length: int = ...) -> str: ... + def update(self, obj: ReadableBuffer, /) -> None: ... + @disjoint_base -class HASH: +class HASH(_HashObjectWithOptionalLength): @property def digest_size(self) -> int: ... @property @@ -31,8 +74,8 @@ class HASH: @property def name(self) -> str: ... def copy(self) -> Self: ... - def digest(self) -> bytes: ... - def hexdigest(self) -> str: ... + def digest(self) -> bytes: ... # type: ignore[override] + def hexdigest(self) -> str: ... # type: ignore[override] def update(self, obj: ReadableBuffer, /) -> None: ... class UnsupportedDigestmodError(ValueError): ... @@ -63,9 +106,19 @@ def get_fips_mode() -> int: ... def hmac_new(key: ReadableBuffer, msg: ReadableBuffer = b"", digestmod: _DigestMod = None) -> HMAC: ... if sys.version_info >= (3, 13): + @overload def new( - name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + name: _XofDigestName, data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> HASHXOF: ... + @overload + def new( + name: _FixedDigestName, data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None ) -> HASH: ... + @overload + def new( + name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None + ) -> _HashObjectWithOptionalLength: ... + def openssl_md5( data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None ) -> HASH: ... @@ -102,9 +155,14 @@ if sys.version_info >= (3, 13): def openssl_shake_256( data: ReadableBuffer = b"", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None ) -> HASHXOF: ... - else: - def new(name: str, string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + @overload + def new(name: _XofDigestName, string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASHXOF: ... + @overload + def new(name: _FixedDigestName, string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... + @overload + def new(name: str, string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _HashObjectWithOptionalLength: ... + 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: ... diff --git a/mypy/typeshed/stdlib/_interpreters.pyi b/mypy/typeshed/stdlib/_interpreters.pyi index a7ef6d1fcecf1..d9a9a3a05227c 100644 --- a/mypy/typeshed/stdlib/_interpreters.pyi +++ b/mypy/typeshed/stdlib/_interpreters.pyi @@ -33,7 +33,7 @@ def get_config(id: SupportsIndex, *, restrict: bool = False) -> types.SimpleName def whence(id: SupportsIndex) -> _Whence: ... def exec( id: SupportsIndex, code: str | types.CodeType | Callable[[], object], shared: _SharedDict = {}, *, restrict: bool = False -) -> None | types.SimpleNamespace: ... +) -> types.SimpleNamespace | None: ... def call( id: SupportsIndex, callable: Callable[..., _R], diff --git a/mypy/typeshed/stdlib/_ssl.pyi b/mypy/typeshed/stdlib/_ssl.pyi index 87023d90e13bb..29e50111b8b2a 100644 --- a/mypy/typeshed/stdlib/_ssl.pyi +++ b/mypy/typeshed/stdlib/_ssl.pyi @@ -79,7 +79,7 @@ class _SSLContext: post_handshake_auth: bool protocol: int security_level: int - sni_callback: Callable[[SSLObject, str, SSLContext], None | int] | None + sni_callback: Callable[[SSLObject, str, SSLContext], int | None] | None verify_flags: int verify_mode: int def __new__(cls, protocol: int, /) -> Self: ... diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index 98dfb02d04b11..fa6ef8150e3a5 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -170,7 +170,7 @@ class SupportsTrunc(Protocol): # The second and third overload could technically be combined, but splitting # them works better with some type checkers. -class SupportsGet(Protocol[_KT_contra, _VT_co]): # type: ignore[misc] # Covariant type as parameter +class SupportsGet(Protocol[_KT_contra, _VT_co]): # type: ignore[misc] # ty:ignore[invalid-protocol] # Covariant type as parameter @overload def get(self, key: _KT_contra, /) -> _VT_co | None: ... @overload @@ -189,6 +189,18 @@ class SupportsKeysAndGetItem(Protocol[_KT, _VT_co]): def keys(self) -> Iterable[_KT]: ... def __getitem__(self, key: _KT, /) -> _VT_co: ... +class SupportsKeysAndGet(Protocol[_KT, _VT_co]): # type: ignore[misc] # ty:ignore[invalid-protocol] # Covariant type as parameter + def keys(self) -> Iterable[_KT]: ... + + @overload + def get(self, key: _KT, /) -> _VT_co | None: ... + @overload + def get( # pyrefly: ignore[invalid-variance] + self, key: _KT, default: _VT_co, / # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter + ) -> _VT_co: ... + @overload + def get(self, key: _KT, default: _T, /) -> _VT_co | _T: ... + # stable class SupportsGetItem(Protocol[_KT_contra, _VT_co]): def __getitem__(self, key: _KT_contra, /) -> _VT_co: ... diff --git a/mypy/typeshed/stdlib/ast.pyi b/mypy/typeshed/stdlib/ast.pyi index a1993773ee25f..f84c93e7953e5 100644 --- a/mypy/typeshed/stdlib/ast.pyi +++ b/mypy/typeshed/stdlib/ast.pyi @@ -1107,7 +1107,7 @@ if sys.version_info >= (3, 14): **kwargs: Unpack[_Attributes], ) -> Self: ... -_ConstantValue: typing_extensions.TypeAlias = str | bytes | bool | int | float | complex | None | EllipsisType +_ConstantValue: typing_extensions.TypeAlias = str | bytes | bool | int | float | complex | EllipsisType | None class Constant(expr): __match_args__ = ("value", "kind") @@ -1741,7 +1741,7 @@ if sys.version_info >= (3, 15): mode: Literal["exec", "eval", "func_type", "single"] = "exec", *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, module: str | None = None, ) -> _T: ... @@ -1752,7 +1752,7 @@ if sys.version_info >= (3, 15): mode: Literal["exec"] = "exec", *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, module: str | None = None, ) -> Module: ... @@ -1763,7 +1763,7 @@ if sys.version_info >= (3, 15): mode: Literal["eval"], *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, module: str | None = None, ) -> Expression: ... @@ -1774,7 +1774,7 @@ if sys.version_info >= (3, 15): mode: Literal["func_type"], *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, module: str | None = None, ) -> FunctionType: ... @@ -1785,7 +1785,7 @@ if sys.version_info >= (3, 15): mode: Literal["single"], *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, module: str | None = None, ) -> Interactive: ... @@ -1795,7 +1795,7 @@ if sys.version_info >= (3, 15): *, mode: Literal["eval"], type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, module: str | None = None, ) -> Expression: ... @@ -1805,7 +1805,7 @@ if sys.version_info >= (3, 15): *, mode: Literal["func_type"], type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, module: str | None = None, ) -> FunctionType: ... @@ -1815,7 +1815,7 @@ if sys.version_info >= (3, 15): *, mode: Literal["single"], type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, module: str | None = None, ) -> Interactive: ... @@ -1826,7 +1826,7 @@ if sys.version_info >= (3, 15): mode: str = "exec", *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, module: str | None = None, ) -> mod: ... @@ -1838,7 +1838,7 @@ elif sys.version_info >= (3, 13): mode: Literal["exec", "eval", "func_type", "single"] = "exec", *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, ) -> _T: ... @overload @@ -1848,7 +1848,7 @@ elif sys.version_info >= (3, 13): mode: Literal["exec"] = "exec", *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, ) -> Module: ... @overload @@ -1858,7 +1858,7 @@ elif sys.version_info >= (3, 13): mode: Literal["eval"], *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, ) -> Expression: ... @overload @@ -1868,7 +1868,7 @@ elif sys.version_info >= (3, 13): mode: Literal["func_type"], *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, ) -> FunctionType: ... @overload @@ -1878,7 +1878,7 @@ elif sys.version_info >= (3, 13): mode: Literal["single"], *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, ) -> Interactive: ... @overload @@ -1887,7 +1887,7 @@ elif sys.version_info >= (3, 13): *, mode: Literal["eval"], type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, ) -> Expression: ... @overload @@ -1896,7 +1896,7 @@ elif sys.version_info >= (3, 13): *, mode: Literal["func_type"], type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, ) -> FunctionType: ... @overload @@ -1905,7 +1905,7 @@ elif sys.version_info >= (3, 13): *, mode: Literal["single"], type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, ) -> Interactive: ... @overload @@ -1915,7 +1915,7 @@ elif sys.version_info >= (3, 13): mode: str = "exec", *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, optimize: Literal[-1, 0, 1, 2] = -1, ) -> mod: ... else: @@ -1926,7 +1926,7 @@ else: mode: Literal["exec", "eval", "func_type", "single"] = "exec", *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, ) -> _T: ... @overload def parse( @@ -1935,7 +1935,7 @@ else: mode: Literal["exec"] = "exec", *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, ) -> Module: ... @overload def parse( @@ -1944,7 +1944,7 @@ else: mode: Literal["eval"], *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, ) -> Expression: ... @overload def parse( @@ -1953,7 +1953,7 @@ else: mode: Literal["func_type"], *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, ) -> FunctionType: ... @overload def parse( @@ -1962,7 +1962,7 @@ else: mode: Literal["single"], *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, ) -> Interactive: ... @overload def parse( @@ -1970,7 +1970,7 @@ else: *, mode: Literal["eval"], type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, ) -> Expression: ... @overload def parse( @@ -1978,7 +1978,7 @@ else: *, mode: Literal["func_type"], type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, ) -> FunctionType: ... @overload def parse( @@ -1986,7 +1986,7 @@ else: *, mode: Literal["single"], type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, ) -> Interactive: ... @overload def parse( @@ -1995,7 +1995,7 @@ else: mode: str = "exec", *, type_comments: bool = False, - feature_version: None | int | tuple[int, int] = None, + feature_version: int | tuple[int, int] | None = None, ) -> mod: ... def literal_eval(node_or_string: str | AST) -> Any: ... diff --git a/mypy/typeshed/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi index cfd67e252e740..29ecbdf7feba0 100644 --- a/mypy/typeshed/stdlib/asyncio/base_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_events.pyi @@ -23,7 +23,7 @@ _ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) _Context: TypeAlias = dict[str, Any] _ExceptionHandler: TypeAlias = Callable[[AbstractEventLoop, _Context], object] _ProtocolFactory: TypeAlias = Callable[[], BaseProtocol] -_SSLContext: TypeAlias = bool | None | ssl.SSLContext +_SSLContext: TypeAlias = bool | ssl.SSLContext | None class Server(AbstractServer): if sys.version_info >= (3, 11): diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index 77b932b25f535..4d1cf3138c7e0 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -66,7 +66,7 @@ _ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) _Context: TypeAlias = dict[str, Any] _ExceptionHandler: TypeAlias = Callable[[AbstractEventLoop, _Context], object] _ProtocolFactory: TypeAlias = Callable[[], BaseProtocol] -_SSLContext: TypeAlias = bool | None | ssl.SSLContext +_SSLContext: TypeAlias = bool | ssl.SSLContext | None @type_check_only class _TaskFactory(Protocol): diff --git a/mypy/typeshed/stdlib/asyncio/subprocess.pyi b/mypy/typeshed/stdlib/asyncio/subprocess.pyi index 6405e5ae14741..7f447cf1d82a6 100644 --- a/mypy/typeshed/stdlib/asyncio/subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/subprocess.pyi @@ -61,9 +61,9 @@ if sys.version_info >= (3, 11): restore_signals: bool = True, start_new_session: bool = False, pass_fds: Collection[int] = (), - group: None | str | int = None, - extra_groups: None | Collection[str | int] = None, - user: None | str | int = None, + group: str | int | None = None, + extra_groups: Collection[str | int] | None = None, + user: str | int | None = None, umask: int = -1, process_group: int | None = None, pipesize: int = -1, @@ -93,9 +93,9 @@ if sys.version_info >= (3, 11): restore_signals: bool = True, start_new_session: bool = False, pass_fds: Collection[int] = (), - group: None | str | int = None, - extra_groups: None | Collection[str | int] = None, - user: None | str | int = None, + group: str | int | None = None, + extra_groups: Collection[str | int] | None = None, + user: str | int | None = None, umask: int = -1, process_group: int | None = None, pipesize: int = -1, @@ -127,9 +127,9 @@ else: restore_signals: bool = True, start_new_session: bool = False, pass_fds: Collection[int] = (), - group: None | str | int = None, - extra_groups: None | Collection[str | int] = None, - user: None | str | int = None, + group: str | int | None = None, + extra_groups: Collection[str | int] | None = None, + user: str | int | None = None, umask: int = -1, pipesize: int = -1, ) -> Process: ... @@ -158,9 +158,9 @@ else: restore_signals: bool = True, start_new_session: bool = False, pass_fds: Collection[int] = (), - group: None | str | int = None, - extra_groups: None | Collection[str | int] = None, - user: None | str | int = None, + group: str | int | None = None, + extra_groups: Collection[str | int] | None = None, + user: str | int | None = None, umask: int = -1, pipesize: int = -1, ) -> Process: ... diff --git a/mypy/typeshed/stdlib/binascii.pyi b/mypy/typeshed/stdlib/binascii.pyi index 6840c68838119..b363f94c1bb57 100644 --- a/mypy/typeshed/stdlib/binascii.pyi +++ b/mypy/typeshed/stdlib/binascii.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import ReadableBuffer -from typing import TypeAlias +from typing import SupportsIndex, TypeAlias from typing_extensions import deprecated # Many functions in binascii accept buffer objects @@ -85,8 +85,8 @@ if sys.version_info < (3, 11): @deprecated("Deprecated since Python 3.9; removed in Python 3.11.") def b2a_hqx(data: ReadableBuffer, /) -> bytes: ... -def crc_hqx(data: ReadableBuffer, crc: int, /) -> int: ... -def crc32(data: ReadableBuffer, crc: int = 0, /) -> int: ... +def crc_hqx(data: ReadableBuffer, crc: SupportsIndex, /) -> int: ... +def crc32(data: ReadableBuffer, crc: SupportsIndex = 0, /) -> int: ... def b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = 1) -> bytes: ... def hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = 1) -> bytes: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 57b5388715408..938ccaf3efe45 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -30,14 +30,14 @@ from _typeshed import ( SupportsRichComparisonT, SupportsWrite, ) -from collections.abc import Awaitable, Callable, Iterable, Iterator, MutableSet, Set as AbstractSet, Sized +from collections.abc import Awaitable, Callable, Hashable, Iterable, Iterator, MutableSet, Set as AbstractSet, Sized from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper from os import PathLike from types import CellType, CodeType, EllipsisType, GenericAlias, NotImplementedType, TracebackType, UnionType # mypy crashes if any of {ByteString, Sequence, MutableSequence, Mapping, MutableMapping} # are imported from collections.abc in builtins.pyi -from typing import ( # noqa: Y022,UP035 +from typing import ( # noqa: Y022 # ruff: ignore[deprecated-import] IO, Any, BinaryIO, @@ -65,7 +65,8 @@ from typing import ( # noqa: Y022,UP035 ) # we can't import `Literal` from typing or mypy crashes: see #11247 -from typing_extensions import Literal, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023, UP035 +# ruff: ignore[deprecated-import] +from typing_extensions import Literal, Self, TypeIs, TypeVarTuple, deprecated, disjoint_base # noqa: Y023 if sys.version_info >= (3, 14): from _typeshed import AnnotateFunc @@ -91,11 +92,11 @@ _P = ParamSpec("_P") # Type variables for slice _StartT_co = TypeVar("_StartT_co", covariant=True, default=Any) # slice -> slice[Any, Any, Any] -_StopT_co = TypeVar("_StopT_co", covariant=True, default=_StartT_co) # slice[A] -> slice[A, A, A] +_StopT_co = TypeVar("_StopT_co", covariant=True, default=_StartT_co) # slice[A] -> slice[A, A, A] # NOTE: step could differ from start and stop, (e.g. datetime/timedelta)l # the default (start|stop) is chosen to cater to the most common case of int/index slices. # FIXME: https://github.com/python/typing/issues/213 (replace step=start|stop with step=start&stop) -_StepT_co = TypeVar("_StepT_co", covariant=True, default=_StartT_co | _StopT_co) # slice[A,B] -> slice[A, B, A|B] +_StepT_co = TypeVar("_StepT_co", covariant=True, default=_StartT_co | _StopT_co) # slice[A,B] -> slice[A, B, A|B] @disjoint_base class object: @@ -181,29 +182,21 @@ class classmethod(Generic[_T, _P, _R_co]): @disjoint_base class type: # object.__base__ is None. Otherwise, it would be a type. - @property - def __base__(self) -> type | None: ... + __base__: Final[type | None] __bases__: tuple[type, ...] - @property - def __basicsize__(self) -> int: ... + __basicsize__: Final[int] # type.__dict__ is read-only at runtime, but that can't be expressed currently. # See https://github.com/python/typeshed/issues/11033 for a discussion. __dict__: Final[types.MappingProxyType[str, Any]] # type: ignore[assignment] - @property - def __dictoffset__(self) -> int: ... - @property - def __flags__(self) -> int: ... - @property - def __itemsize__(self) -> int: ... + __dictoffset__: Final[int] + __flags__: Final[int] + __itemsize__: Final[int] __module__: str - @property - def __mro__(self) -> tuple[type, ...]: ... + __mro__: Final[tuple[type, ...]] __name__: str __qualname__: str - @property - def __text_signature__(self) -> str | None: ... - @property - def __weakrefoffset__(self) -> int: ... + __text_signature__: Final[str | None] + __weakrefoffset__: Final[int] @overload def __init__(self, o: object, /) -> None: ... @@ -594,6 +587,7 @@ class str(Sequence[str]): def __len__(self) -> int: ... def __lt__(self, value: str, /) -> bool: ... def __mod__(self, value: Any, /) -> str: ... + def __rmod__(self, value: str, /) -> str: ... def __mul__(self, value: SupportsIndex, /) -> str: ... # type: ignore[misc] def __ne__(self, value: object, /) -> bool: ... @@ -700,7 +694,9 @@ class bytes(Sequence[int]): def __add__(self, value: ReadableBuffer, /) -> bytes: ... def __mul__(self, value: SupportsIndex, /) -> bytes: ... def __rmul__(self, value: SupportsIndex, /) -> bytes: ... + # The format string chooses the conversion, including numbers and %a/%r (PEP 461). def __mod__(self, value: Any, /) -> bytes: ... + def __rmod__(self, value: bytes, /) -> bytes: ... # Incompatible with Sequence.__contains__ def __contains__(self, key: SupportsIndex | ReadableBuffer, /) -> bool: ... # type: ignore[override] def __eq__(self, value: object, /) -> bool: ... @@ -831,7 +827,9 @@ class bytearray(MutableSequence[int]): def __mul__(self, value: SupportsIndex, /) -> bytearray: ... def __rmul__(self, value: SupportsIndex, /) -> bytearray: ... def __imul__(self, value: SupportsIndex, /) -> Self: ... - def __mod__(self, value: Any, /) -> bytes: ... + # The format string chooses the conversion, including numbers and %a/%r (PEP 461). + def __mod__(self, value: Any, /) -> bytearray: ... + def __rmod__(self, value: bytearray, /) -> bytearray: ... # Incompatible with Sequence.__contains__ def __contains__(self, key: SupportsIndex | ReadableBuffer, /) -> bool: ... # type: ignore[override] def __eq__(self, value: object, /) -> bool: ... @@ -880,7 +878,7 @@ class memoryview(Sequence[_I]): def __enter__(self) -> Self: ... def __exit__( self, - exc_type: type[BaseException] | None, # noqa: PYI036 # This is the module declaring BaseException + exc_type: type[BaseException] | None, # ruff: ignore[bad-exit-annotation] # This is the module declaring BaseException exc_val: BaseException | None, exc_tb: TracebackType | None, /, @@ -1033,7 +1031,7 @@ class tuple(Sequence[_T_co]): def __gt__(self, value: tuple[_T_co, ...], /) -> bool: ... def __ge__(self, value: tuple[_T_co, ...], /) -> bool: ... def __eq__(self, value: object, /) -> bool: ... - def __hash__(self) -> int: ... + def __hash__(self: tuple[Hashable, ...]) -> int: ... @overload def __add__(self, value: tuple[_T_co, ...], /) -> tuple[_T_co, ...]: ... @@ -1351,12 +1349,36 @@ class set(MutableSet[_T]): def __iter__(self) -> Iterator[_T]: ... def __and__(self, value: AbstractSet[object], /) -> set[_T]: ... def __iand__(self, value: AbstractSet[object], /) -> Self: ... + + @overload + def __rand__(self, value: set[_S], /) -> set[_S]: ... + @overload + def __rand__(self, value: frozenset[_S], /) -> frozenset[_S]: ... + def __or__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... def __ior__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] + + @overload + def __ror__(self, value: set[_S], /) -> set[_T | _S]: ... + @overload + def __ror__(self, value: frozenset[_S], /) -> frozenset[_T | _S]: ... + def __sub__(self, value: AbstractSet[object], /) -> set[_T]: ... def __isub__(self, value: AbstractSet[object], /) -> Self: ... + + @overload + def __rsub__(self, value: set[_S], /) -> set[_S]: ... + @overload + def __rsub__(self, value: frozenset[_S], /) -> frozenset[_S]: ... + def __xor__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ... def __ixor__(self, value: AbstractSet[_T], /) -> Self: ... # type: ignore[override,misc] + + @overload + def __rxor__(self, value: set[_S], /) -> set[_T | _S]: ... + @overload + def __rxor__(self, value: frozenset[_S], /) -> frozenset[_T | _S]: ... + def __le__(self, value: AbstractSet[object], /) -> bool: ... def __lt__(self, value: AbstractSet[object], /) -> bool: ... def __ge__(self, value: AbstractSet[object], /) -> bool: ... @@ -1384,9 +1406,33 @@ class frozenset(AbstractSet[_T_co]): def __contains__(self, o: object, /) -> bool: ... def __iter__(self) -> Iterator[_T_co]: ... def __and__(self, value: AbstractSet[object], /) -> frozenset[_T_co]: ... + + @overload + def __rand__(self, value: set[_S], /) -> set[_S]: ... + @overload + def __rand__(self, value: frozenset[_S], /) -> frozenset[_S]: ... + def __or__(self, value: AbstractSet[_S], /) -> frozenset[_T_co | _S]: ... + + @overload + def __ror__(self, value: set[_S], /) -> set[_T_co | _S]: ... + @overload + def __ror__(self, value: frozenset[_S], /) -> frozenset[_T_co | _S]: ... + def __sub__(self, value: AbstractSet[object], /) -> frozenset[_T_co]: ... + + @overload + def __rsub__(self, value: set[_S], /) -> set[_S]: ... + @overload + def __rsub__(self, value: frozenset[_S], /) -> frozenset[_S]: ... + def __xor__(self, value: AbstractSet[_S], /) -> frozenset[_T_co | _S]: ... + + @overload + def __rxor__(self, value: set[_S], /) -> set[_T_co | _S]: ... + @overload + def __rxor__(self, value: frozenset[_S], /) -> frozenset[_T_co | _S]: ... + def __le__(self, value: AbstractSet[object], /) -> bool: ... def __lt__(self, value: AbstractSet[object], /) -> bool: ... def __ge__(self, value: AbstractSet[object], /) -> bool: ... @@ -2198,10 +2244,6 @@ if sys.version_info >= (3, 15): def __build_class__(func: Callable[[], CellType | Any], name: str, /, *bases: Any, metaclass: Any = ..., **kwds: Any) -> Any: ... -# Backwards compatibility hack for folks who relied on the ellipsis type -# existing in typeshed in Python 3.9 and earlier. -ellipsis = EllipsisType - Ellipsis: EllipsisType NotImplemented: NotImplementedType diff --git a/mypy/typeshed/stdlib/cgi.pyi b/mypy/typeshed/stdlib/cgi.pyi index b7f88ded315f4..fd8752aa6532c 100644 --- a/mypy/typeshed/stdlib/cgi.pyi +++ b/mypy/typeshed/stdlib/cgi.pyi @@ -81,7 +81,7 @@ class FieldStorage: length: int done: int list: _list[Any] | None - value: None | bytes | _list[Any] + value: bytes | _list[Any] | None def __init__( self, fp: IO[Any] | None = None, diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index 3e2e838eaa26a..bce72464fd751 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -148,12 +148,12 @@ class UserList(MutableSequence[_T]): def __add__(self, other: Iterable[_T]) -> Self: ... def __radd__(self, other: Iterable[_T]) -> Self: ... def __iadd__(self, other: Iterable[_T]) -> Self: ... - def __mul__(self, n: int) -> Self: ... - def __rmul__(self, n: int) -> Self: ... - def __imul__(self, n: int) -> Self: ... + def __mul__(self, n: SupportsIndex) -> Self: ... + def __rmul__(self, n: SupportsIndex) -> Self: ... + def __imul__(self, n: SupportsIndex) -> Self: ... def append(self, item: _T) -> None: ... - def insert(self, i: int, item: _T) -> None: ... - def pop(self, i: int = -1) -> _T: ... + def insert(self, i: SupportsIndex, item: _T) -> None: ... + def pop(self, i: SupportsIndex = -1) -> _T: ... def remove(self, item: _T) -> None: ... def copy(self) -> Self: ... def __copy__(self) -> Self: ... @@ -191,21 +191,23 @@ class UserString(Sequence[UserString]): def __reversed__(self) -> Iterator[Self]: ... def __add__(self, other: object) -> Self: ... def __radd__(self, other: object) -> Self: ... - def __mul__(self, n: int) -> Self: ... - def __rmul__(self, n: int) -> Self: ... + def __mul__(self, n: SupportsIndex) -> Self: ... + def __rmul__(self, n: SupportsIndex) -> Self: ... def __mod__(self, args: Any) -> Self: ... def __rmod__(self, template: object) -> Self: ... def capitalize(self) -> Self: ... def casefold(self) -> Self: ... - def center(self, width: int, *args: Any) -> Self: ... - def count(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ... + def center(self, width: SupportsIndex, *args: Any) -> Self: ... + def count(self, sub: str | UserString, start: SupportsIndex | None = 0, end: SupportsIndex | None = sys.maxsize) -> int: ... def encode(self: UserString, encoding: str | None = "utf-8", errors: str | None = "strict") -> bytes: ... - def endswith(self, suffix: str | tuple[str, ...], start: int | None = 0, end: int | None = sys.maxsize) -> bool: ... - def expandtabs(self, tabsize: int = 8) -> Self: ... - def find(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ... + def endswith( + self, suffix: str | tuple[str, ...], start: SupportsIndex | None = 0, end: SupportsIndex | None = sys.maxsize + ) -> bool: ... + def expandtabs(self, tabsize: SupportsIndex = 8) -> Self: ... + def find(self, sub: str | UserString, start: SupportsIndex | None = 0, end: SupportsIndex | None = sys.maxsize) -> int: ... def format(self, *args: Any, **kwds: Any) -> str: ... def format_map(self, mapping: Mapping[str, Any]) -> str: ... - def index(self, sub: str, start: int = 0, end: int = sys.maxsize) -> int: ... + def index(self, sub: str, start: SupportsIndex | None = 0, end: SupportsIndex | None = sys.maxsize) -> int: ... def isalpha(self) -> bool: ... def isalnum(self) -> bool: ... def isdecimal(self) -> bool: ... @@ -219,29 +221,31 @@ class UserString(Sequence[UserString]): def isupper(self) -> bool: ... def isascii(self) -> bool: ... def join(self, seq: Iterable[str]) -> str: ... - def ljust(self, width: int, *args: Any) -> Self: ... + def ljust(self, width: SupportsIndex, *args: Any) -> Self: ... def lower(self) -> Self: ... def lstrip(self, chars: str | None = None) -> Self: ... maketrans = str.maketrans def partition(self, sep: str) -> tuple[str, str, str]: ... 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: ... - def rjust(self, width: int, *args: Any) -> Self: ... + def replace(self, old: str | UserString, new: str | UserString, maxsplit: SupportsIndex = -1) -> Self: ... + def rfind(self, sub: str | UserString, start: SupportsIndex | None = 0, end: SupportsIndex | None = sys.maxsize) -> int: ... + def rindex(self, sub: str | UserString, start: SupportsIndex | None = 0, end: SupportsIndex | None = sys.maxsize) -> int: ... + def rjust(self, width: SupportsIndex, *args: Any) -> Self: ... def rpartition(self, sep: str) -> tuple[str, str, str]: ... def rstrip(self, chars: str | None = None) -> Self: ... - def split(self, sep: str | None = None, maxsplit: int = -1) -> list[str]: ... - def rsplit(self, sep: str | None = None, maxsplit: int = -1) -> list[str]: ... + def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... + def rsplit(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ... def splitlines(self, keepends: bool = False) -> list[str]: ... - def startswith(self, prefix: str | tuple[str, ...], start: int | None = 0, end: int | None = sys.maxsize) -> bool: ... + def startswith( + self, prefix: str | tuple[str, ...], start: SupportsIndex | None = 0, end: SupportsIndex | None = sys.maxsize + ) -> bool: ... def strip(self, chars: str | None = None) -> Self: ... def swapcase(self) -> Self: ... def title(self) -> Self: ... def translate(self, *args: Any) -> Self: ... def upper(self) -> Self: ... - def zfill(self, width: int) -> Self: ... + def zfill(self, width: SupportsIndex) -> Self: ... @disjoint_base class deque(MutableSequence[_T]): @@ -259,12 +263,12 @@ class deque(MutableSequence[_T]): def count(self, x: _T, /) -> int: ... def extend(self, iterable: Iterable[_T], /) -> None: ... def extendleft(self, iterable: Iterable[_T], /) -> None: ... - def insert(self, i: int, x: _T, /) -> None: ... - def index(self, x: _T, start: int = 0, stop: int = ..., /) -> int: ... + def insert(self, i: SupportsIndex, x: _T, /) -> None: ... + def index(self, x: _T, start: SupportsIndex = 0, stop: SupportsIndex = ..., /) -> int: ... def pop(self) -> _T: ... # type: ignore[override] def popleft(self) -> _T: ... def remove(self, value: _T, /) -> None: ... - def rotate(self, n: int = 1, /) -> None: ... + def rotate(self, n: SupportsIndex = 1, /) -> None: ... def __copy__(self) -> Self: ... def __len__(self) -> int: ... __hash__: ClassVar[None] # type: ignore[assignment] @@ -276,9 +280,9 @@ class deque(MutableSequence[_T]): def __reduce__(self) -> tuple[type[Self], tuple[()], None, Iterator[_T]]: ... def __iadd__(self, value: Iterable[_T], /) -> Self: ... def __add__(self, value: Self, /) -> Self: ... - def __mul__(self, value: int, /) -> Self: ... - def __rmul__(self, value: int, /) -> Self: ... - def __imul__(self, value: int, /) -> Self: ... + def __mul__(self, value: SupportsIndex, /) -> Self: ... + def __rmul__(self, value: SupportsIndex, /) -> Self: ... + def __imul__(self, value: SupportsIndex, /) -> Self: ... def __lt__(self, value: deque[_T], /) -> bool: ... def __le__(self, value: deque[_T], /) -> bool: ... def __gt__(self, value: deque[_T], /) -> bool: ... diff --git a/mypy/typeshed/stdlib/doctest.pyi b/mypy/typeshed/stdlib/doctest.pyi index 7d1dfe6d8a92c..000278ae953e1 100644 --- a/mypy/typeshed/stdlib/doctest.pyi +++ b/mypy/typeshed/stdlib/doctest.pyi @@ -133,7 +133,7 @@ class DocTestFinder: self, obj: object, name: str | None = None, - module: None | bool | types.ModuleType = None, + module: bool | types.ModuleType | None = None, globs: dict[str, Any] | None = None, extraglobs: dict[str, Any] | None = None, ) -> list[DocTest]: ... @@ -198,7 +198,7 @@ def testfile( filename: str, module_relative: bool = True, name: str | None = None, - package: None | str | types.ModuleType = None, + package: str | types.ModuleType | None = None, globs: dict[str, Any] | None = None, verbose: bool | None = None, report: bool = True, @@ -239,7 +239,7 @@ class SkipDocTestCase(DocTestCase): class _DocTestSuite(unittest.TestSuite): ... def DocTestSuite( - module: None | str | types.ModuleType = None, + module: str | types.ModuleType | None = None, globs: dict[str, Any] | None = None, extraglobs: dict[str, Any] | None = None, test_finder: DocTestFinder | None = None, @@ -251,7 +251,7 @@ class DocFileCase(DocTestCase): ... def DocFileTest( path: str, module_relative: bool = True, - package: None | str | types.ModuleType = None, + package: str | types.ModuleType | None = None, globs: dict[str, Any] | None = None, parser: DocTestParser = ..., encoding: str | None = None, @@ -259,7 +259,7 @@ def DocFileTest( ) -> DocFileCase: ... def DocFileSuite(*paths: str, **kw: Any) -> _DocTestSuite: ... def script_from_examples(s: str) -> str: ... -def testsource(module: None | str | types.ModuleType, name: str) -> str: ... +def testsource(module: str | types.ModuleType | None, name: str) -> str: ... def debug_src(src: str, pm: bool = False, globs: dict[str, Any] | None = None) -> None: ... def debug_script(src: str, pm: bool = False, globs: dict[str, Any] | None = None) -> None: ... -def debug(module: None | str | types.ModuleType, name: str, pm: bool = False) -> None: ... +def debug(module: str | types.ModuleType | None, name: str, pm: bool = False) -> None: ... diff --git a/mypy/typeshed/stdlib/email/__init__.pyi b/mypy/typeshed/stdlib/email/__init__.pyi index 503674f1f6020..f2a0a92703e32 100644 --- a/mypy/typeshed/stdlib/email/__init__.pyi +++ b/mypy/typeshed/stdlib/email/__init__.pyi @@ -9,7 +9,7 @@ from typing import TypeAlias, overload # At runtime, listing submodules in __all__ without them being imported is # valid, and causes them to be included in a star import. See #6523 -__all__ = [ # noqa: F822 # Undefined names in __all__ +__all__ = [ # ruff: ignore[undefined-export] # Undefined names in __all__ "base64mime", # pyright: ignore[reportUnsupportedDunderAll] "charset", # pyright: ignore[reportUnsupportedDunderAll] "encoders", # pyright: ignore[reportUnsupportedDunderAll] @@ -31,7 +31,7 @@ __all__ = [ # noqa: F822 # Undefined names in __all__ # Definitions imported by multiple submodules in typeshed _ParamType: TypeAlias = str | tuple[str | None, str | None, str] # noqa: Y047 -_ParamsType: TypeAlias = str | None | tuple[str, str | None, str] # noqa: Y047 +_ParamsType: TypeAlias = str | tuple[str, str | None, str] | None # noqa: Y047 @overload def message_from_string(s: str) -> Message[str, str]: ... diff --git a/mypy/typeshed/stdlib/filecmp.pyi b/mypy/typeshed/stdlib/filecmp.pyi index 620cc177a415a..651fe2bd958bb 100644 --- a/mypy/typeshed/stdlib/filecmp.pyi +++ b/mypy/typeshed/stdlib/filecmp.pyi @@ -33,8 +33,8 @@ class dircmp(Generic[AnyStr]): ignore: Sequence[AnyStr] | None = None, hide: Sequence[AnyStr] | None = None, ) -> None: ... - left: AnyStr - right: AnyStr + left: GenericPath[AnyStr] + right: GenericPath[AnyStr] hide: Sequence[AnyStr] ignore: Sequence[AnyStr] # These properties are created at runtime by __getattr__ diff --git a/mypy/typeshed/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index 07d0ffc7a021e..23260ab908551 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -5,6 +5,7 @@ from collections.abc import Callable, Hashable, Iterable, Sized from types import GenericAlias from typing import ( Any, + Concatenate, Final, Generic, Literal, @@ -43,6 +44,8 @@ _PWrapped = ParamSpec("_PWrapped") _RWrapped = TypeVar("_RWrapped") _PWrapper = ParamSpec("_PWrapper") _RWrapper = TypeVar("_RWrapper") +_WrapperSelfT = TypeVar("_WrapperSelfT") +_PBound = ParamSpec("_PBound") if sys.version_info >= (3, 14): @overload @@ -117,10 +120,17 @@ WRAPPER_UPDATES: Final[tuple[Literal["__dict__"]]] class _Wrapped(Generic[_PWrapped, _RWrapped, _PWrapper, _RWrapper]): __wrapped__: Callable[_PWrapped, _RWrapped] def __call__(self, *args: _PWrapper.args, **kwargs: _PWrapper.kwargs) -> _RWrapper: ... - # as with ``Callable``, we'll assume that these attributes exist + # as with ``Callable``, we'll assume that these attributes/methods exist __name__: str __qualname__: str + @overload + def __get__(self, instance: None, owner: type, /) -> Self: ... + @overload + def __get__( + self: Callable[Concatenate[_WrapperSelfT, _PBound], _RWrapper], instance: _WrapperSelfT, owner: type | None = None, / + ) -> Callable[_PBound, _RWrapper]: ... + @type_check_only class _Wrapper(Generic[_PWrapped, _RWrapped]): def __call__(self, f: Callable[_PWrapper, _RWrapper]) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ... @@ -235,6 +245,20 @@ class _SingleDispatchCallable(Generic[_T]): def singledispatch(func: Callable[..., _T]) -> _SingleDispatchCallable[_T]: ... +@type_check_only +class _SingleDispatchMethodCallable(Generic[_T]): + __name__: str + __qualname__: str + __wrapped__: Callable[..., _T] + def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ... + + @overload + def register(self, cls: _RegType, method: None = None) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + @overload + def register(self, cls: Callable[..., _T], method: None = None) -> Callable[..., _T]: ... + @overload + def register(self, cls: _RegType, method: Callable[..., _T]) -> Callable[..., _T]: ... + class singledispatchmethod(Generic[_T]): dispatcher: _SingleDispatchCallable[_T] func: Callable[..., _T] @@ -249,7 +273,7 @@ class singledispatchmethod(Generic[_T]): @overload def register(self, cls: _RegType, method: Callable[..., _T]) -> Callable[..., _T]: ... - def __get__(self, obj: _S, cls: type[_S] | None = None) -> Callable[..., _T]: ... + def __get__(self, obj: _S, cls: type[_S] | None = None) -> _SingleDispatchMethodCallable[_T]: ... class cached_property(Generic[_T_co]): func: Callable[[Any], _T_co] diff --git a/mypy/typeshed/stdlib/graphlib.pyi b/mypy/typeshed/stdlib/graphlib.pyi index f0ac72b6135e8..0e77f031ad1c4 100644 --- a/mypy/typeshed/stdlib/graphlib.pyi +++ b/mypy/typeshed/stdlib/graphlib.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import SupportsItems -from collections.abc import Iterable +from collections.abc import Iterable, Iterator from typing import Any, Generic, TypeVar, overload __all__ = ["TopologicalSorter", "CycleError"] @@ -22,7 +22,7 @@ class TopologicalSorter(Generic[_T]): def __bool__(self) -> bool: ... def done(self, *nodes: _T) -> None: ... def get_ready(self) -> tuple[_T, ...]: ... - def static_order(self) -> Iterable[_T]: ... + def static_order(self) -> Iterator[_T]: ... if sys.version_info >= (3, 11): def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/hashlib.pyi b/mypy/typeshed/stdlib/hashlib.pyi index 50bc8e21f1d52..be1ce7a8efd09 100644 --- a/mypy/typeshed/stdlib/hashlib.pyi +++ b/mypy/typeshed/stdlib/hashlib.pyi @@ -2,7 +2,11 @@ import sys from _blake2 import blake2b as blake2b, blake2s as blake2s from _hashlib import ( HASH, + HASHXOF, + _FixedDigestName, _HashObject, + _HashObjectWithOptionalLength, + _XofDigestName, openssl_md5 as md5, openssl_sha1 as sha1, openssl_sha3_224 as sha3_224, @@ -20,7 +24,9 @@ from _hashlib import ( ) from _typeshed import ReadableBuffer from collections.abc import Callable, Set as AbstractSet -from typing import Protocol, type_check_only +from typing import Protocol, TypeVar, overload, type_check_only + +_HashT = TypeVar("_HashT", bound=_HashObject) if sys.version_info >= (3, 15): __all__ = ( @@ -89,7 +95,12 @@ else: "pbkdf2_hmac", ) -def new(name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... +@overload +def new(name: _XofDigestName, data: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASHXOF: ... +@overload +def new(name: _FixedDigestName, data: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> HASH: ... +@overload +def new(name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _HashObjectWithOptionalLength: ... algorithms_guaranteed: AbstractSet[str] algorithms_available: AbstractSet[str] @@ -104,9 +115,12 @@ if sys.version_info >= (3, 11): def readinto(self, buf: bytearray, /) -> int: ... def readable(self) -> bool: ... + @overload + def file_digest(fileobj: _BytesIOLike | _FileDigestFileObj, digest: str, /, *, _bufsize: int = 262144) -> HASH: ... + @overload def file_digest( - fileobj: _BytesIOLike | _FileDigestFileObj, digest: str | Callable[[], _HashObject], /, *, _bufsize: int = 262144 - ) -> HASH: ... + fileobj: _BytesIOLike | _FileDigestFileObj, digest: Callable[[], _HashT], /, *, _bufsize: int = 262144 + ) -> _HashT: ... # Legacy typing-only alias _Hash = HASH diff --git a/mypy/typeshed/stdlib/imp.pyi b/mypy/typeshed/stdlib/imp.pyi index b5b4223aa58e9..69351dede0526 100644 --- a/mypy/typeshed/stdlib/imp.pyi +++ b/mypy/typeshed/stdlib/imp.pyi @@ -56,7 +56,7 @@ def load_module(name: str, file: _FileLike | None, filename: str, details: tuple # IO[Any] is a TextIOWrapper if name is a .py file, and a FileIO otherwise. def find_module( - name: str, path: None | list[str] | list[PathLike[str]] | list[StrPath] = None + name: str, path: list[str] | list[PathLike[str]] | list[StrPath] | None = None ) -> tuple[IO[Any], str, tuple[str, str, int]]: ... def reload(module: types.ModuleType) -> types.ModuleType: ... def init_builtin(name: str) -> types.ModuleType | None: ... diff --git a/mypy/typeshed/stdlib/json/__init__.pyi b/mypy/typeshed/stdlib/json/__init__.pyi index 2342b29cb0c82..d853722c0fc8b 100644 --- a/mypy/typeshed/stdlib/json/__init__.pyi +++ b/mypy/typeshed/stdlib/json/__init__.pyi @@ -16,7 +16,7 @@ def dumps( check_circular: bool = True, allow_nan: bool = True, cls: type[JSONEncoder] | None = None, - indent: None | int | str = None, + indent: int | str | None = None, separators: tuple[str, str] | None = None, default: Callable[[Any], Any] | None = None, sort_keys: bool = False, @@ -31,7 +31,7 @@ def dump( check_circular: bool = True, allow_nan: bool = True, cls: type[JSONEncoder] | None = None, - indent: None | int | str = None, + indent: int | str | None = None, separators: tuple[str, str] | None = None, default: Callable[[Any], Any] | None = None, sort_keys: bool = False, diff --git a/mypy/typeshed/stdlib/lib2to3/refactor.pyi b/mypy/typeshed/stdlib/lib2to3/refactor.pyi index b365d64a1de1a..9031b10097152 100644 --- a/mypy/typeshed/stdlib/lib2to3/refactor.pyi +++ b/mypy/typeshed/stdlib/lib2to3/refactor.pyi @@ -79,7 +79,7 @@ class RefactoringTool: class MultiprocessingUnsupported(Exception): ... class MultiprocessRefactoringTool(RefactoringTool): - queue: JoinableQueue[None | tuple[Iterable[str], bool | int]] | None + queue: JoinableQueue[tuple[Iterable[str], bool | int] | None] | None output_lock: Lock | None def refactor( self, items: Iterable[str], write: bool = False, doctests_only: bool = False, num_processes: int = 1 diff --git a/mypy/typeshed/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index 39bd64694a1e1..d7799e3c948ff 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -61,7 +61,7 @@ if sys.version_info >= (3, 12): __all__ += ["getHandlerByName", "getHandlerNames"] _SysExcInfoType: TypeAlias = tuple[type[BaseException], BaseException, TracebackType | None] | tuple[None, None, None] -_ExcInfoType: TypeAlias = None | bool | _SysExcInfoType | BaseException +_ExcInfoType: TypeAlias = bool | _SysExcInfoType | BaseException | None _ArgsType: TypeAlias = tuple[object, ...] | Mapping[str, object] _Level: TypeAlias = int | str _FormatStyle: TypeAlias = Literal["%", "{", "$"] @@ -225,7 +225,7 @@ class Logger(Filterer): lno: int, msg: object, args: _ArgsType, - exc_info: _SysExcInfoType | None, + exc_info: _SysExcInfoType | Literal[False] | None, func: str | None = None, extra: Mapping[str, object] | None = None, sinfo: str | None = None, @@ -307,12 +307,15 @@ class Filter: def filter(self, record: LogRecord) -> bool: ... class LogRecord: - # args can be set to None by logging.handlers.QueueHandler - # (see https://bugs.python.org/issue44473) + # args can be set to None by logging.handlers.QueueHandler, which + # contradicts the LogRecord documentation, but seems to be intentional, + # see https://github.com/python/cpython/issues/88639 args: _ArgsType | None asctime: str created: float - exc_info: _SysExcInfoType | None + # Prior to Python 3.16, Logger._log() only normalizes truthy exc_info + # values so exc_info=False ends up on the record unchanged. + exc_info: _SysExcInfoType | Literal[False] | None exc_text: str | None filename: str funcName: str @@ -342,6 +345,9 @@ class LogRecord: pathname: str, lineno: int, msg: object, + # args can be set to None by logging.handlers.QueueHandler, which + # contradicts the LogRecord documentation, but seems to be intentional, + # see https://github.com/python/cpython/issues/88639 args: _ArgsType | None, exc_info: _SysExcInfoType | None, func: str | None = None, diff --git a/mypy/typeshed/stdlib/marshal.pyi b/mypy/typeshed/stdlib/marshal.pyi index 2988074a43366..04cdf05b19341 100644 --- a/mypy/typeshed/stdlib/marshal.pyi +++ b/mypy/typeshed/stdlib/marshal.pyi @@ -6,13 +6,8 @@ from typing import Any, Final, TypeAlias version: Final[int] _Marshallable: TypeAlias = ( - # handled in w_object() in marshal.c - None - | type[StopIteration] - | types.EllipsisType - | bool # handled in w_complex_object() in marshal.c - | int + int | float | complex | bytes @@ -24,6 +19,11 @@ _Marshallable: TypeAlias = ( | frozenset[_Marshallable] | types.CodeType | ReadableBuffer + # handled in w_object() in marshal.c + | type[StopIteration] + | types.EllipsisType + | bool + | None ) if sys.version_info >= (3, 15): diff --git a/mypy/typeshed/stdlib/nntplib.pyi b/mypy/typeshed/stdlib/nntplib.pyi index 50b633ce1ad12..926b07be79e6e 100644 --- a/mypy/typeshed/stdlib/nntplib.pyi +++ b/mypy/typeshed/stdlib/nntplib.pyi @@ -95,7 +95,7 @@ class NNTP: def xhdr(self, hdr: str, str: Any, *, file: _File = None) -> tuple[str, _list[str]]: ... def xover(self, start: int, end: int, *, file: _File = None) -> tuple[str, _list[tuple[int, dict[str, str]]]]: ... def over( - self, message_spec: None | str | _list[Any] | tuple[Any, ...], *, file: _File = None + self, message_spec: str | _list[Any] | tuple[Any, ...] | None, *, file: _File = None ) -> tuple[str, _list[tuple[int, dict[str, str]]]]: ... def date(self) -> tuple[str, datetime.datetime]: ... def post(self, data: bytes | Iterable[bytes]) -> str: ... diff --git a/mypy/typeshed/stdlib/pathlib/__init__.pyi b/mypy/typeshed/stdlib/pathlib/__init__.pyi index 781b6aebd8a14..dfd85087642af 100644 --- a/mypy/typeshed/stdlib/pathlib/__init__.pyi +++ b/mypy/typeshed/stdlib/pathlib/__init__.pyi @@ -1,5 +1,4 @@ import sys -import types from _typeshed import ( OpenBinaryMode, OpenBinaryModeReading, @@ -14,7 +13,7 @@ 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 GenericAlias, TracebackType +from types import GenericAlias, ModuleType, TracebackType from typing import IO, Any, BinaryIO, ClassVar, Literal, TypeVar, overload from typing_extensions import Never, Self, deprecated @@ -56,7 +55,7 @@ class PurePath(PathLike[str]): else: __slots__ = ("_drv", "_root", "_parts", "_str", "_hash", "_pparts", "_cached_cparts") if sys.version_info >= (3, 13): - parser: ClassVar[types.ModuleType] + parser: ClassVar[ModuleType] def full_match(self, pattern: StrPath, *, case_sensitive: bool | None = None) -> bool: ... @property diff --git a/mypy/typeshed/stdlib/profiling/sampling/stack_collector.pyi b/mypy/typeshed/stdlib/profiling/sampling/stack_collector.pyi index 0da7c4987801c..8ea1db6bc41c4 100644 --- a/mypy/typeshed/stdlib/profiling/sampling/stack_collector.pyi +++ b/mypy/typeshed/stdlib/profiling/sampling/stack_collector.pyi @@ -1,12 +1,22 @@ -from _typeshed import StrOrBytesPath, SupportsGet +from _typeshed import StrOrBytesPath, SupportsGet, SupportsKeysAndGet from abc import ABCMeta +from collections import Counter from collections.abc import Sequence +from typing import Literal, TypeAlias, TypedDict, type_check_only +from typing_extensions import Required from _remote_debugging import AwaitedInfo, InterpreterInfo -from .collector import Collector, _Frame, _Timestamps +from .collector import Collector, _Frame, _Location, _Timestamps + +# type check only +# TODO: move to binary_collector.pyi when that is added +_CaptureFeatureKeys: TypeAlias = Literal["all_threads", "native", "gc", "opcodes", "blocking"] class StackTraceCollector(Collector, metaclass=ABCMeta): + sample_interval_usec: int + skip_idle: bool + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... def collect( self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None @@ -14,11 +24,35 @@ class StackTraceCollector(Collector, metaclass=ABCMeta): def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... class CollapsedStackCollector(StackTraceCollector): + stack_counter: Counter[tuple[tuple[str, _Location, str], int]] def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... def export(self, filename: StrOrBytesPath) -> None: ... +@type_check_only +class _FlamegraphCollectorStats(TypedDict, total=False): + sample_interval_usec: Required[int] + duration_sec: float + sample_rate: float + error_rate: float | None + missed_samples: float | None + mode: int | None + +@type_check_only +class _ThreadStatusCounts(TypedDict): + has_gil: int + on_cpu: int + gil_requested: int + unknown: int + has_exception: int + total: int + class FlamegraphCollector(StackTraceCollector): + stats: _FlamegraphCollectorStats + thread_status_counts: _ThreadStatusCounts + samples_with_gc_frames: int + per_thread_stats: dict[int, _ThreadStatusCounts] + def __init__(self, sample_interval_usec: int, *, skip_idle: bool = False) -> None: ... def collect( self, stack_frames: Sequence[InterpreterInfo] | Sequence[AwaitedInfo], timestamps_us: _Timestamps = None @@ -33,8 +67,21 @@ class FlamegraphCollector(StackTraceCollector): mode: int | None = None, ) -> None: ... def set_replay_stats(self, info: SupportsGet[str, float | None]) -> None: ... + def set_mode(self, mode: int | None) -> None: ... def export(self, filename: StrOrBytesPath) -> None: ... def process_frames(self, frames: Sequence[_Frame], thread_id: int, weight: int = 1) -> None: ... class DiffFlamegraphCollector(FlamegraphCollector): - def __init__(self, sample_interval_usec: int, *, baseline_binary_path: StrOrBytesPath, skip_idle: bool = False) -> None: ... + baseline_binary_path: StrOrBytesPath + mode: int | None + capture_config: SupportsKeysAndGet[_CaptureFeatureKeys, bool] | None + + def __init__( + self, + sample_interval_usec: int, + *, + baseline_binary_path: StrOrBytesPath, + skip_idle: bool = False, + mode: int | None = None, + capture_config: SupportsKeysAndGet[_CaptureFeatureKeys, bool] | None = None, + ) -> None: ... diff --git a/mypy/typeshed/stdlib/pstats.pyi b/mypy/typeshed/stdlib/pstats.pyi index 19eb683df1666..8f244fde02c36 100644 --- a/mypy/typeshed/stdlib/pstats.pyi +++ b/mypy/typeshed/stdlib/pstats.pyi @@ -61,15 +61,15 @@ class Stats: sort_arg_dict_default: _SortArgDict def __init__( self, - arg: None | str | Profile | _cProfile = None, + arg: str | Profile | _cProfile | None = None, /, - *args: None | str | Profile | _cProfile | Self, + *args: str | Profile | _cProfile | Self | None, stream: IO[Any] | None = None, ) -> None: ... - def init(self, arg: None | str | Profile | _cProfile) -> None: ... - def load_stats(self, arg: None | str | Profile | _cProfile) -> None: ... + def init(self, arg: str | Profile | _cProfile | None) -> None: ... + def load_stats(self, arg: str | Profile | _cProfile | None) -> None: ... def get_top_level_stats(self) -> None: ... - def add(self, *arg_list: None | str | Profile | _cProfile | Self) -> Self: ... + def add(self, *arg_list: str | Profile | _cProfile | Self | None) -> Self: ... def dump_stats(self, filename: StrOrBytesPath) -> None: ... def get_sort_arg_defs(self) -> _SortArgDict: ... diff --git a/mypy/typeshed/stdlib/readline.pyi b/mypy/typeshed/stdlib/readline.pyi index aff1e504a174a..c981463e3df21 100644 --- a/mypy/typeshed/stdlib/readline.pyi +++ b/mypy/typeshed/stdlib/readline.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import StrOrBytesPath from collections.abc import Callable, Sequence -from typing import Literal, TypeAlias +from typing import Literal, SupportsIndex, TypeAlias if sys.platform != "win32": _Completer: TypeAlias = Callable[[str, int], str | None] @@ -19,7 +19,7 @@ if sys.platform != "win32": def set_history_length(length: int, /) -> None: ... def clear_history() -> None: ... def get_current_history_length() -> int: ... - def get_history_item(index: int, /) -> str: ... + def get_history_item(index: SupportsIndex, /) -> str | None: ... def remove_history_item(pos: int, /) -> None: ... def replace_history_item(pos: int, line: str, /) -> None: ... def add_history(string: str, /) -> None: ... diff --git a/mypy/typeshed/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi index 5919106f3ed9a..920157948ada6 100644 --- a/mypy/typeshed/stdlib/shutil.pyi +++ b/mypy/typeshed/stdlib/shutil.pyi @@ -73,7 +73,7 @@ def copytree( src: StrPath, dst: _StrPathT, symlinks: bool = False, - ignore: None | Callable[[str, list[str]], Iterable[str]] | Callable[[StrPath, list[str]], Iterable[str]] = None, + ignore: Callable[[str, list[str]], Iterable[str]] | Callable[[StrPath, list[str]], Iterable[str]] | None = None, copy_function: Callable[[str, str], object] = ..., ignore_dangling_symlinks: bool = False, dirs_exist_ok: bool = False, diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index 0790069c115cc..2f889d4ffc9bb 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -59,7 +59,7 @@ if sys.platform == "win32": # reveal_type(x) # bytes, based on the overloads # except TimeoutError as e: # reveal_type(e.cmd) # Any, but morally is _CMD -_FILE: TypeAlias = None | int | IO[Any] +_FILE: TypeAlias = int | IO[Any] | None _InputString: TypeAlias = ReadableBuffer | str _CMD: TypeAlias = StrOrBytesPath | Sequence[StrOrBytesPath] if sys.platform == "win32": @@ -518,6 +518,7 @@ if sys.version_info >= (3, 11): pass_fds: Collection[int] = (), *, encoding: str | None = None, + errors: str | None = None, timeout: float | None = None, text: bool | None = None, user: str | int | None = None, @@ -550,6 +551,7 @@ else: pass_fds: Collection[int] = (), *, encoding: str | None = None, + errors: str | None = None, timeout: float | None = None, text: bool | None = None, user: str | int | None = None, @@ -583,6 +585,7 @@ if sys.version_info >= (3, 11): timeout: float | None = None, *, encoding: str | None = None, + errors: str | None = None, text: bool | None = None, user: str | int | None = None, group: str | int | None = None, @@ -615,6 +618,7 @@ else: timeout: float | None = None, *, encoding: str | None = None, + errors: str | None = None, text: bool | None = None, user: str | int | None = None, group: str | int | None = None, diff --git a/mypy/typeshed/stdlib/termios.pyi b/mypy/typeshed/stdlib/termios.pyi index 971c9ad46bf45..5d9c81ed54887 100644 --- a/mypy/typeshed/stdlib/termios.pyi +++ b/mypy/typeshed/stdlib/termios.pyi @@ -186,12 +186,14 @@ if sys.platform != "win32": EXTPROC: Final[int] IUTF8: Final[int] - if sys.platform == "darwin" and sys.version_info >= (3, 13): - ALTWERASE: Final[int] + # On Linux, only available when Python was built against glibc 2.42 or newer. B14400: Final[int] B28800: Final[int] B7200: Final[int] B76800: Final[int] + + if sys.platform == "darwin" and sys.version_info >= (3, 13): + ALTWERASE: Final[int] CCAR_OFLOW: Final[int] CCTS_OFLOW: Final[int] CDSR_OFLOW: Final[int] @@ -274,6 +276,8 @@ if sys.platform != "win32": B460800: Final[int] B500000: Final[int] B921600: Final[int] + # On Linux, only available when Python was built against glibc 2.42 or newer. + IBSHIFT: Final[int] if sys.platform != "linux": TCSASOFT: Final[int] @@ -286,7 +290,6 @@ if sys.platform != "win32": CNUL: Final[int] COMMON: Final[int] CSWTCH: Final[int] - IBSHIFT: Final[int] INIT_C_CC: Final[int] NSWTCH: Final[int] diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index 457cf609da8cc..39aaa7e9685f8 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -603,6 +603,10 @@ if sys.version_info >= (3, 15): def __len__(self) -> int: ... def __contains__(self, key: object, /) -> bool: ... def __reversed__(self) -> Iterator[str]: ... + def __or__(self, other: dict[str, Any] | FrameLocalsProxyType, /) -> dict[str, Any]: ... + # Will raise a NameError if invoked via |= + def __ior__(self, other: dict[str, Any] | FrameLocalsProxyType, /) -> dict[str, Any]: ... # noqa: Y034 + def __ror__(self, other: dict[str, Any] | FrameLocalsProxyType, /) -> dict[str, Any]: ... def copy(self) -> dict[str, Any]: ... def pop(self, key: str, default: Any = ..., /) -> Any: ... def setdefault(self, key: str, default: Any = ..., /) -> Any: ... diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 1da103adb0920..10561b3271c5e 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -1,7 +1,7 @@ # Since this module defines "overload" it is not recognized by Ruff as typing.overload # TODO: The collections import is required, otherwise mypy crashes. # https://github.com/python/mypy/issues/16744 -import collections # noqa: F401 # pyright: ignore[reportUnusedImport] +import collections # ruff: ignore[unused-import] # pyright: ignore[reportUnusedImport] import sys import typing_extensions from _collections_abc import dict_items, dict_keys, dict_values diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index 69dceba1476e5..49ddbc2f24bf9 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -30,7 +30,7 @@ from collections.abc import ( from contextlib import AbstractAsyncContextManager as AsyncContextManager, AbstractContextManager as ContextManager from re import Match as Match, Pattern as Pattern from types import GenericAlias, ModuleType, UnionType -from typing import ( # noqa: Y022,Y037,Y038,Y039,UP035 +from typing import ( # noqa: Y022,Y037,Y038,Y039 # ruff: ignore[deprecated-import] IO as IO, TYPE_CHECKING as TYPE_CHECKING, AbstractSet as AbstractSet, @@ -541,7 +541,7 @@ else: self, name: str, *, - bound: None | AnnotationForm | str = None, + bound: AnnotationForm | str | None = None, contravariant: bool = False, covariant: bool = False, default: AnnotationForm = ..., @@ -650,7 +650,10 @@ class _NoExtraItemsType: ... NoExtraItems: _NoExtraItemsType # PEP 747 -TypeForm: _SpecialForm +if sys.version_info >= (3, 15): + from typing import TypeForm as TypeForm +else: + TypeForm: _SpecialForm # PEP 649/749 if sys.version_info >= (3, 14): diff --git a/mypy/typeshed/stdlib/unittest/main.pyi b/mypy/typeshed/stdlib/unittest/main.pyi index 09b547cd1cd6c..87200bd02b053 100644 --- a/mypy/typeshed/stdlib/unittest/main.pyi +++ b/mypy/typeshed/stdlib/unittest/main.pyi @@ -48,7 +48,7 @@ class TestProgram: else: def __init__( self, - module: None | str | ModuleType = "__main__", + module: str | ModuleType | None = "__main__", defaultTest: str | Iterable[str] | None = None, argv: list[str] | None = None, testRunner: type[_TestRunner] | _TestRunner | None = None, diff --git a/mypy/typeshed/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi index a7a0eec39136d..de88e30f0fe33 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -544,10 +544,10 @@ if sys.version_info >= (3, 13): class ThreadingMixin(Base): DEFAULT_TIMEOUT: Final[float | None] = None - def __init__(self, /, *args: Any, timeout: float | None | _SentinelObject = ..., **kwargs: Any) -> None: ... + def __init__(self, /, *args: Any, timeout: float | _SentinelObject | None = ..., **kwargs: Any) -> None: ... # Same as `NonCallableMock.reset_mock.` def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ... - def wait_until_called(self, *, timeout: float | None | _SentinelObject = ...) -> None: ... + def wait_until_called(self, *, timeout: float | _SentinelObject | None = ...) -> None: ... def wait_until_any_call_with(self, *args: Any, **kwargs: Any) -> None: ... class ThreadingMock(ThreadingMixin, MagicMixin, Mock): ... diff --git a/mypy/typeshed/stdlib/urllib/parse.pyi b/mypy/typeshed/stdlib/urllib/parse.pyi index b83a0f4e8678c..a3250b4092f0d 100644 --- a/mypy/typeshed/stdlib/urllib/parse.pyi +++ b/mypy/typeshed/stdlib/urllib/parse.pyi @@ -238,7 +238,7 @@ def urljoin(base: AnyStr, url: AnyStr | None, allow_fragments: bool = True) -> A def urlparse(url: str, scheme: str = "", allow_fragments: bool = True) -> ParseResult: ... @overload def urlparse( - url: bytes | bytearray | None, scheme: bytes | bytearray | None | Literal[""] = "", allow_fragments: bool = True + url: bytes | bytearray | None, scheme: bytes | bytearray | Literal[""] | None = "", allow_fragments: bool = True ) -> ParseResultBytes: ... if sys.version_info >= (3, 15): @overload @@ -252,7 +252,7 @@ if sys.version_info >= (3, 15): @overload def urlparse( url: bytes | bytearray | None, - scheme: bytes | bytearray | None | Literal[""] = "", + scheme: bytes | bytearray | Literal[""] | None = "", allow_fragments: bool = True, *, missing_as_none: Literal[True], @@ -260,7 +260,7 @@ if sys.version_info >= (3, 15): @overload def urlparse( url: bytes | bytearray | None, - scheme: bytes | bytearray | None | Literal[""] = "", + scheme: bytes | bytearray | Literal[""] | None = "", allow_fragments: bool = True, *, missing_as_none: Literal[False] = False, @@ -272,7 +272,7 @@ if sys.version_info >= (3, 15): @overload def urlparse( url: bytes | bytearray | None, - scheme: bytes | bytearray | None | Literal[""] = "", + scheme: bytes | bytearray | Literal[""] | None = "", allow_fragments: bool = True, *, missing_as_none: bool, @@ -284,12 +284,12 @@ def urlsplit(url: str, scheme: str = "", allow_fragments: bool = True) -> SplitR if sys.version_info >= (3, 11): @overload def urlsplit( - url: bytes | None, scheme: bytes | None | Literal[""] = "", allow_fragments: bool = True + url: bytes | None, scheme: bytes | Literal[""] | None = "", allow_fragments: bool = True ) -> SplitResultBytes: ... else: @overload def urlsplit( - url: bytes | bytearray | None, scheme: bytes | bytearray | None | Literal[""] = "", allow_fragments: bool = True + url: bytes | bytearray | None, scheme: bytes | bytearray | Literal[""] | None = "", allow_fragments: bool = True ) -> SplitResultBytes: ... if sys.version_info >= (3, 15): @overload @@ -303,7 +303,7 @@ if sys.version_info >= (3, 15): @overload def urlsplit( url: bytes | None, - scheme: bytes | None | Literal[""] = "", + scheme: bytes | Literal[""] | None = "", allow_fragments: bool = True, *, missing_as_none: Literal[True], @@ -311,7 +311,7 @@ if sys.version_info >= (3, 15): @overload def urlsplit( url: bytes | None, - scheme: bytes | None | Literal[""] = "", + scheme: bytes | Literal[""] | None = "", allow_fragments: bool = True, *, missing_as_none: Literal[False] = False, @@ -322,7 +322,7 @@ if sys.version_info >= (3, 15): ) -> SplitResult[str | None]: ... @overload def urlsplit( - url: bytes | None, scheme: bytes | None | Literal[""] = "", allow_fragments: bool = True, *, missing_as_none: bool + url: bytes | None, scheme: bytes | Literal[""] | None = "", allow_fragments: bool = True, *, missing_as_none: bool ) -> SplitResultBytes[bytes | None]: ... if sys.version_info >= (3, 15): diff --git a/mypy/typeshed/stdlib/xml/__init__.pyi b/mypy/typeshed/stdlib/xml/__init__.pyi index 555d9b8f90a95..969712fd20b06 100644 --- a/mypy/typeshed/stdlib/xml/__init__.pyi +++ b/mypy/typeshed/stdlib/xml/__init__.pyi @@ -2,7 +2,7 @@ # valid, and causes them to be included in a star import. See #6523 import sys -__all__ = ["dom", "parsers", "sax", "etree"] # noqa: F822 # pyright: ignore[reportUnsupportedDunderAll] +__all__ = ["dom", "parsers", "sax", "etree"] # ruff: ignore[undefined-export] # pyright: ignore[reportUnsupportedDunderAll] if sys.version_info >= (3, 15): __all__ += ["is_valid_name"] # pyright: ignore[reportUnsupportedDunderAll] diff --git a/mypy/typeshed/stdlib/xmlrpc/client.pyi b/mypy/typeshed/stdlib/xmlrpc/client.pyi index 573401f18d082..3107f1cbb3772 100644 --- a/mypy/typeshed/stdlib/xmlrpc/client.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/client.pyi @@ -21,7 +21,6 @@ _Marshallable: TypeAlias = ( | str | bytes | bytearray - | None | tuple[_Marshallable, ...] # Ideally we'd use _Marshallable for list and dict, but invariance makes that impractical | list[Any] @@ -29,6 +28,7 @@ _Marshallable: TypeAlias = ( | datetime | DateTime | Binary + | None ) _XMLDate: TypeAlias = int | datetime | tuple[int, ...] | time.struct_time _HostType: TypeAlias = tuple[str, dict[str, str]] | str diff --git a/mypy/typeshed/stdlib/zlib.pyi b/mypy/typeshed/stdlib/zlib.pyi index 557fa761feebf..b507770601d9b 100644 --- a/mypy/typeshed/stdlib/zlib.pyi +++ b/mypy/typeshed/stdlib/zlib.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import ReadableBuffer -from typing import Any, Final, final, type_check_only +from typing import Any, Final, SupportsIndex, final, type_check_only from typing_extensions import Self DEFLATED: Final = 8 @@ -58,7 +58,7 @@ class _Decompress: def flush(self, length: int = 16384, /) -> bytes: ... def copy(self) -> _Decompress: ... -def adler32(data: ReadableBuffer, value: int = 1, /) -> int: ... +def adler32(data: ReadableBuffer, value: SupportsIndex = 1, /) -> int: ... if sys.version_info >= (3, 15): def adler32_combine(adler1: int, adler2: int, len2: int, /) -> int: ... @@ -72,7 +72,7 @@ else: def compressobj( level: int = -1, method: int = 8, wbits: int = 15, memLevel: int = 8, strategy: int = 0, zdict: ReadableBuffer | None = None ) -> _Compress: ... -def crc32(data: ReadableBuffer, value: int = 0, /) -> int: ... +def crc32(data: ReadableBuffer, value: SupportsIndex = 0, /) -> int: ... if sys.version_info >= (3, 15): def crc32_combine(crc1: int, crc2: int, len2: int, /) -> int: ...