diff --git a/mypy/typeshed/stdlib/VERSIONS b/mypy/typeshed/stdlib/VERSIONS index ed23ee6ddcea..1d04b47c77bc 100644 --- a/mypy/typeshed/stdlib/VERSIONS +++ b/mypy/typeshed/stdlib/VERSIONS @@ -22,6 +22,7 @@ __main__: 3.0- _ast: 3.0- _asyncio: 3.0- _bisect: 3.0- +_blake2: 3.6- _bootlocale: 3.4-3.9 _codecs: 3.0- _collections_abc: 3.3- diff --git a/mypy/typeshed/stdlib/_blake2.pyi b/mypy/typeshed/stdlib/_blake2.pyi new file mode 100644 index 000000000000..10d7019a222f --- /dev/null +++ b/mypy/typeshed/stdlib/_blake2.pyi @@ -0,0 +1,117 @@ +import sys +from _typeshed import ReadableBuffer +from typing import ClassVar, final +from typing_extensions import Self + +BLAKE2B_MAX_DIGEST_SIZE: int = 64 +BLAKE2B_MAX_KEY_SIZE: int = 64 +BLAKE2B_PERSON_SIZE: int = 16 +BLAKE2B_SALT_SIZE: int = 16 +BLAKE2S_MAX_DIGEST_SIZE: int = 32 +BLAKE2S_MAX_KEY_SIZE: int = 32 +BLAKE2S_PERSON_SIZE: int = 8 +BLAKE2S_SALT_SIZE: int = 8 + +@final +class blake2b: + MAX_DIGEST_SIZE: ClassVar[int] = 64 + MAX_KEY_SIZE: ClassVar[int] = 64 + PERSON_SIZE: ClassVar[int] = 16 + SALT_SIZE: ClassVar[int] = 16 + block_size: int + digest_size: int + name: str + if sys.version_info >= (3, 9): + def __init__( + self, + 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, + ) -> None: ... + else: + def __init__( + self, + 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, + ) -> None: ... + + def copy(self) -> Self: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, data: ReadableBuffer, /) -> None: ... + +@final +class blake2s: + MAX_DIGEST_SIZE: ClassVar[int] = 32 + MAX_KEY_SIZE: ClassVar[int] = 32 + PERSON_SIZE: ClassVar[int] = 8 + SALT_SIZE: ClassVar[int] = 8 + block_size: int + digest_size: int + name: str + if sys.version_info >= (3, 9): + def __init__( + self, + 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, + ) -> None: ... + else: + def __init__( + self, + 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, + ) -> None: ... + + def copy(self) -> Self: ... + def digest(self) -> bytes: ... + def hexdigest(self) -> str: ... + def update(self, data: ReadableBuffer, /) -> None: ... diff --git a/mypy/typeshed/stdlib/_interpreters.pyi b/mypy/typeshed/stdlib/_interpreters.pyi index 75f661a7e8e1..a57ef13c6d0f 100644 --- a/mypy/typeshed/stdlib/_interpreters.pyi +++ b/mypy/typeshed/stdlib/_interpreters.pyi @@ -7,7 +7,7 @@ _Configs: TypeAlias = Literal["default", "isolated", "legacy", "empty", ""] class InterpreterError(Exception): ... class InterpreterNotFoundError(InterpreterError): ... -class NotShareableError(Exception): ... +class NotShareableError(ValueError): ... class CrossInterpreterBufferView: def __buffer__(self, flags: int, /) -> memoryview: ... diff --git a/mypy/typeshed/stdlib/_io.pyi b/mypy/typeshed/stdlib/_io.pyi index e8290daad106..ccd47726f356 100644 --- a/mypy/typeshed/stdlib/_io.pyi +++ b/mypy/typeshed/stdlib/_io.pyi @@ -86,19 +86,24 @@ class BytesIO(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] class BufferedReader(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes raw: RawIOBase - def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... + def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ... def peek(self, size: int = 0, /) -> bytes: ... class BufferedWriter(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of writelines in the base classes raw: RawIOBase - def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... + def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ... def write(self, buffer: ReadableBuffer, /) -> int: ... -class BufferedRandom(BufferedReader, BufferedWriter, BufferedIOBase, _BufferedIOBase): # type: ignore[misc] # incompatible definitions of methods in the base classes +class BufferedRandom(BufferedIOBase, _BufferedIOBase, BinaryIO): # type: ignore[misc] # incompatible definitions of methods in the base classes + mode: str + name: Any + raw: RawIOBase + def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ... def seek(self, target: int, whence: int = 0, /) -> int: ... # stubtest needs this + def peek(self, size: int = 0, /) -> bytes: ... class BufferedRWPair(BufferedIOBase, _BufferedIOBase): - def __init__(self, reader: RawIOBase, writer: RawIOBase, buffer_size: int = ...) -> None: ... + def __init__(self, reader: RawIOBase, writer: RawIOBase, buffer_size: int = 8192) -> None: ... def peek(self, size: int = ..., /) -> bytes: ... class _TextIOBase(_IOBase): @@ -173,19 +178,23 @@ class TextIOWrapper(TextIOBase, _TextIOBase, TextIO, Generic[_BufferT_co]): # t # operations. def seek(self, cookie: int, whence: int = 0, /) -> int: ... -class StringIO(TextIOWrapper, TextIOBase, _TextIOBase): # type: ignore[misc] # incompatible definitions of write in the base classes +class StringIO(TextIOBase, _TextIOBase, TextIO): # type: ignore[misc] # incompatible definitions of write in the base classes def __init__(self, initial_value: str | None = ..., newline: str | None = ...) -> None: ... # StringIO does not contain a "name" field. This workaround is necessary # to allow StringIO sub-classes to add this field, as it is defined # as a read-only property on IO[]. name: Any def getvalue(self) -> str: ... + @property + def line_buffering(self) -> bool: ... -class IncrementalNewlineDecoder(codecs.IncrementalDecoder): +class IncrementalNewlineDecoder: def __init__(self, decoder: codecs.IncrementalDecoder | None, translate: bool, errors: str = ...) -> None: ... def decode(self, input: ReadableBuffer | str, final: bool = False) -> str: ... @property def newlines(self) -> str | tuple[str, ...] | None: ... + def getstate(self) -> tuple[bytes, int]: ... + def reset(self) -> None: ... def setstate(self, state: tuple[bytes, int], /) -> None: ... if sys.version_info >= (3, 10): diff --git a/mypy/typeshed/stdlib/ast.pyi b/mypy/typeshed/stdlib/ast.pyi index 3a43d62a3a60..351a4af2fb75 100644 --- a/mypy/typeshed/stdlib/ast.pyi +++ b/mypy/typeshed/stdlib/ast.pyi @@ -2023,11 +2023,18 @@ class NodeVisitor: def visit_AugLoad(self, node: AugLoad) -> Any: ... def visit_AugStore(self, node: AugStore) -> Any: ... def visit_Param(self, node: Param) -> Any: ... - def visit_Num(self, node: Num) -> Any: ... - def visit_Str(self, node: Str) -> Any: ... - def visit_Bytes(self, node: Bytes) -> Any: ... - def visit_NameConstant(self, node: NameConstant) -> Any: ... - def visit_Ellipsis(self, node: Ellipsis) -> Any: ... + + if sys.version_info < (3, 14): + @deprecated("Replaced by visit_Constant; removed in Python 3.14") + def visit_Num(self, node: Num) -> Any: ... # type: ignore[deprecated] + @deprecated("Replaced by visit_Constant; removed in Python 3.14") + def visit_Str(self, node: Str) -> Any: ... # type: ignore[deprecated] + @deprecated("Replaced by visit_Constant; removed in Python 3.14") + def visit_Bytes(self, node: Bytes) -> Any: ... # type: ignore[deprecated] + @deprecated("Replaced by visit_Constant; removed in Python 3.14") + def visit_NameConstant(self, node: NameConstant) -> Any: ... # type: ignore[deprecated] + @deprecated("Replaced by visit_Constant; removed in Python 3.14") + def visit_Ellipsis(self, node: Ellipsis) -> Any: ... # type: ignore[deprecated] class NodeTransformer(NodeVisitor): def generic_visit(self, node: AST) -> AST: ... diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index 47d1bb13e4a3..d1ff7d425ba4 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -7,7 +7,7 @@ from _asyncio import ( _register_task as _register_task, _unregister_task as _unregister_task, ) -from collections.abc import Awaitable, Coroutine, Generator, Iterable, Iterator +from collections.abc import AsyncIterator, Awaitable, Coroutine, Generator, Iterable, Iterator from typing import Any, Literal, Protocol, TypeVar, overload from typing_extensions import TypeAlias @@ -84,7 +84,12 @@ FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION ALL_COMPLETED = concurrent.futures.ALL_COMPLETED -if sys.version_info >= (3, 10): +if sys.version_info >= (3, 13): + class _SyncAndAsyncIterator(Iterator[_T_co], AsyncIterator[_T_co], Protocol[_T_co]): ... + + def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> _SyncAndAsyncIterator[Future[_T]]: ... + +elif sys.version_info >= (3, 10): def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> Iterator[Future[_T]]: ... else: diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index eaa6695f7045..1db7f0edc241 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -9,6 +9,7 @@ from _typeshed import ( ConvertibleToFloat, ConvertibleToInt, FileDescriptorOrPath, + MaybeNone, OpenBinaryMode, OpenBinaryModeReading, OpenBinaryModeUpdating, @@ -93,6 +94,9 @@ _SupportsAnextT = TypeVar("_SupportsAnextT", bound=SupportsAnext[Any], covariant _AwaitableT = TypeVar("_AwaitableT", bound=Awaitable[Any]) _AwaitableT_co = TypeVar("_AwaitableT_co", bound=Awaitable[Any], covariant=True) _P = ParamSpec("_P") +_StartT = TypeVar("_StartT", covariant=True, default=Any) +_StopT = TypeVar("_StopT", covariant=True, default=Any) +_StepT = TypeVar("_StepT", covariant=True, default=Any) class object: __doc__: str | None @@ -786,7 +790,7 @@ class memoryview(Sequence[_I]): @overload def __setitem__(self, key: slice, value: ReadableBuffer, /) -> None: ... @overload - def __setitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], value: SupportsIndex, /) -> None: ... + def __setitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], value: _I, /) -> None: ... if sys.version_info >= (3, 10): def tobytes(self, order: Literal["C", "F", "A"] | None = "C") -> bytes: ... else: @@ -838,22 +842,31 @@ class bool(int): def __invert__(self) -> int: ... @final -class slice: +class slice(Generic[_StartT, _StopT, _StepT]): @property - def start(self) -> Any: ... + def start(self) -> _StartT: ... @property - def step(self) -> Any: ... + def step(self) -> _StepT: ... @property - def stop(self) -> Any: ... + def stop(self) -> _StopT: ... @overload - def __new__(cls, stop: Any, /) -> Self: ... + def __new__(cls, stop: int | None, /) -> slice[int | MaybeNone, int | MaybeNone, int | MaybeNone]: ... @overload - def __new__(cls, start: Any, stop: Any, step: Any = ..., /) -> Self: ... + def __new__( + cls, start: int | None, stop: int | None, step: int | None = None, / + ) -> slice[int | MaybeNone, int | MaybeNone, int | MaybeNone]: ... + @overload + def __new__(cls, stop: _T2, /) -> slice[Any, _T2, Any]: ... + @overload + def __new__(cls, start: _T1, stop: _T2, /) -> slice[_T1, _T2, Any]: ... + @overload + def __new__(cls, start: _T1, stop: _T2, step: _T3, /) -> slice[_T1, _T2, _T3]: ... def __eq__(self, value: object, /) -> bool: ... if sys.version_info >= (3, 12): def __hash__(self) -> int: ... else: __hash__: ClassVar[None] # type: ignore[assignment] + def indices(self, len: SupportsIndex, /) -> tuple[int, int, int]: ... class tuple(Sequence[_T_co]): @@ -1117,7 +1130,7 @@ class frozenset(AbstractSet[_T_co]): if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any, /) -> GenericAlias: ... -class enumerate(Iterator[tuple[int, _T]]): +class enumerate(Generic[_T]): def __new__(cls, iterable: Iterable[_T], start: int = 0) -> Self: ... def __iter__(self) -> Self: ... def __next__(self) -> tuple[int, _T]: ... @@ -1311,7 +1324,7 @@ else: def exit(code: sys._ExitCode = None) -> NoReturn: ... -class filter(Iterator[_T]): +class filter(Generic[_T]): @overload def __new__(cls, function: None, iterable: Iterable[_T | None], /) -> Self: ... @overload @@ -1372,7 +1385,7 @@ def len(obj: Sized, /) -> int: ... def license() -> None: ... def locals() -> dict[str, Any]: ... -class map(Iterator[_S]): +class map(Generic[_S]): @overload def __new__(cls, func: Callable[[_T1], _S], iter1: Iterable[_T1], /) -> Self: ... @overload @@ -1614,7 +1627,7 @@ def pow(base: _SupportsSomeKindOfPow, exp: float, mod: None = None) -> Any: ... def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex: ... def quit(code: sys._ExitCode = None) -> NoReturn: ... -class reversed(Iterator[_T]): +class reversed(Generic[_T]): @overload def __new__(cls, sequence: Reversible[_T], /) -> Iterator[_T]: ... # type: ignore[misc] @overload @@ -1675,7 +1688,7 @@ def vars(object: type, /) -> types.MappingProxyType[str, Any]: ... @overload def vars(object: Any = ..., /) -> dict[str, Any]: ... -class zip(Iterator[_T_co]): +class zip(Generic[_T_co]): if sys.version_info >= (3, 10): @overload def __new__(cls, *, strict: bool = ...) -> zip[Any]: ... diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index fb34251693ad..8a5b7dd6101c 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -58,9 +58,11 @@ class ContextDecorator: def _recreate_cm(self) -> Self: ... def __call__(self, func: _F) -> _F: ... -class _GeneratorContextManager(AbstractContextManager[_T_co, bool | None], ContextDecorator): +class _GeneratorContextManagerBase: ... + +class _GeneratorContextManager(_GeneratorContextManagerBase, AbstractContextManager[_T_co, bool | None], ContextDecorator): # __init__ and all instance attributes are actually inherited from _GeneratorContextManagerBase - # _GeneratorContextManagerBase is more trouble than it's worth to include in the stub; see #6676 + # adding them there is more trouble than it's worth to include in the stub; see #6676 def __init__(self, func: Callable[..., Iterator[_T_co]], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ... gen: Generator[_T_co, Any, Any] func: Callable[..., Generator[_T_co, Any, Any]] @@ -84,9 +86,11 @@ if sys.version_info >= (3, 10): def _recreate_cm(self) -> Self: ... def __call__(self, func: _AF) -> _AF: ... - class _AsyncGeneratorContextManager(AbstractAsyncContextManager[_T_co, bool | None], AsyncContextDecorator): + class _AsyncGeneratorContextManager( + _GeneratorContextManagerBase, AbstractAsyncContextManager[_T_co, bool | None], AsyncContextDecorator + ): # __init__ and these attributes are actually defined in the base class _GeneratorContextManagerBase, - # which is more trouble than it's worth to include in the stub (see #6676) + # adding them there is more trouble than it's worth to include in the stub (see #6676) def __init__(self, func: Callable[..., AsyncIterator[_T_co]], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ... gen: AsyncGenerator[_T_co, Any] func: Callable[..., AsyncGenerator[_T_co, Any]] @@ -97,7 +101,7 @@ if sys.version_info >= (3, 10): ) -> bool | None: ... else: - class _AsyncGeneratorContextManager(AbstractAsyncContextManager[_T_co, bool | None]): + class _AsyncGeneratorContextManager(_GeneratorContextManagerBase, AbstractAsyncContextManager[_T_co, bool | None]): def __init__(self, func: Callable[..., AsyncIterator[_T_co]], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ... gen: AsyncGenerator[_T_co, Any] func: Callable[..., AsyncGenerator[_T_co, Any]] diff --git a/mypy/typeshed/stdlib/distutils/_msvccompiler.pyi b/mypy/typeshed/stdlib/distutils/_msvccompiler.pyi new file mode 100644 index 000000000000..bba9373b72db --- /dev/null +++ b/mypy/typeshed/stdlib/distutils/_msvccompiler.pyi @@ -0,0 +1,13 @@ +from _typeshed import Incomplete +from distutils.ccompiler import CCompiler +from typing import ClassVar, Final + +PLAT_SPEC_TO_RUNTIME: Final[dict[str, str]] +PLAT_TO_VCVARS: Final[dict[str, str]] + +class MSVCCompiler(CCompiler): + compiler_type: ClassVar[str] + executables: ClassVar[dict[Incomplete, Incomplete]] + res_extension: ClassVar[str] + initialized: bool + def initialize(self, plat_name: str | None = None) -> None: ... diff --git a/mypy/typeshed/stdlib/email/message.pyi b/mypy/typeshed/stdlib/email/message.pyi index f04b014431f9..ebad05a1cf7b 100644 --- a/mypy/typeshed/stdlib/email/message.pyi +++ b/mypy/typeshed/stdlib/email/message.pyi @@ -1,3 +1,4 @@ +from _typeshed import MaybeNone from collections.abc import Generator, Iterator, Sequence from email import _ParamsType, _ParamType from email.charset import Charset @@ -42,17 +43,17 @@ class Message(Generic[_HeaderT, _HeaderParamT]): def get_unixfrom(self) -> str | None: ... def attach(self, payload: _PayloadType) -> None: ... # `i: int` without a multipart payload results in an error - # `| Any`: can be None for cleared or unset payload, but annoying to check + # `| MaybeNone` acts like `| Any`: can be None for cleared or unset payload, but annoying to check @overload # multipart def get_payload(self, i: int, decode: Literal[True]) -> None: ... @overload # multipart - def get_payload(self, i: int, decode: Literal[False] = False) -> _PayloadType | Any: ... + def get_payload(self, i: int, decode: Literal[False] = False) -> _PayloadType | MaybeNone: ... @overload # either - def get_payload(self, i: None = None, decode: Literal[False] = False) -> _PayloadType | _MultipartPayloadType | Any: ... + def get_payload(self, i: None = None, decode: Literal[False] = False) -> _PayloadType | _MultipartPayloadType | MaybeNone: ... @overload # not multipart - def get_payload(self, i: None = None, *, decode: Literal[True]) -> _EncodedPayloadType | Any: ... + def get_payload(self, i: None = None, *, decode: Literal[True]) -> _EncodedPayloadType | MaybeNone: ... @overload # not multipart, IDEM but w/o kwarg - def get_payload(self, i: None, decode: Literal[True]) -> _EncodedPayloadType | Any: ... + def get_payload(self, i: None, decode: Literal[True]) -> _EncodedPayloadType | MaybeNone: ... # If `charset=None` and payload supports both `encode` AND `decode`, # then an invalid payload could be passed, but this is unlikely # Not[_SupportsEncodeToPayload] @@ -75,7 +76,7 @@ class Message(Generic[_HeaderT, _HeaderParamT]): # This is important for protocols using __getitem__, like SupportsKeysAndGetItem # Morally, the return type should be `AnyOf[_HeaderType, None]`, # so using "the Any trick" instead. - def __getitem__(self, name: str) -> _HeaderT | Any: ... + def __getitem__(self, name: str) -> _HeaderT | MaybeNone: ... def __setitem__(self, name: str, val: _HeaderParamT) -> None: ... def __delitem__(self, name: str) -> None: ... def keys(self) -> list[str]: ... diff --git a/mypy/typeshed/stdlib/email/policy.pyi b/mypy/typeshed/stdlib/email/policy.pyi index 5adf4a8c2390..5b145bcf2318 100644 --- a/mypy/typeshed/stdlib/email/policy.pyi +++ b/mypy/typeshed/stdlib/email/policy.pyi @@ -3,6 +3,7 @@ from email._policybase import Compat32 as Compat32, Policy as Policy, _MessageFa from email.contentmanager import ContentManager from email.message import EmailMessage, Message from typing import Any, TypeVar, overload +from typing_extensions import Self __all__ = ["Compat32", "compat32", "Policy", "EmailPolicy", "default", "strict", "SMTP", "HTTP"] @@ -23,6 +24,8 @@ 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 + verify_generated_headers: bool = ..., utf8: bool = ..., refold_source: str = ..., header_factory: Callable[[str, str], str] = ..., @@ -38,6 +41,8 @@ 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 + verify_generated_headers: bool = ..., utf8: bool = ..., refold_source: str = ..., header_factory: Callable[[str, str], str] = ..., @@ -48,6 +53,22 @@ class EmailPolicy(Policy[_MessageT]): def header_fetch_parse(self, name: str, value: str) -> Any: ... def fold(self, name: str, value: str) -> Any: ... def fold_binary(self, name: str, value: str) -> bytes: ... + def clone( + self, + *, + max_line_length: int | None = ..., + linesep: str = ..., + cte_type: str = ..., + 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 + verify_generated_headers: bool = ..., + utf8: bool = ..., + refold_source: str = ..., + header_factory: Callable[[str, str], str] = ..., + content_manager: ContentManager = ..., + ) -> Self: ... default: EmailPolicy[EmailMessage] SMTP: EmailPolicy[EmailMessage] diff --git a/mypy/typeshed/stdlib/hashlib.pyi b/mypy/typeshed/stdlib/hashlib.pyi index 93bd986c9d31..74687d9abe3d 100644 --- a/mypy/typeshed/stdlib/hashlib.pyi +++ b/mypy/typeshed/stdlib/hashlib.pyi @@ -1,7 +1,8 @@ import sys +from _blake2 import blake2b as blake2b, blake2s as blake2s from _typeshed import ReadableBuffer from collections.abc import Callable, Set as AbstractSet -from typing import Protocol, final +from typing import Protocol from typing_extensions import Self if sys.version_info >= (3, 11): @@ -55,12 +56,20 @@ class _Hash: def block_size(self) -> int: ... @property def name(self) -> str: ... - def __init__(self, data: ReadableBuffer = ...) -> None: ... def copy(self) -> Self: ... def digest(self) -> bytes: ... def hexdigest(self) -> str: ... def update(self, data: ReadableBuffer, /) -> None: ... +class _VarLenHash: + digest_size: int + block_size: int + name: str + def copy(self) -> _VarLenHash: ... + def digest(self, length: int, /) -> bytes: ... + def hexdigest(self, length: int, /) -> str: ... + def update(self, data: ReadableBuffer, /) -> None: ... + if sys.version_info >= (3, 9): def new(name: str, data: ReadableBuffer = b"", *, usedforsecurity: bool = ...) -> _Hash: ... def md5(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _Hash: ... @@ -69,6 +78,12 @@ if sys.version_info >= (3, 9): def sha256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _Hash: ... def sha384(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _Hash: ... def sha512(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _Hash: ... + def sha3_224(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _Hash: ... + def sha3_256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _Hash: ... + def sha3_384(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _Hash: ... + def sha3_512(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _Hash: ... + def shake_128(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _VarLenHash: ... + def shake_256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _VarLenHash: ... else: def new(name: str, data: ReadableBuffer = b"") -> _Hash: ... @@ -78,6 +93,12 @@ else: def sha256(string: ReadableBuffer = b"") -> _Hash: ... def sha384(string: ReadableBuffer = b"") -> _Hash: ... def sha512(string: ReadableBuffer = b"") -> _Hash: ... + 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: ... algorithms_guaranteed: AbstractSet[str] algorithms_available: AbstractSet[str] @@ -85,74 +106,9 @@ algorithms_available: AbstractSet[str] def pbkdf2_hmac( hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: int | None = None ) -> bytes: ... - -class _VarLenHash: - digest_size: int - block_size: int - name: str - def __init__(self, data: ReadableBuffer = ...) -> None: ... - def copy(self) -> _VarLenHash: ... - def digest(self, length: int, /) -> bytes: ... - def hexdigest(self, length: int, /) -> str: ... - def update(self, data: ReadableBuffer, /) -> None: ... - -sha3_224 = _Hash -sha3_256 = _Hash -sha3_384 = _Hash -sha3_512 = _Hash -shake_128 = _VarLenHash -shake_256 = _VarLenHash - def scrypt( password: ReadableBuffer, *, salt: ReadableBuffer, n: int, r: int, p: int, maxmem: int = 0, dklen: int = 64 ) -> bytes: ... -@final -class _BlakeHash(_Hash): - MAX_DIGEST_SIZE: int - MAX_KEY_SIZE: int - PERSON_SIZE: int - SALT_SIZE: int - - if sys.version_info >= (3, 9): - def __init__( - self, - data: ReadableBuffer = ..., - /, - *, - digest_size: int = ..., - key: ReadableBuffer = ..., - salt: ReadableBuffer = ..., - person: ReadableBuffer = ..., - fanout: int = ..., - depth: int = ..., - leaf_size: int = ..., - node_offset: int = ..., - node_depth: int = ..., - inner_size: int = ..., - last_node: bool = ..., - usedforsecurity: bool = ..., - ) -> None: ... - else: - def __init__( - self, - data: ReadableBuffer = ..., - /, - *, - digest_size: int = ..., - key: ReadableBuffer = ..., - salt: ReadableBuffer = ..., - person: ReadableBuffer = ..., - fanout: int = ..., - depth: int = ..., - leaf_size: int = ..., - node_offset: int = ..., - node_depth: int = ..., - inner_size: int = ..., - last_node: bool = ..., - ) -> None: ... - -blake2b = _BlakeHash -blake2s = _BlakeHash if sys.version_info >= (3, 11): class _BytesIOLike(Protocol): diff --git a/mypy/typeshed/stdlib/http/client.pyi b/mypy/typeshed/stdlib/http/client.pyi index f47c744a6c7d..3db764ef1e7c 100644 --- a/mypy/typeshed/stdlib/http/client.pyi +++ b/mypy/typeshed/stdlib/http/client.pyi @@ -3,10 +3,10 @@ import io import ssl import sys import types -from _typeshed import ReadableBuffer, SupportsRead, SupportsReadline, WriteableBuffer +from _typeshed import MaybeNone, ReadableBuffer, SupportsRead, SupportsReadline, WriteableBuffer from collections.abc import Callable, Iterable, Iterator, Mapping from socket import socket -from typing import Any, BinaryIO, TypeVar, overload +from typing import BinaryIO, TypeVar, overload from typing_extensions import Self, TypeAlias __all__ = [ @@ -154,7 +154,7 @@ class HTTPConnection: timeout: float | None host: str port: int - sock: socket | Any # can be `None` if `.connect()` was not called + sock: socket | MaybeNone # can be `None` if `.connect()` was not called def __init__( self, host: str, @@ -187,7 +187,7 @@ class HTTPConnection: class HTTPSConnection(HTTPConnection): # Can be `None` if `.connect()` was not called: - sock: ssl.SSLSocket | Any + sock: ssl.SSLSocket | MaybeNone if sys.version_info >= (3, 12): def __init__( self, diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index 18076011178f..013c3cba120f 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import MaybeNone from collections.abc import Callable, Iterable, Iterator from typing import Any, Generic, Literal, SupportsComplex, SupportsFloat, SupportsIndex, SupportsInt, TypeVar, overload from typing_extensions import Self, TypeAlias @@ -122,7 +123,7 @@ class zip_longest(Generic[_T_co]): # In the overloads without fillvalue, all of the tuple members could theoretically be None, # but we return Any instead to avoid false positives for code where we know one of the iterables # is longer. - def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> zip_longest[tuple[_T1 | Any, _T2 | Any]]: ... + def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone]]: ... @overload def __new__( cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, fillvalue: _T @@ -131,7 +132,7 @@ class zip_longest(Generic[_T_co]): @overload def __new__( cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], / - ) -> zip_longest[tuple[_T1 | Any, _T2 | Any, _T3 | Any]]: ... + ) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone, _T3 | MaybeNone]]: ... @overload def __new__( cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /, *, fillvalue: _T @@ -140,7 +141,7 @@ class zip_longest(Generic[_T_co]): @overload def __new__( cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], / - ) -> zip_longest[tuple[_T1 | Any, _T2 | Any, _T3 | Any, _T4 | Any]]: ... + ) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone, _T3 | MaybeNone, _T4 | MaybeNone]]: ... @overload def __new__( cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /, *, fillvalue: _T @@ -149,7 +150,7 @@ class zip_longest(Generic[_T_co]): @overload def __new__( cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], / - ) -> zip_longest[tuple[_T1 | Any, _T2 | Any, _T3 | Any, _T4 | Any, _T5 | Any]]: ... + ) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone, _T3 | MaybeNone, _T4 | MaybeNone, _T5 | MaybeNone]]: ... @overload def __new__( cls, @@ -174,7 +175,7 @@ class zip_longest(Generic[_T_co]): iter6: Iterable[_T], /, *iterables: Iterable[_T], - ) -> zip_longest[tuple[_T | Any, ...]]: ... + ) -> zip_longest[tuple[_T | MaybeNone, ...]]: ... @overload def __new__( cls, diff --git a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi index b417925fb17b..d6f46b527905 100644 --- a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi @@ -1,6 +1,5 @@ import threading from collections.abc import Callable -from contextlib import AbstractContextManager from multiprocessing.context import BaseContext from types import TracebackType from typing_extensions import TypeAlias @@ -14,7 +13,7 @@ class Barrier(threading.Barrier): self, parties: int, action: Callable[[], object] | None = None, timeout: float | None = None, *ctx: BaseContext ) -> None: ... -class Condition(AbstractContextManager[bool, None]): +class Condition: def __init__(self, lock: _LockLike | None = None, *, ctx: BaseContext) -> None: ... def notify(self, n: int = 1) -> None: ... def notify_all(self) -> None: ... @@ -22,6 +21,7 @@ class Condition(AbstractContextManager[bool, None]): def wait_for(self, predicate: Callable[[], bool], timeout: float | None = None) -> bool: ... def acquire(self, block: bool = ..., timeout: float | None = ...) -> bool: ... def release(self) -> None: ... + def __enter__(self) -> bool: ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, / ) -> None: ... @@ -34,9 +34,10 @@ class Event: def wait(self, timeout: float | None = None) -> bool: ... # Not part of public API -class SemLock(AbstractContextManager[bool, None]): +class SemLock: def acquire(self, block: bool = ..., timeout: float | None = ...) -> bool: ... def release(self) -> None: ... + def __enter__(self) -> bool: ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, / ) -> None: ... diff --git a/mypy/typeshed/stdlib/optparse.pyi b/mypy/typeshed/stdlib/optparse.pyi index b513bb647060..d6db7a06f291 100644 --- a/mypy/typeshed/stdlib/optparse.pyi +++ b/mypy/typeshed/stdlib/optparse.pyi @@ -1,4 +1,4 @@ -from _typeshed import Incomplete +from _typeshed import Incomplete, MaybeNone from abc import abstractmethod from collections.abc import Callable, Iterable, Mapping, Sequence from typing import IO, Any, AnyStr, Literal, NoReturn, overload @@ -56,7 +56,7 @@ class HelpFormatter: current_indent: int default_tag: str help_position: int - help_width: int | Any # initialized as None and computed later as int when storing option strings + help_width: int | MaybeNone # initialized as None and computed later as int when storing option strings indent_increment: int level: int max_help_position: int diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 833f9b1e56cb..203956786a9b 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -1076,6 +1076,14 @@ if sys.platform != "win32": def cpu_count() -> int | None: ... +if sys.version_info >= (3, 13): + # Documented to return `int | None`, but falls back to `len(sched_getaffinity(0))` when + # available. See https://github.com/python/cpython/blob/417c130/Lib/os.py#L1175-L1186. + if sys.platform != "win32" and sys.platform != "darwin": + def process_cpu_count() -> int: ... + else: + def process_cpu_count() -> int | None: ... + if sys.platform != "win32": # Unix only def confstr(name: str | int, /) -> str | None: ... diff --git a/mypy/typeshed/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi index ac297b7d4567..b8fe2e9e1a46 100644 --- a/mypy/typeshed/stdlib/re.pyi +++ b/mypy/typeshed/stdlib/re.pyi @@ -2,7 +2,7 @@ import enum import sre_compile import sre_constants import sys -from _typeshed import ReadableBuffer +from _typeshed import MaybeNone, ReadableBuffer from collections.abc import Callable, Iterator, Mapping from typing import Any, AnyStr, Generic, Literal, TypeVar, final, overload from typing_extensions import TypeAlias @@ -90,19 +90,19 @@ class Match(Generic[AnyStr]): @overload def group(self, group: Literal[0] = 0, /) -> AnyStr: ... @overload - def group(self, group: str | int, /) -> AnyStr | Any: ... + def group(self, group: str | int, /) -> AnyStr | MaybeNone: ... @overload - def group(self, group1: str | int, group2: str | int, /, *groups: str | int) -> tuple[AnyStr | Any, ...]: ... + def group(self, group1: str | int, group2: str | int, /, *groups: str | int) -> tuple[AnyStr | MaybeNone, ...]: ... # Each item of groups()'s return tuple is either "AnyStr" or # "AnyStr | None", depending on the pattern. @overload - def groups(self) -> tuple[AnyStr | Any, ...]: ... + def groups(self) -> tuple[AnyStr | MaybeNone, ...]: ... @overload def groups(self, default: _T) -> tuple[AnyStr | _T, ...]: ... # Each value in groupdict()'s return dict is either "AnyStr" or # "AnyStr | None", depending on the pattern. @overload - def groupdict(self) -> dict[str, AnyStr | Any]: ... + def groupdict(self) -> dict[str, AnyStr | MaybeNone]: ... @overload def groupdict(self, default: _T) -> dict[str, AnyStr | _T]: ... def start(self, group: int | str = 0, /) -> int: ... @@ -114,7 +114,7 @@ class Match(Generic[AnyStr]): @overload def __getitem__(self, key: Literal[0], /) -> AnyStr: ... @overload - def __getitem__(self, key: int | str, /) -> AnyStr | Any: ... + 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): @@ -151,11 +151,11 @@ class Pattern(Generic[AnyStr]): @overload def fullmatch(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ... @overload - def split(self: Pattern[str], string: str, maxsplit: int = 0) -> list[str | Any]: ... + def split(self: Pattern[str], string: str, maxsplit: int = 0) -> list[str | MaybeNone]: ... @overload - def split(self: Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0) -> list[bytes | Any]: ... + def split(self: Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0) -> list[bytes | MaybeNone]: ... @overload - def split(self, string: AnyStr, maxsplit: int = 0) -> list[AnyStr | Any]: ... + def split(self, string: AnyStr, maxsplit: int = 0) -> list[AnyStr | MaybeNone]: ... # return type depends on the number of groups in the pattern @overload def findall(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> list[Any]: ... @@ -270,11 +270,11 @@ def fullmatch(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) - @overload def fullmatch(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ... @overload -def split(pattern: str | Pattern[str], string: str, maxsplit: int = 0, flags: _FlagsType = 0) -> list[str | Any]: ... +def split(pattern: str | Pattern[str], string: str, maxsplit: int = 0, flags: _FlagsType = 0) -> list[str | MaybeNone]: ... @overload def split( pattern: bytes | Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0, flags: _FlagsType = 0 -) -> list[bytes | Any]: ... +) -> list[bytes | MaybeNone]: ... @overload def findall(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> list[Any]: ... @overload diff --git a/mypy/typeshed/stdlib/sqlite3/__init__.pyi b/mypy/typeshed/stdlib/sqlite3/__init__.pyi index d6087aa755c1..931e8d03cb75 100644 --- a/mypy/typeshed/stdlib/sqlite3/__init__.pyi +++ b/mypy/typeshed/stdlib/sqlite3/__init__.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import ReadableBuffer, StrOrBytesPath, SupportsLenAndGetItem, Unused +from _typeshed import MaybeNone, ReadableBuffer, StrOrBytesPath, SupportsLenAndGetItem, Unused from collections.abc import Callable, Generator, Iterable, Iterator, Mapping, Sequence from sqlite3.dbapi2 import ( PARSE_COLNAMES as PARSE_COLNAMES, @@ -401,9 +401,9 @@ class Cursor: arraysize: int @property def connection(self) -> Connection: ... - # May be None, but using | Any instead to avoid slightly annoying false positives. + # May be None, but using `| MaybeNone` (`| Any`) instead to avoid slightly annoying false positives. @property - def description(self) -> tuple[tuple[str, None, None, None, None, None, None], ...] | Any: ... + def description(self) -> tuple[tuple[str, None, None, None, None, None, None], ...] | MaybeNone: ... @property def lastrowid(self) -> int | None: ... row_factory: Callable[[Cursor, Row], object] | None diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index 703a5012012c..fef35b56945a 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import ReadableBuffer, StrOrBytesPath +from _typeshed import MaybeNone, ReadableBuffer, StrOrBytesPath from collections.abc import Callable, Collection, Iterable, Mapping, Sequence from types import TracebackType from typing import IO, Any, AnyStr, Final, Generic, Literal, TypeVar, overload @@ -1848,7 +1848,7 @@ class Popen(Generic[AnyStr]): stdout: IO[AnyStr] | None stderr: IO[AnyStr] | None pid: int - returncode: int | Any + returncode: int | MaybeNone universal_newlines: bool if sys.version_info >= (3, 11): diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 4d25a04f8eb7..5d3550ea62ab 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -1,6 +1,6 @@ import _tkinter import sys -from _typeshed import Incomplete, StrEnum, StrOrBytesPath +from _typeshed import Incomplete, MaybeNone, StrEnum, StrOrBytesPath from collections.abc import Callable, Iterable, Mapping, Sequence from tkinter.constants import * from tkinter.font import _FontDescription @@ -509,7 +509,7 @@ class Misc: pad: _ScreenUnits = ..., uniform: str = ..., weight: int = ..., - ) -> _GridIndexInfo | Any: ... # can be None but annoying to check + ) -> _GridIndexInfo | MaybeNone: ... # can be None but annoying to check def grid_rowconfigure( self, index: int | str | list[int] | tuple[int, ...], @@ -519,7 +519,7 @@ class Misc: pad: _ScreenUnits = ..., uniform: str = ..., weight: int = ..., - ) -> _GridIndexInfo | Any: ... # can be None but annoying to check + ) -> _GridIndexInfo | MaybeNone: ... # can be None but annoying to check columnconfigure = grid_columnconfigure rowconfigure = grid_rowconfigure def grid_location(self, x: _ScreenUnits, y: _ScreenUnits) -> tuple[int, int]: ... diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index b851f478140a..dacef0620b22 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -1,6 +1,6 @@ import _tkinter import tkinter -from _typeshed import Incomplete +from _typeshed import Incomplete, MaybeNone from collections.abc import Callable from tkinter.font import _FontDescription from typing import Any, Literal, TypedDict, overload @@ -1156,7 +1156,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): background: str = ..., font: _FontDescription = ..., image: tkinter._ImageSpec = ..., - ) -> _TreeviewTagDict | Any: ... # can be None but annoying to check + ) -> _TreeviewTagDict | MaybeNone: ... # can be None but annoying to check @overload def tag_has(self, tagname: str, item: None = None) -> tuple[str, ...]: ... @overload diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index 0c5a43617040..ebea6f22fb12 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import SupportsKeysAndGetItem +from _typeshed import MaybeNone, SupportsKeysAndGetItem from _typeshed.importlib import LoaderProtocol from collections.abc import ( AsyncGenerator, @@ -528,9 +528,9 @@ class FrameType: def f_lasti(self) -> int: ... # see discussion in #6769: f_lineno *can* sometimes be None, # but you should probably file a bug report with CPython if you encounter it being None in the wild. - # An `int | None` annotation here causes too many false-positive errors. + # An `int | None` annotation here causes too many false-positive errors, so applying `int | Any`. @property - def f_lineno(self) -> int | Any: ... + def f_lineno(self) -> int | MaybeNone: ... @property def f_locals(self) -> dict[str, Any]: ... f_trace: Callable[[FrameType, str, Any], Any] | None diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index ce16d9adff99..27ae11daba70 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -575,7 +575,7 @@ class Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): @abstractmethod def __len__(self) -> int: ... -class Sequence(Collection[_T_co], Reversible[_T_co]): +class Sequence(Reversible[_T_co], Collection[_T_co]): @overload @abstractmethod def __getitem__(self, index: int) -> _T_co: ... @@ -760,7 +760,7 @@ TYPE_CHECKING: bool # In stubs, the arguments of the IO class are marked as positional-only. # This differs from runtime, but better reflects the fact that in reality # classes deriving from IO use different names for the arguments. -class IO(Iterator[AnyStr]): +class IO(Generic[AnyStr]): # At runtime these are all abstract properties, # but making them abstract in the stub is hugely disruptive, for not much gain. # See #8726 diff --git a/mypy/typeshed/stdlib/unittest/runner.pyi b/mypy/typeshed/stdlib/unittest/runner.pyi index be546f42315e..393d03dfa0fc 100644 --- a/mypy/typeshed/stdlib/unittest/runner.pyi +++ b/mypy/typeshed/stdlib/unittest/runner.pyi @@ -18,13 +18,16 @@ class _TextTestStream(_SupportsWriteAndFlush, Protocol): # _WritelnDecorator should have all the same attrs as its stream param. # But that's not feasible to do Generically # We can expand the attributes if requested -class _WritelnDecorator(_TextTestStream): +class _WritelnDecorator: def __init__(self, stream: _TextTestStream) -> None: ... def writeln(self, arg: str | None = None) -> str: ... def __getattr__(self, attr: str) -> Any: ... # Any attribute from the stream type passed to __init__ # These attributes are prevented by __getattr__ stream: Never __getstate__: Never + # Methods proxied from the wrapped stream object via __getattr__ + def flush(self) -> object: ... + def write(self, s: str, /) -> object: ... _StreamT = TypeVar("_StreamT", bound=_TextTestStream, default=_WritelnDecorator) diff --git a/mypy/typeshed/stdlib/warnings.pyi b/mypy/typeshed/stdlib/warnings.pyi index c7ab1cb091dd..533a36817506 100644 --- a/mypy/typeshed/stdlib/warnings.pyi +++ b/mypy/typeshed/stdlib/warnings.pyi @@ -1,3 +1,4 @@ +import re import sys from _warnings import warn as warn, warn_explicit as warn_explicit from collections.abc import Sequence @@ -25,7 +26,7 @@ if sys.version_info >= (3, 14): _ActionKind: TypeAlias = Literal["default", "error", "ignore", "always", "module", "once"] else: _ActionKind: TypeAlias = Literal["default", "error", "ignore", "always", "all", "module", "once"] -filters: Sequence[tuple[str, str | None, type[Warning], str | None, int]] # undocumented, do not mutate +filters: Sequence[tuple[str, re.Pattern[str] | None, type[Warning], re.Pattern[str] | None, int]] # undocumented, do not mutate def showwarning( message: Warning | str, diff --git a/mypy/typeshed/stdlib/zipimport.pyi b/mypy/typeshed/stdlib/zipimport.pyi index f53b09e188eb..71d4f4478c43 100644 --- a/mypy/typeshed/stdlib/zipimport.pyi +++ b/mypy/typeshed/stdlib/zipimport.pyi @@ -3,6 +3,7 @@ from _typeshed import StrOrBytesPath from importlib.abc import ResourceReader from importlib.machinery import ModuleSpec from types import CodeType, ModuleType +from typing_extensions import deprecated __all__ = ["ZipImportError", "zipimporter"] @@ -26,6 +27,7 @@ class zipimporter: def get_resource_reader(self, fullname: str) -> ResourceReader | None: ... # undocumented def get_source(self, fullname: str) -> str | None: ... def is_package(self, fullname: str) -> bool: ... + @deprecated("Deprecated since 3.10; use exec_module() instead") def load_module(self, fullname: str) -> ModuleType: ... if sys.version_info >= (3, 10): def exec_module(self, module: ModuleType) -> None: ...