From 8660d804de1515c071de087f51e3cc4db340eedb Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 23 Nov 2021 11:00:19 +0000 Subject: [PATCH 1/3] Sync typeshed Source commit: https://github.com/python/typeshed/commit/2445eddb4b67fdaa58ec7c2113ff1542021a6206 --- mypy/typeshed/stdlib/@python2/__builtin__.pyi | 11 +- mypy/typeshed/stdlib/@python2/ast.pyi | 3 +- mypy/typeshed/stdlib/@python2/builtins.pyi | 11 +- .../stdlib/@python2/ctypes/__init__.pyi | 6 +- .../stdlib/@python2/logging/__init__.pyi | 39 +- mypy/typeshed/stdlib/@python2/warnings.pyi | 3 +- mypy/typeshed/stdlib/_collections_abc.pyi | 23 + mypy/typeshed/stdlib/_thread.pyi | 3 + mypy/typeshed/stdlib/_tkinter.pyi | 4 +- mypy/typeshed/stdlib/_typeshed/__init__.pyi | 5 + mypy/typeshed/stdlib/_weakref.pyi | 3 + mypy/typeshed/stdlib/_winapi.pyi | 4 +- mypy/typeshed/stdlib/array.pyi | 34 +- mypy/typeshed/stdlib/ast.pyi | 3 +- .../stdlib/asyncio/base_subprocess.pyi | 5 +- mypy/typeshed/stdlib/asyncio/locks.pyi | 5 +- mypy/typeshed/stdlib/asyncio/protocols.pyi | 2 +- mypy/typeshed/stdlib/asyncio/sslproto.pyi | 5 +- mypy/typeshed/stdlib/asyncio/tasks.pyi | 14 +- mypy/typeshed/stdlib/bdb.pyi | 4 +- mypy/typeshed/stdlib/builtins.pyi | 779 ++++++++++-------- mypy/typeshed/stdlib/bz2.pyi | 4 +- mypy/typeshed/stdlib/cmath.pyi | 9 +- mypy/typeshed/stdlib/collections/__init__.pyi | 91 +- .../stdlib/concurrent/futures/thread.pyi | 2 +- mypy/typeshed/stdlib/contextlib.pyi | 42 +- mypy/typeshed/stdlib/ctypes/__init__.pyi | 6 +- mypy/typeshed/stdlib/datetime.pyi | 151 ++-- mypy/typeshed/stdlib/decimal.pyi | 50 +- .../stdlib/email/_header_value_parser.pyi | 24 +- mypy/typeshed/stdlib/functools.pyi | 6 +- mypy/typeshed/stdlib/http/client.pyi | 1 + mypy/typeshed/stdlib/importlib/__init__.pyi | 17 +- mypy/typeshed/stdlib/importlib/resources.pyi | 6 +- mypy/typeshed/stdlib/inspect.pyi | 53 +- mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi | 4 +- mypy/typeshed/stdlib/lzma.pyi | 4 +- mypy/typeshed/stdlib/math.pyi | 13 +- mypy/typeshed/stdlib/msilib/__init__.pyi | 10 +- .../stdlib/multiprocessing/__init__.pyi | 2 +- mypy/typeshed/stdlib/operator.pyi | 5 +- mypy/typeshed/stdlib/os/__init__.pyi | 19 +- mypy/typeshed/stdlib/pathlib.pyi | 17 +- mypy/typeshed/stdlib/pickle.pyi | 2 + mypy/typeshed/stdlib/posix.pyi | 3 + mypy/typeshed/stdlib/pyexpat/__init__.pyi | 2 + mypy/typeshed/stdlib/random.pyi | 10 +- mypy/typeshed/stdlib/reprlib.pyi | 9 +- mypy/typeshed/stdlib/shutil.pyi | 4 +- mypy/typeshed/stdlib/signal.pyi | 6 +- mypy/typeshed/stdlib/smtpd.pyi | 5 +- mypy/typeshed/stdlib/socketserver.pyi | 4 +- mypy/typeshed/stdlib/sqlite3/dbapi2.pyi | 21 + mypy/typeshed/stdlib/sre_parse.pyi | 12 +- mypy/typeshed/stdlib/sys.pyi | 11 +- mypy/typeshed/stdlib/tarfile.pyi | 4 +- mypy/typeshed/stdlib/tempfile.pyi | 26 +- mypy/typeshed/stdlib/time.pyi | 2 + mypy/typeshed/stdlib/tkinter/__init__.pyi | 65 +- mypy/typeshed/stdlib/tkinter/ttk.pyi | 4 +- mypy/typeshed/stdlib/tokenize.pyi | 8 +- mypy/typeshed/stdlib/traceback.pyi | 6 +- mypy/typeshed/stdlib/tracemalloc.pyi | 3 +- mypy/typeshed/stdlib/types.pyi | 20 +- mypy/typeshed/stdlib/typing.pyi | 60 +- mypy/typeshed/stdlib/typing_extensions.pyi | 19 +- mypy/typeshed/stdlib/unittest/case.pyi | 6 +- mypy/typeshed/stdlib/warnings.pyi | 3 +- mypy/typeshed/stdlib/weakref.pyi | 10 + mypy/typeshed/stdlib/winreg.pyi | 2 + mypy/typeshed/stdlib/zoneinfo/__init__.pyi | 4 +- 71 files changed, 1089 insertions(+), 744 deletions(-) diff --git a/mypy/typeshed/stdlib/@python2/__builtin__.pyi b/mypy/typeshed/stdlib/@python2/__builtin__.pyi index 453a95871463..fad8b2b4e7d8 100644 --- a/mypy/typeshed/stdlib/@python2/__builtin__.pyi +++ b/mypy/typeshed/stdlib/@python2/__builtin__.pyi @@ -121,7 +121,7 @@ class type(object): def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... def __call__(self, *args: Any, **kwds: Any) -> Any: ... def __subclasses__(self: _TT) -> List[_TT]: ... - # Note: the documentation doesnt specify what the return type is, the standard + # Note: the documentation doesn't specify what the return type is, the standard # implementation seems to be returning a list. def mro(self) -> List[type]: ... def __instancecheck__(self, instance: Any) -> bool: ... @@ -850,13 +850,18 @@ def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicod @overload def getattr(__o: Any, name: Text) -> Any: ... -# While technically covered by the last overload, spelling out the types for None and bool -# help mypy out in some tricky situations involving type context (aka bidirectional inference) +# While technically covered by the last overload, spelling out the types for None, bool +# and basic containers help mypy out in some tricky situations involving type context +# (aka bidirectional inference) @overload def getattr(__o: Any, name: Text, __default: None) -> Any | None: ... @overload def getattr(__o: Any, name: Text, __default: bool) -> Any | bool: ... @overload +def getattr(__o: object, name: str, __default: list[Any]) -> Any | list[Any]: ... +@overload +def getattr(__o: object, name: str, __default: dict[Any, Any]) -> Any | dict[Any, Any]: ... +@overload def getattr(__o: Any, name: Text, __default: _T) -> Any | _T: ... def globals() -> Dict[str, Any]: ... def hasattr(__obj: Any, __name: Text) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/ast.pyi b/mypy/typeshed/stdlib/@python2/ast.pyi index ec370e1a6c08..b86e38dce4c5 100644 --- a/mypy/typeshed/stdlib/@python2/ast.pyi +++ b/mypy/typeshed/stdlib/@python2/ast.pyi @@ -4,10 +4,9 @@ # from _ast below when loaded in an unorthodox way by the Dropbox # internal Bazel integration. import typing as _typing -from typing import Any, Iterator - from _ast import * from _ast import AST, Module +from typing import Any, Iterator def parse(source: str | unicode, filename: str | unicode = ..., mode: str | unicode = ...) -> Module: ... def copy_location(new_node: AST, old_node: AST) -> AST: ... diff --git a/mypy/typeshed/stdlib/@python2/builtins.pyi b/mypy/typeshed/stdlib/@python2/builtins.pyi index 453a95871463..fad8b2b4e7d8 100644 --- a/mypy/typeshed/stdlib/@python2/builtins.pyi +++ b/mypy/typeshed/stdlib/@python2/builtins.pyi @@ -121,7 +121,7 @@ class type(object): def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... def __call__(self, *args: Any, **kwds: Any) -> Any: ... def __subclasses__(self: _TT) -> List[_TT]: ... - # Note: the documentation doesnt specify what the return type is, the standard + # Note: the documentation doesn't specify what the return type is, the standard # implementation seems to be returning a list. def mro(self) -> List[type]: ... def __instancecheck__(self, instance: Any) -> bool: ... @@ -850,13 +850,18 @@ def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicod @overload def getattr(__o: Any, name: Text) -> Any: ... -# While technically covered by the last overload, spelling out the types for None and bool -# help mypy out in some tricky situations involving type context (aka bidirectional inference) +# While technically covered by the last overload, spelling out the types for None, bool +# and basic containers help mypy out in some tricky situations involving type context +# (aka bidirectional inference) @overload def getattr(__o: Any, name: Text, __default: None) -> Any | None: ... @overload def getattr(__o: Any, name: Text, __default: bool) -> Any | bool: ... @overload +def getattr(__o: object, name: str, __default: list[Any]) -> Any | list[Any]: ... +@overload +def getattr(__o: object, name: str, __default: dict[Any, Any]) -> Any | dict[Any, Any]: ... +@overload def getattr(__o: Any, name: Text, __default: _T) -> Any | _T: ... def globals() -> Dict[str, Any]: ... def hasattr(__obj: Any, __name: Text) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi b/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi index 149e9f281647..33184cc2ff88 100644 --- a/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi @@ -166,7 +166,7 @@ def POINTER(type: Type[_CT]) -> Type[pointer[_CT]]: ... # ctypes._Pointer in that it is the base class for all pointer types. Unlike the real _Pointer, # it can be instantiated directly (to mimic the behavior of the real pointer function). class pointer(Generic[_CT], _PointerLike, _CData): - _type_: ClassVar[Type[_CT]] = ... + _type_: Type[_CT] = ... contents: _CT = ... def __init__(self, arg: _CT = ...) -> None: ... @overload @@ -262,8 +262,8 @@ class BigEndianStructure(Structure): ... class LittleEndianStructure(Structure): ... class Array(Generic[_CT], _CData): - _length_: ClassVar[int] = ... - _type_: ClassVar[Type[_CT]] = ... + _length_: int = ... + _type_: Type[_CT] = ... raw: bytes = ... # Note: only available if _CT == c_char value: Any = ... # Note: bytes if _CT == c_char, Text if _CT == c_wchar, unavailable otherwise # TODO These methods cannot be annotated correctly at the moment. diff --git a/mypy/typeshed/stdlib/@python2/logging/__init__.pyi b/mypy/typeshed/stdlib/@python2/logging/__init__.pyi index 9cca9b51f753..f981e2400624 100644 --- a/mypy/typeshed/stdlib/@python2/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/logging/__init__.pyi @@ -1,8 +1,24 @@ import threading -from _typeshed import StrPath +from _typeshed import StrPath, SupportsWrite from time import struct_time from types import FrameType, TracebackType -from typing import IO, Any, Callable, Dict, List, Mapping, MutableMapping, Optional, Sequence, Text, Tuple, Union, overload +from typing import ( + IO, + Any, + Callable, + Dict, + Generic, + List, + Mapping, + MutableMapping, + Optional, + Sequence, + Text, + Tuple, + TypeVar, + Union, + overload, +) _SysExcInfoType = Union[Tuple[type, BaseException, Optional[TracebackType]], Tuple[None, None, None]] _ExcInfoType = Union[None, bool, _SysExcInfoType] @@ -159,10 +175,12 @@ class LogRecord: ) -> None: ... def getMessage(self) -> str: ... -class LoggerAdapter: - logger: Logger +_L = TypeVar("_L", Logger, LoggerAdapter[Logger], LoggerAdapter[Any]) + +class LoggerAdapter(Generic[_L]): + logger: _L extra: Mapping[str, Any] - def __init__(self, logger: Logger, extra: Mapping[str, Any]) -> None: ... + def __init__(self, logger: _L, extra: Mapping[str, Any]) -> None: ... def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> Tuple[Any, MutableMapping[str, Any]]: ... def debug( self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any @@ -227,9 +245,14 @@ def shutdown(handlerList: Sequence[Any] = ...) -> None: ... # handlerList is un def setLoggerClass(klass: type) -> None: ... def captureWarnings(capture: bool) -> None: ... -class StreamHandler(Handler): - stream: IO[str] # undocumented - def __init__(self, stream: IO[str] | None = ...) -> None: ... +_StreamT = TypeVar("_StreamT", bound=SupportsWrite[str]) + +class StreamHandler(Handler, Generic[_StreamT]): + stream: _StreamT # undocumented + @overload + def __init__(self: StreamHandler[IO[str]], stream: None = ...) -> None: ... + @overload + def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None: ... class FileHandler(StreamHandler): baseFilename: str # undocumented diff --git a/mypy/typeshed/stdlib/@python2/warnings.pyi b/mypy/typeshed/stdlib/@python2/warnings.pyi index e3540ed60b0c..0d187bf70c33 100644 --- a/mypy/typeshed/stdlib/@python2/warnings.pyi +++ b/mypy/typeshed/stdlib/@python2/warnings.pyi @@ -1,9 +1,8 @@ +from _warnings import warn as warn, warn_explicit as warn_explicit from types import ModuleType, TracebackType from typing import List, TextIO, Type, overload from typing_extensions import Literal -from _warnings import warn as warn, warn_explicit as warn_explicit - def showwarning( message: Warning | str, category: Type[Warning], filename: str, lineno: int, file: TextIO | None = ..., line: str | None = ... ) -> None: ... diff --git a/mypy/typeshed/stdlib/_collections_abc.pyi b/mypy/typeshed/stdlib/_collections_abc.pyi index 27d5234432f3..223b5fb8d62e 100644 --- a/mypy/typeshed/stdlib/_collections_abc.pyi +++ b/mypy/typeshed/stdlib/_collections_abc.pyi @@ -1,3 +1,5 @@ +import sys +from types import MappingProxyType from typing import ( AbstractSet as Set, AsyncGenerator as AsyncGenerator, @@ -10,6 +12,7 @@ from typing import ( Container as Container, Coroutine as Coroutine, Generator as Generator, + Generic, Hashable as Hashable, ItemsView as ItemsView, Iterable as Iterable, @@ -23,8 +26,10 @@ from typing import ( Reversible as Reversible, Sequence as Sequence, Sized as Sized, + TypeVar, ValuesView as ValuesView, ) +from typing_extensions import final __all__ = [ "Awaitable", @@ -53,3 +58,21 @@ __all__ = [ "MutableSequence", "ByteString", ] + +_KT_co = TypeVar("_KT_co", covariant=True) # Key type covariant containers. +_VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. + +@final +class dict_keys(KeysView[_KT_co], Generic[_KT_co, _VT_co]): # undocumented + if sys.version_info >= (3, 10): + mapping: MappingProxyType[_KT_co, _VT_co] + +@final +class dict_values(ValuesView[_VT_co], Generic[_KT_co, _VT_co]): # undocumented + if sys.version_info >= (3, 10): + mapping: MappingProxyType[_KT_co, _VT_co] + +@final +class dict_items(ItemsView[_KT_co, _VT_co], Generic[_KT_co, _VT_co]): # undocumented + if sys.version_info >= (3, 10): + mapping: MappingProxyType[_KT_co, _VT_co] diff --git a/mypy/typeshed/stdlib/_thread.pyi b/mypy/typeshed/stdlib/_thread.pyi index 2425703121b5..2f4252981b68 100644 --- a/mypy/typeshed/stdlib/_thread.pyi +++ b/mypy/typeshed/stdlib/_thread.pyi @@ -2,6 +2,7 @@ import sys from threading import Thread from types import TracebackType from typing import Any, Callable, NoReturn, Optional, Tuple, Type +from typing_extensions import final error = RuntimeError @@ -9,6 +10,7 @@ def _count() -> int: ... _dangling: Any +@final class LockType: def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... @@ -29,6 +31,7 @@ TIMEOUT_MAX: float if sys.version_info >= (3, 8): def get_native_id() -> int: ... # only available on some platforms + @final class _ExceptHookArgs(Tuple[Type[BaseException], Optional[BaseException], Optional[TracebackType], Optional[Thread]]): @property def exc_type(self) -> Type[BaseException]: ... diff --git a/mypy/typeshed/stdlib/_tkinter.pyi b/mypy/typeshed/stdlib/_tkinter.pyi index 378b04202c4f..e97edf5b4fae 100644 --- a/mypy/typeshed/stdlib/_tkinter.pyi +++ b/mypy/typeshed/stdlib/_tkinter.pyi @@ -1,5 +1,5 @@ from typing import Any -from typing_extensions import Literal +from typing_extensions import Literal, final # _tkinter is meant to be only used internally by tkinter, but some tkinter # functions e.g. return _tkinter.Tcl_Obj objects. Tcl_Obj represents a Tcl @@ -14,6 +14,7 @@ from typing_extensions import Literal # >>> text.tag_add('foo', '1.0', 'end') # >>> text.tag_ranges('foo') # (, ) +@final class Tcl_Obj: string: str # str(tclobj) returns this typename: str @@ -37,6 +38,7 @@ class TclError(Exception): ... # # eval always returns str because _tkinter_tkapp_eval_impl in _tkinter.c calls # Tkapp_UnicodeResult, and it returns a string when it succeeds. +@final class TkappType: # Please keep in sync with tkinter.Tk def call(self, __command: Any, *args: Any) -> Any: ... diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index 6dd0b38c2e65..8c0005294bf0 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -40,6 +40,11 @@ class SupportsLessThan(Protocol): SupportsLessThanT = TypeVar("SupportsLessThanT", bound=SupportsLessThan) # noqa: Y001 +class SupportsGreaterThan(Protocol): + def __gt__(self, __other: Any) -> bool: ... + +SupportsGreaterThanT = TypeVar("SupportsGreaterThanT", bound=SupportsGreaterThan) # noqa: Y001 + class SupportsDivMod(Protocol[_T_contra, _T_co]): def __divmod__(self, __other: _T_contra) -> _T_co: ... diff --git a/mypy/typeshed/stdlib/_weakref.pyi b/mypy/typeshed/stdlib/_weakref.pyi index 006836f85055..dcaef25b3f0f 100644 --- a/mypy/typeshed/stdlib/_weakref.pyi +++ b/mypy/typeshed/stdlib/_weakref.pyi @@ -1,5 +1,6 @@ import sys from typing import Any, Callable, Generic, TypeVar, overload +from typing_extensions import final if sys.version_info >= (3, 9): from types import GenericAlias @@ -7,9 +8,11 @@ if sys.version_info >= (3, 9): _C = TypeVar("_C", bound=Callable[..., Any]) _T = TypeVar("_T") +@final class CallableProxyType(Generic[_C]): # "weakcallableproxy" def __getattr__(self, attr: str) -> Any: ... +@final class ProxyType(Generic[_T]): # "weakproxy" def __getattr__(self, attr: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/_winapi.pyi b/mypy/typeshed/stdlib/_winapi.pyi index f1a12be18677..83089d485c17 100644 --- a/mypy/typeshed/stdlib/_winapi.pyi +++ b/mypy/typeshed/stdlib/_winapi.pyi @@ -1,6 +1,6 @@ import sys from typing import Any, NoReturn, Sequence, overload -from typing_extensions import Literal +from typing_extensions import Literal, final CREATE_NEW_CONSOLE: int CREATE_NEW_PROCESS_GROUP: int @@ -126,7 +126,7 @@ def WriteFile(handle: int, buffer: bytes, overlapped: Literal[True]) -> tuple[Ov def WriteFile(handle: int, buffer: bytes, overlapped: Literal[False] = ...) -> tuple[int, int]: ... @overload def WriteFile(handle: int, buffer: bytes, overlapped: int | bool) -> tuple[Any, int]: ... - +@final class Overlapped: event: int def GetOverlappedResult(self, __wait: bool) -> tuple[int, int]: ... diff --git a/mypy/typeshed/stdlib/array.pyi b/mypy/typeshed/stdlib/array.pyi index cbb765a6880f..6f4444b10f96 100644 --- a/mypy/typeshed/stdlib/array.pyi +++ b/mypy/typeshed/stdlib/array.pyi @@ -15,11 +15,11 @@ class array(MutableSequence[_T], Generic[_T]): typecode: _TypeCode itemsize: int @overload - def __init__(self: array[int], typecode: _IntTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... + def __init__(self: array[int], __typecode: _IntTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... @overload - def __init__(self: array[float], typecode: _FloatTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... + def __init__(self: array[float], __typecode: _FloatTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... @overload - def __init__(self: array[str], typecode: _UnicodeTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... + def __init__(self: array[str], __typecode: _UnicodeTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... @overload def __init__(self, typecode: str, __initializer: bytes | Iterable[_T] = ...) -> None: ... def append(self, __v: _T) -> None: ... @@ -48,22 +48,22 @@ class array(MutableSequence[_T], Generic[_T]): def tostring(self) -> bytes: ... def __len__(self) -> int: ... @overload - def __getitem__(self, i: int) -> _T: ... + def __getitem__(self, __i: int) -> _T: ... @overload - def __getitem__(self, s: slice) -> array[_T]: ... + def __getitem__(self, __s: slice) -> array[_T]: ... @overload # type: ignore # Overrides MutableSequence - def __setitem__(self, i: int, o: _T) -> None: ... + def __setitem__(self, __i: int, __o: _T) -> None: ... @overload - def __setitem__(self, s: slice, o: array[_T]) -> None: ... - def __delitem__(self, i: int | slice) -> None: ... - def __add__(self, x: array[_T]) -> array[_T]: ... - def __ge__(self, other: array[_T]) -> bool: ... - def __gt__(self, other: array[_T]) -> bool: ... - def __iadd__(self, x: array[_T]) -> array[_T]: ... # type: ignore # Overrides MutableSequence - def __imul__(self, n: int) -> array[_T]: ... - def __le__(self, other: array[_T]) -> bool: ... - def __lt__(self, other: array[_T]) -> bool: ... - def __mul__(self, n: int) -> array[_T]: ... - def __rmul__(self, n: int) -> array[_T]: ... + def __setitem__(self, __s: slice, __o: array[_T]) -> None: ... + def __delitem__(self, __i: int | slice) -> None: ... + def __add__(self, __x: array[_T]) -> array[_T]: ... + def __ge__(self, __other: array[_T]) -> bool: ... + def __gt__(self, __other: array[_T]) -> bool: ... + def __iadd__(self, __x: array[_T]) -> array[_T]: ... # type: ignore # Overrides MutableSequence + def __imul__(self, __n: int) -> array[_T]: ... + def __le__(self, __other: array[_T]) -> bool: ... + def __lt__(self, __other: array[_T]) -> bool: ... + def __mul__(self, __n: int) -> array[_T]: ... + def __rmul__(self, __n: int) -> array[_T]: ... ArrayType = array diff --git a/mypy/typeshed/stdlib/ast.pyi b/mypy/typeshed/stdlib/ast.pyi index 1649e4ab41be..00c62c30c037 100644 --- a/mypy/typeshed/stdlib/ast.pyi +++ b/mypy/typeshed/stdlib/ast.pyi @@ -8,11 +8,10 @@ # sys. import sys import typing as _typing +from _ast import * # type: ignore from typing import Any, Iterator, TypeVar, overload from typing_extensions import Literal -from _ast import * # type: ignore - if sys.version_info >= (3, 8): class Num(Constant): value: complex diff --git a/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi index a27fe764359e..23034790a4a9 100644 --- a/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi @@ -1,5 +1,6 @@ import subprocess -from typing import IO, Any, Callable, Deque, Optional, Sequence, Tuple, Union +from collections import deque +from typing import IO, Any, Callable, Optional, Sequence, Tuple, Union from . import events, futures, protocols, transports @@ -14,7 +15,7 @@ class BaseSubprocessTransport(transports.SubprocessTransport): _pid: int | None # undocumented _returncode: int | None # undocumented _exit_waiters: list[futures.Future[Any]] # undocumented - _pending_calls: Deque[tuple[Callable[..., Any], Tuple[Any, ...]]] # undocumented + _pending_calls: deque[tuple[Callable[..., Any], Tuple[Any, ...]]] # undocumented _pipes: dict[int, _File] # undocumented _finished: bool # undocumented def __init__( diff --git a/mypy/typeshed/stdlib/asyncio/locks.pyi b/mypy/typeshed/stdlib/asyncio/locks.pyi index 901232740773..7c4f40d9e4ca 100644 --- a/mypy/typeshed/stdlib/asyncio/locks.pyi +++ b/mypy/typeshed/stdlib/asyncio/locks.pyi @@ -1,6 +1,7 @@ import sys +from collections import deque from types import TracebackType -from typing import Any, Awaitable, Callable, Deque, Generator, Type, TypeVar +from typing import Any, Awaitable, Callable, Generator, Type, TypeVar from .events import AbstractEventLoop from .futures import Future @@ -57,7 +58,7 @@ class Condition(_ContextManagerMixin): class Semaphore(_ContextManagerMixin): _value: int - _waiters: Deque[Future[Any]] + _waiters: deque[Future[Any]] def __init__(self, value: int = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... def locked(self) -> bool: ... async def acquire(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/asyncio/protocols.pyi b/mypy/typeshed/stdlib/asyncio/protocols.pyi index aed6bbfb69ca..754f02c8bb4b 100644 --- a/mypy/typeshed/stdlib/asyncio/protocols.pyi +++ b/mypy/typeshed/stdlib/asyncio/protocols.pyi @@ -17,7 +17,7 @@ if sys.version_info >= (3, 7): def buffer_updated(self, nbytes: int) -> None: ... class DatagramProtocol(BaseProtocol): - def connection_made(self, transport: transports.DatagramTransport) -> None: ... # type: ignore + def connection_made(self, transport: transports.DatagramTransport) -> None: ... # type: ignore[override] def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None: ... def error_received(self, exc: Exception) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/sslproto.pyi b/mypy/typeshed/stdlib/asyncio/sslproto.pyi index 54f2a74f9f5a..082e96dc0233 100644 --- a/mypy/typeshed/stdlib/asyncio/sslproto.pyi +++ b/mypy/typeshed/stdlib/asyncio/sslproto.pyi @@ -1,6 +1,7 @@ import ssl import sys -from typing import Any, Callable, ClassVar, Deque +from collections import deque +from typing import Any, Callable, ClassVar from typing_extensions import Literal from . import constants, events, futures, protocols, transports @@ -73,7 +74,7 @@ class SSLProtocol(protocols.Protocol): _server_hostname: str | None _sslcontext: ssl.SSLContext _extra: dict[str, Any] - _write_backlog: Deque[tuple[bytes, int]] + _write_backlog: deque[tuple[bytes, int]] _write_buffer_size: int _waiter: futures.Future[Any] _loop: events.AbstractEventLoop diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index 49f70e0db5c2..15c12909f3c3 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -2,7 +2,7 @@ import concurrent.futures import sys from collections.abc import Awaitable, Generator, Iterable, Iterator from types import FrameType -from typing import Any, Generic, Optional, Set, TextIO, TypeVar, Union, overload +from typing import Any, Generic, Optional, TextIO, TypeVar, Union, overload from typing_extensions import Literal from .events import AbstractEventLoop @@ -232,22 +232,22 @@ if sys.version_info >= (3, 10): def shield(arg: _FutureT[_T]) -> Future[_T]: ... def sleep(delay: float, result: _T = ...) -> Future[_T]: ... @overload - def wait(fs: Iterable[_FT], *, timeout: float | None = ..., return_when: str = ...) -> Future[tuple[Set[_FT], Set[_FT]]]: ... # type: ignore + def wait(fs: Iterable[_FT], *, timeout: float | None = ..., return_when: str = ...) -> Future[tuple[set[_FT], set[_FT]]]: ... # type: ignore @overload def wait( fs: Iterable[Awaitable[_T]], *, timeout: float | None = ..., return_when: str = ... - ) -> Future[tuple[Set[Task[_T]], Set[Task[_T]]]]: ... + ) -> Future[tuple[set[Task[_T]], set[Task[_T]]]]: ... def wait_for(fut: _FutureT[_T], timeout: float | None) -> Future[_T]: ... else: def shield(arg: _FutureT[_T], *, loop: AbstractEventLoop | None = ...) -> Future[_T]: ... def sleep(delay: float, result: _T = ..., *, loop: AbstractEventLoop | None = ...) -> Future[_T]: ... @overload - def wait(fs: Iterable[_FT], *, loop: AbstractEventLoop | None = ..., timeout: float | None = ..., return_when: str = ...) -> Future[tuple[Set[_FT], Set[_FT]]]: ... # type: ignore + def wait(fs: Iterable[_FT], *, loop: AbstractEventLoop | None = ..., timeout: float | None = ..., return_when: str = ...) -> Future[tuple[set[_FT], set[_FT]]]: ... # type: ignore @overload def wait( fs: Iterable[Awaitable[_T]], *, loop: AbstractEventLoop | None = ..., timeout: float | None = ..., return_when: str = ... - ) -> Future[tuple[Set[Task[_T]], Set[Task[_T]]]]: ... + ) -> Future[tuple[set[Task[_T]], set[Task[_T]]]]: ... def wait_for(fut: _FutureT[_T], timeout: float | None, *, loop: AbstractEventLoop | None = ...) -> Future[_T]: ... class Task(Future[_T], Generic[_T]): @@ -278,14 +278,14 @@ class Task(Future[_T], Generic[_T]): @classmethod def current_task(cls, loop: AbstractEventLoop | None = ...) -> Task[Any] | None: ... @classmethod - def all_tasks(cls, loop: AbstractEventLoop | None = ...) -> Set[Task[Any]]: ... + def all_tasks(cls, loop: AbstractEventLoop | None = ...) -> set[Task[Any]]: ... if sys.version_info < (3, 7): def _wakeup(self, fut: Future[Any]) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... if sys.version_info >= (3, 7): - def all_tasks(loop: AbstractEventLoop | None = ...) -> Set[Task[Any]]: ... + def all_tasks(loop: AbstractEventLoop | None = ...) -> set[Task[Any]]: ... if sys.version_info >= (3, 8): def create_task(coro: Generator[_TaskYieldType, None, _T] | Awaitable[_T], *, name: str | None = ...) -> Task[_T]: ... else: diff --git a/mypy/typeshed/stdlib/bdb.pyi b/mypy/typeshed/stdlib/bdb.pyi index 068a3d44845e..1d03ddf19a0e 100644 --- a/mypy/typeshed/stdlib/bdb.pyi +++ b/mypy/typeshed/stdlib/bdb.pyi @@ -1,5 +1,5 @@ from types import CodeType, FrameType, TracebackType -from typing import IO, Any, Callable, Iterable, Mapping, Set, SupportsInt, Tuple, Type, TypeVar +from typing import IO, Any, Callable, Iterable, Mapping, SupportsInt, Tuple, Type, TypeVar _T = TypeVar("_T") _TraceDispatch = Callable[[FrameType, str, Any], Any] # TODO: Recursive type @@ -11,7 +11,7 @@ class BdbQuit(Exception): ... class Bdb: - skip: Set[str] | None + skip: set[str] | None breaks: dict[str, list[int]] fncache: dict[str, str] frame_returning: FrameType | None diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 4694042cab24..dfafe6f738e5 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -1,5 +1,7 @@ import sys import types +from _ast import AST +from _collections_abc import dict_items, dict_keys, dict_values from _typeshed import ( OpenBinaryMode, OpenBinaryModeReading, @@ -11,17 +13,19 @@ from _typeshed import ( StrOrBytesPath, SupportsAnext, SupportsDivMod, + SupportsGreaterThan, + SupportsGreaterThanT, SupportsKeysAndGetItem, SupportsLenAndGetItem, SupportsLessThan, SupportsLessThanT, SupportsNext, SupportsRDivMod, + SupportsTrunc, SupportsWrite, ) -from ast import AST, mod from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper -from types import CodeType, MappingProxyType, TracebackType +from types import CodeType, TracebackType from typing import ( IO, AbstractSet, @@ -31,12 +35,9 @@ from typing import ( BinaryIO, ByteString, Callable, - FrozenSet, Generic, - ItemsView, Iterable, Iterator, - KeysView, Mapping, MutableMapping, MutableSequence, @@ -45,7 +46,6 @@ from typing import ( Protocol, Reversible, Sequence, - Set, Sized, SupportsAbs, SupportsBytes, @@ -57,24 +57,18 @@ from typing import ( Type, TypeVar, Union, - ValuesView, overload, ) -from typing_extensions import Literal, SupportsIndex, final +from typing_extensions import Literal, SupportsIndex, TypeGuard, final if sys.version_info >= (3, 9): from types import GenericAlias -class _SupportsTrunc(Protocol): - def __trunc__(self) -> int: ... - _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) _T_contra = TypeVar("_T_contra", contravariant=True) _KT = TypeVar("_KT") _VT = TypeVar("_VT") -_KT_co = TypeVar("_KT_co", covariant=True) # Key type covariant containers. -_VT_co = TypeVar("_VT_co", covariant=True) # Value type covariant containers. _S = TypeVar("_S") _T1 = TypeVar("_T1") _T2 = TypeVar("_T2") @@ -83,6 +77,7 @@ _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") _TT = TypeVar("_TT", bound="type") _TBE = TypeVar("_TBE", bound="BaseException") +_R = TypeVar("_R") # Return-type TypeVar class object: __doc__: str | None @@ -97,37 +92,46 @@ class object: def __class__(self, __type: Type[object]) -> None: ... # type: ignore # noqa: F811 def __init__(self) -> None: ... def __new__(cls: Type[_T]) -> _T: ... - def __setattr__(self, name: str, value: Any) -> None: ... - def __eq__(self, o: object) -> bool: ... - def __ne__(self, o: object) -> bool: ... + def __setattr__(self, __name: str, __value: Any) -> None: ... + def __eq__(self, __o: object) -> bool: ... + def __ne__(self, __o: object) -> bool: ... def __str__(self) -> str: ... def __repr__(self) -> str: ... def __hash__(self) -> int: ... - def __format__(self, format_spec: str) -> str: ... - def __getattribute__(self, name: str) -> Any: ... - def __delattr__(self, name: str) -> None: ... + def __format__(self, __format_spec: str) -> str: ... + def __getattribute__(self, __name: str) -> Any: ... + def __delattr__(self, __name: str) -> None: ... def __sizeof__(self) -> int: ... - def __reduce__(self) -> str | Tuple[Any, ...]: ... + def __reduce__(self) -> str | Tuple[object, ...]: ... if sys.version_info >= (3, 8): - def __reduce_ex__(self, protocol: SupportsIndex) -> str | Tuple[Any, ...]: ... + def __reduce_ex__(self, __protocol: SupportsIndex) -> str | Tuple[object, ...]: ... else: - def __reduce_ex__(self, protocol: int) -> str | Tuple[Any, ...]: ... + def __reduce_ex__(self, __protocol: int) -> str | Tuple[object, ...]: ... def __dir__(self) -> Iterable[str]: ... def __init_subclass__(cls) -> None: ... -class staticmethod(object): # Special, only valid as a decorator. - __func__: Callable[..., Any] +class staticmethod(Generic[_R]): # Special, only valid as a decorator. + __func__: Callable[..., _R] __isabstractmethod__: bool - def __init__(self, f: Callable[..., Any]) -> None: ... + def __init__(self: staticmethod[_R], __f: Callable[..., _R]) -> None: ... def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, obj: _T, type: Type[_T] | None = ...) -> Callable[..., Any]: ... + def __get__(self, __obj: _T, __type: Type[_T] | None = ...) -> Callable[..., _R]: ... + if sys.version_info >= (3, 10): + __name__: str + __qualname__: str + __wrapped__: Callable[..., _R] + def __call__(self, *args: Any, **kwargs: Any) -> _R: ... -class classmethod(object): # Special, only valid as a decorator. - __func__: Callable[..., Any] +class classmethod(Generic[_R]): # Special, only valid as a decorator. + __func__: Callable[..., _R] __isabstractmethod__: bool - def __init__(self, f: Callable[..., Any]) -> None: ... + def __init__(self: classmethod[_R], __f: Callable[..., _R]) -> None: ... def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, obj: _T, type: Type[_T] | None = ...) -> Callable[..., Any]: ... + def __get__(self, __obj: _T, __type: Type[_T] | None = ...) -> Callable[..., _R]: ... + if sys.version_info >= (3, 10): + __name__: str + __qualname__: str + __wrapped__: Callable[..., _R] class type(object): __base__: type @@ -144,39 +148,42 @@ class type(object): __text_signature__: str | None __weakrefoffset__: int @overload - def __init__(self, o: object) -> None: ... + def __init__(self, __o: object) -> None: ... @overload - def __init__(self, name: str, bases: Tuple[type, ...], dict: dict[str, Any], **kwds: Any) -> None: ... + def __init__(self, __name: str, __bases: Tuple[type, ...], __dict: dict[str, Any], **kwds: Any) -> None: ... @overload - def __new__(cls, o: object) -> type: ... + def __new__(cls, __o: object) -> type: ... @overload - def __new__(cls: Type[_TT], name: str, bases: Tuple[type, ...], namespace: dict[str, Any], **kwds: Any) -> _TT: ... + def __new__(cls: Type[_TT], __name: str, __bases: Tuple[type, ...], __namespace: dict[str, Any], **kwds: Any) -> _TT: ... def __call__(self, *args: Any, **kwds: Any) -> Any: ... def __subclasses__(self: _TT) -> list[_TT]: ... - # Note: the documentation doesnt specify what the return type is, the standard + # Note: the documentation doesn't specify what the return type is, the standard # implementation seems to be returning a list. def mro(self) -> list[type]: ... - def __instancecheck__(self, instance: Any) -> bool: ... - def __subclasscheck__(self, subclass: type) -> bool: ... + def __instancecheck__(self, __instance: Any) -> bool: ... + def __subclasscheck__(self, __subclass: type) -> bool: ... @classmethod - def __prepare__(metacls, __name: str, __bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]: ... + def __prepare__(metacls, __name: str, __bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, object]: ... if sys.version_info >= (3, 10): - def __or__(self, t: Any) -> types.UnionType: ... - def __ror__(self, t: Any) -> types.UnionType: ... + def __or__(self, __t: Any) -> types.UnionType: ... + def __ror__(self, __t: Any) -> types.UnionType: ... class super(object): @overload - def __init__(self, t: Any, obj: Any) -> None: ... + def __init__(self, __t: Any, __obj: Any) -> None: ... @overload - def __init__(self, t: Any) -> None: ... + def __init__(self, __t: Any) -> None: ... @overload def __init__(self) -> None: ... +_PositiveInteger = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] +_NegativeInteger = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20] + class int: @overload - def __new__(cls: Type[_T], x: str | bytes | SupportsInt | SupportsIndex | _SupportsTrunc = ...) -> _T: ... + def __new__(cls: Type[_T], __x: str | bytes | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> _T: ... @overload - def __new__(cls: Type[_T], x: str | bytes | bytearray, base: SupportsIndex) -> _T: ... + def __new__(cls: Type[_T], __x: str | bytes | bytearray, base: SupportsIndex) -> _T: ... if sys.version_info >= (3, 8): def as_integer_ratio(self) -> tuple[int, Literal[1]]: ... @property @@ -196,49 +203,57 @@ class int: def from_bytes( cls, bytes: Iterable[SupportsIndex] | SupportsBytes, byteorder: Literal["little", "big"], *, signed: bool = ... ) -> int: ... # TODO buffer object argument - def __add__(self, x: int) -> int: ... - def __sub__(self, x: int) -> int: ... - def __mul__(self, x: int) -> int: ... - def __floordiv__(self, x: int) -> int: ... - def __truediv__(self, x: int) -> float: ... - def __mod__(self, x: int) -> int: ... - def __divmod__(self, x: int) -> tuple[int, int]: ... - def __radd__(self, x: int) -> int: ... - def __rsub__(self, x: int) -> int: ... - def __rmul__(self, x: int) -> int: ... - def __rfloordiv__(self, x: int) -> int: ... - def __rtruediv__(self, x: int) -> float: ... - def __rmod__(self, x: int) -> int: ... - def __rdivmod__(self, x: int) -> tuple[int, int]: ... - @overload - def __pow__(self, __x: Literal[2], __modulo: int | None = ...) -> int: ... - @overload - def __pow__(self, __x: int, __modulo: int | None = ...) -> Any: ... # Return type can be int or float, depending on x. - def __rpow__(self, x: int, mod: int | None = ...) -> Any: ... - def __and__(self, n: int) -> int: ... - def __or__(self, n: int) -> int: ... - def __xor__(self, n: int) -> int: ... - def __lshift__(self, n: int) -> int: ... - def __rshift__(self, n: int) -> int: ... - def __rand__(self, n: int) -> int: ... - def __ror__(self, n: int) -> int: ... - def __rxor__(self, n: int) -> int: ... - def __rlshift__(self, n: int) -> int: ... - def __rrshift__(self, n: int) -> int: ... + def __add__(self, __x: int) -> int: ... + def __sub__(self, __x: int) -> int: ... + def __mul__(self, __x: int) -> int: ... + def __floordiv__(self, __x: int) -> int: ... + def __truediv__(self, __x: int) -> float: ... + def __mod__(self, __x: int) -> int: ... + def __divmod__(self, __x: int) -> tuple[int, int]: ... + def __radd__(self, __x: int) -> int: ... + def __rsub__(self, __x: int) -> int: ... + def __rmul__(self, __x: int) -> int: ... + def __rfloordiv__(self, __x: int) -> int: ... + def __rtruediv__(self, __x: int) -> float: ... + def __rmod__(self, __x: int) -> int: ... + def __rdivmod__(self, __x: int) -> tuple[int, int]: ... + @overload + def __pow__(self, __x: int, __modulo: Literal[0]) -> NoReturn: ... + @overload + def __pow__(self, __x: int, __modulo: int) -> int: ... + @overload + def __pow__(self, __x: _PositiveInteger, __modulo: None = ...) -> int: ... + @overload + def __pow__(self, __x: _NegativeInteger, __modulo: None = ...) -> float: ... + # positive x -> int; negative x -> float + # return type must be Any as `int | float` causes too many false-positive errors + @overload + def __pow__(self, __x: int, __modulo: None = ...) -> Any: ... + def __rpow__(self, __x: int, __mod: int | None = ...) -> Any: ... + def __and__(self, __n: int) -> int: ... + def __or__(self, __n: int) -> int: ... + def __xor__(self, __n: int) -> int: ... + def __lshift__(self, __n: int) -> int: ... + def __rshift__(self, __n: int) -> int: ... + def __rand__(self, __n: int) -> int: ... + def __ror__(self, __n: int) -> int: ... + def __rxor__(self, __n: int) -> int: ... + def __rlshift__(self, __n: int) -> int: ... + def __rrshift__(self, __n: int) -> int: ... def __neg__(self) -> int: ... def __pos__(self) -> int: ... def __invert__(self) -> int: ... def __trunc__(self) -> int: ... def __ceil__(self) -> int: ... def __floor__(self) -> int: ... - def __round__(self, ndigits: SupportsIndex = ...) -> int: ... + def __round__(self, __ndigits: SupportsIndex = ...) -> int: ... def __getnewargs__(self) -> tuple[int]: ... - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: int) -> bool: ... - def __le__(self, x: int) -> bool: ... - def __gt__(self, x: int) -> bool: ... - def __ge__(self, x: int) -> bool: ... + def __eq__(self, __x: object) -> bool: ... + def __ne__(self, __x: object) -> bool: ... + def __lt__(self, __x: int) -> bool: ... + def __le__(self, __x: int) -> bool: ... + def __gt__(self, __x: int) -> bool: ... + def __ge__(self, __x: int) -> bool: ... def __str__(self) -> str: ... def __float__(self) -> float: ... def __int__(self) -> int: ... @@ -259,39 +274,42 @@ class float: @property def imag(self) -> float: ... def conjugate(self) -> float: ... - def __add__(self, x: float) -> float: ... - def __sub__(self, x: float) -> float: ... - def __mul__(self, x: float) -> float: ... - def __floordiv__(self, x: float) -> float: ... - def __truediv__(self, x: float) -> float: ... - def __mod__(self, x: float) -> float: ... - def __divmod__(self, x: float) -> tuple[float, float]: ... - def __pow__( - self, x: float, mod: None = ... - ) -> float: ... # In Python 3, returns complex if self is negative and x is not whole - def __radd__(self, x: float) -> float: ... - def __rsub__(self, x: float) -> float: ... - def __rmul__(self, x: float) -> float: ... - def __rfloordiv__(self, x: float) -> float: ... - def __rtruediv__(self, x: float) -> float: ... - def __rmod__(self, x: float) -> float: ... - def __rdivmod__(self, x: float) -> tuple[float, float]: ... - def __rpow__(self, x: float, mod: None = ...) -> float: ... + def __add__(self, __x: float) -> float: ... + def __sub__(self, __x: float) -> float: ... + def __mul__(self, __x: float) -> float: ... + def __floordiv__(self, __x: float) -> float: ... + def __truediv__(self, __x: float) -> float: ... + def __mod__(self, __x: float) -> float: ... + def __divmod__(self, __x: float) -> tuple[float, float]: ... + @overload + def __pow__(self, __x: int, __mod: None = ...) -> float: ... + # positive x -> float; negative x -> complex + # return type must be Any as `float | complex` causes too many false-positive errors + @overload + def __pow__(self, __x: float, __mod: None = ...) -> Any: ... + def __radd__(self, __x: float) -> float: ... + def __rsub__(self, __x: float) -> float: ... + def __rmul__(self, __x: float) -> float: ... + def __rfloordiv__(self, __x: float) -> float: ... + def __rtruediv__(self, __x: float) -> float: ... + def __rmod__(self, __x: float) -> float: ... + def __rdivmod__(self, __x: float) -> tuple[float, float]: ... + def __rpow__(self, __x: float, __mod: None = ...) -> float: ... def __getnewargs__(self) -> tuple[float]: ... def __trunc__(self) -> int: ... if sys.version_info >= (3, 9): def __ceil__(self) -> int: ... def __floor__(self) -> int: ... @overload - def __round__(self, ndigits: None = ...) -> int: ... + def __round__(self, __ndigits: None = ...) -> int: ... @overload - def __round__(self, ndigits: SupportsIndex) -> float: ... - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: float) -> bool: ... - def __le__(self, x: float) -> bool: ... - def __gt__(self, x: float) -> bool: ... - def __ge__(self, x: float) -> bool: ... + def __round__(self, __ndigits: SupportsIndex) -> float: ... + def __eq__(self, __x: object) -> bool: ... + def __ne__(self, __x: object) -> bool: ... + def __lt__(self, __x: float) -> bool: ... + def __le__(self, __x: float) -> bool: ... + def __gt__(self, __x: float) -> bool: ... + def __ge__(self, __x: float) -> bool: ... def __neg__(self) -> float: ... def __pos__(self) -> float: ... def __str__(self) -> str: ... @@ -311,18 +329,18 @@ class complex: @property def imag(self) -> float: ... def conjugate(self) -> complex: ... - def __add__(self, x: complex) -> complex: ... - def __sub__(self, x: complex) -> complex: ... - def __mul__(self, x: complex) -> complex: ... - def __pow__(self, x: complex, mod: None = ...) -> complex: ... - def __truediv__(self, x: complex) -> complex: ... - def __radd__(self, x: complex) -> complex: ... - def __rsub__(self, x: complex) -> complex: ... - def __rmul__(self, x: complex) -> complex: ... - def __rpow__(self, x: complex, mod: None = ...) -> complex: ... - def __rtruediv__(self, x: complex) -> complex: ... - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... + def __add__(self, __x: complex) -> complex: ... + def __sub__(self, __x: complex) -> complex: ... + def __mul__(self, __x: complex) -> complex: ... + def __pow__(self, __x: complex, mod: None = ...) -> complex: ... + def __truediv__(self, __x: complex) -> complex: ... + def __radd__(self, __x: complex) -> complex: ... + def __rsub__(self, __x: complex) -> complex: ... + def __rmul__(self, __x: complex) -> complex: ... + def __rpow__(self, __x: complex, __mod: None = ...) -> complex: ... + def __rtruediv__(self, __x: complex) -> complex: ... + def __eq__(self, __x: object) -> bool: ... + def __ne__(self, __x: object) -> bool: ... def __neg__(self) -> complex: ... def __pos__(self) -> complex: ... def __str__(self) -> str: ... @@ -335,7 +353,7 @@ class _FormatMapMapping(Protocol): class str(Sequence[str]): @overload - def __new__(cls: Type[_T], o: object = ...) -> _T: ... + def __new__(cls: Type[_T], object: object = ...) -> _T: ... @overload def __new__(cls: Type[_T], o: bytes, encoding: str = ..., errors: str = ...) -> _T: ... def capitalize(self) -> str: ... @@ -399,21 +417,21 @@ class str(Sequence[str]): @staticmethod @overload def maketrans(__x: str, __y: str, __z: str | None = ...) -> dict[int, int | None]: ... - def __add__(self, s: str) -> str: ... + def __add__(self, __s: str) -> str: ... # Incompatible with Sequence.__contains__ - def __contains__(self, o: str) -> bool: ... # type: ignore - def __eq__(self, x: object) -> bool: ... - def __ge__(self, x: str) -> bool: ... - def __getitem__(self, i: int | slice) -> str: ... - def __gt__(self, x: str) -> bool: ... + def __contains__(self, __o: str) -> bool: ... # type: ignore[override] + def __eq__(self, __x: object) -> bool: ... + def __ge__(self, __x: str) -> bool: ... + def __getitem__(self, __i: int | slice) -> str: ... + def __gt__(self, __x: str) -> bool: ... def __hash__(self) -> int: ... def __iter__(self) -> Iterator[str]: ... - def __le__(self, x: str) -> bool: ... + def __le__(self, __x: str) -> bool: ... def __len__(self) -> int: ... - def __lt__(self, x: str) -> bool: ... - def __mod__(self, x: Any) -> str: ... - def __mul__(self, n: SupportsIndex) -> str: ... - def __ne__(self, x: object) -> bool: ... + def __lt__(self, __x: str) -> bool: ... + def __mod__(self, __x: Any) -> str: ... + def __mul__(self, __n: SupportsIndex) -> str: ... + def __ne__(self, __x: object) -> bool: ... def __repr__(self) -> str: ... def __rmul__(self, n: SupportsIndex) -> str: ... def __str__(self) -> str: ... @@ -421,15 +439,15 @@ class str(Sequence[str]): class bytes(ByteString): @overload - def __new__(cls: Type[_T], ints: Iterable[SupportsIndex]) -> _T: ... + def __new__(cls: Type[_T], __ints: Iterable[SupportsIndex]) -> _T: ... @overload - def __new__(cls: Type[_T], string: str, encoding: str, errors: str = ...) -> _T: ... + def __new__(cls: Type[_T], __string: str, encoding: str, errors: str = ...) -> _T: ... @overload - def __new__(cls: Type[_T], length: SupportsIndex) -> _T: ... + def __new__(cls: Type[_T], __length: SupportsIndex) -> _T: ... @overload def __new__(cls: Type[_T]) -> _T: ... @overload - def __new__(cls: Type[_T], o: SupportsBytes) -> _T: ... + def __new__(cls: Type[_T], __o: SupportsBytes) -> _T: ... def capitalize(self) -> bytes: ... def center(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytes: ... def count( @@ -502,32 +520,32 @@ class bytes(ByteString): def __repr__(self) -> str: ... def __hash__(self) -> int: ... @overload - def __getitem__(self, i: SupportsIndex) -> int: ... + def __getitem__(self, __i: SupportsIndex) -> int: ... @overload - def __getitem__(self, s: slice) -> bytes: ... - def __add__(self, s: bytes) -> bytes: ... - def __mul__(self, n: SupportsIndex) -> bytes: ... - def __rmul__(self, n: SupportsIndex) -> bytes: ... - def __mod__(self, value: Any) -> bytes: ... + def __getitem__(self, __s: slice) -> bytes: ... + def __add__(self, __s: bytes) -> bytes: ... + def __mul__(self, __n: SupportsIndex) -> bytes: ... + def __rmul__(self, __n: SupportsIndex) -> bytes: ... + def __mod__(self, __value: Any) -> bytes: ... # Incompatible with Sequence.__contains__ - def __contains__(self, o: SupportsIndex | bytes) -> bool: ... # type: ignore - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: bytes) -> bool: ... - def __le__(self, x: bytes) -> bool: ... - def __gt__(self, x: bytes) -> bool: ... - def __ge__(self, x: bytes) -> bool: ... + def __contains__(self, __o: SupportsIndex | bytes) -> bool: ... # type: ignore[override] + def __eq__(self, __x: object) -> bool: ... + def __ne__(self, __x: object) -> bool: ... + def __lt__(self, __x: bytes) -> bool: ... + def __le__(self, __x: bytes) -> bool: ... + def __gt__(self, __x: bytes) -> bool: ... + def __ge__(self, __x: bytes) -> bool: ... def __getnewargs__(self) -> tuple[bytes]: ... class bytearray(MutableSequence[int], ByteString): @overload def __init__(self) -> None: ... @overload - def __init__(self, ints: Iterable[SupportsIndex]) -> None: ... + def __init__(self, __ints: Iterable[SupportsIndex]) -> None: ... @overload - def __init__(self, string: str, encoding: str, errors: str = ...) -> None: ... + def __init__(self, __string: str, encoding: str, errors: str = ...) -> None: ... @overload - def __init__(self, length: SupportsIndex) -> None: ... + def __init__(self, __length: SupportsIndex) -> None: ... def append(self, __item: SupportsIndex) -> None: ... def capitalize(self) -> bytearray: ... def center(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytearray: ... @@ -602,31 +620,32 @@ class bytearray(MutableSequence[int], ByteString): def __iter__(self) -> Iterator[int]: ... def __str__(self) -> str: ... def __repr__(self) -> str: ... - __hash__: None # type: ignore + __hash__: None # type: ignore[assignment] @overload - def __getitem__(self, i: SupportsIndex) -> int: ... + def __getitem__(self, __i: SupportsIndex) -> int: ... @overload - def __getitem__(self, s: slice) -> bytearray: ... + def __getitem__(self, __s: slice) -> bytearray: ... @overload - def __setitem__(self, i: SupportsIndex, x: SupportsIndex) -> None: ... + def __setitem__(self, __i: SupportsIndex, x: SupportsIndex) -> None: ... @overload - def __setitem__(self, s: slice, x: Iterable[SupportsIndex] | bytes) -> None: ... - def __delitem__(self, i: SupportsIndex | slice) -> None: ... - def __add__(self, s: bytes) -> bytearray: ... - def __iadd__(self, s: Iterable[int]) -> bytearray: ... - def __mul__(self, n: SupportsIndex) -> bytearray: ... - def __rmul__(self, n: SupportsIndex) -> bytearray: ... - def __imul__(self, n: SupportsIndex) -> bytearray: ... - def __mod__(self, value: Any) -> bytes: ... + def __setitem__(self, __s: slice, __x: Iterable[SupportsIndex] | bytes) -> None: ... + def __delitem__(self, __i: SupportsIndex | slice) -> None: ... + def __add__(self, __s: bytes) -> bytearray: ... + def __iadd__(self, __s: Iterable[int]) -> bytearray: ... + def __mul__(self, __n: SupportsIndex) -> bytearray: ... + def __rmul__(self, __n: SupportsIndex) -> bytearray: ... + def __imul__(self, __n: SupportsIndex) -> bytearray: ... + def __mod__(self, __value: Any) -> bytes: ... # Incompatible with Sequence.__contains__ - def __contains__(self, o: SupportsIndex | bytes) -> bool: ... # type: ignore - def __eq__(self, x: object) -> bool: ... - def __ne__(self, x: object) -> bool: ... - def __lt__(self, x: bytes) -> bool: ... - def __le__(self, x: bytes) -> bool: ... - def __gt__(self, x: bytes) -> bool: ... - def __ge__(self, x: bytes) -> bool: ... + def __contains__(self, __o: SupportsIndex | bytes) -> bool: ... # type: ignore[override] + def __eq__(self, __x: object) -> bool: ... + def __ne__(self, __x: object) -> bool: ... + def __lt__(self, __x: bytes) -> bool: ... + def __le__(self, __x: bytes) -> bool: ... + def __gt__(self, __x: bytes) -> bool: ... + def __ge__(self, __x: bytes) -> bool: ... +@final class memoryview(Sized, Sequence[int]): format: str itemsize: int @@ -644,20 +663,20 @@ class memoryview(Sized, Sequence[int]): def __init__(self, obj: ReadableBuffer) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + self, __exc_type: Type[BaseException] | None, __exc_val: BaseException | None, __exc_tb: TracebackType | None ) -> None: ... def cast(self, format: str, shape: list[int] | Tuple[int, ...] = ...) -> memoryview: ... @overload - def __getitem__(self, i: SupportsIndex) -> int: ... + def __getitem__(self, __i: SupportsIndex) -> int: ... @overload - def __getitem__(self, s: slice) -> memoryview: ... - def __contains__(self, x: object) -> bool: ... + def __getitem__(self, __s: slice) -> memoryview: ... + def __contains__(self, __x: object) -> bool: ... def __iter__(self) -> Iterator[int]: ... def __len__(self) -> int: ... @overload - def __setitem__(self, s: slice, o: bytes) -> None: ... + def __setitem__(self, __s: slice, __o: bytes) -> None: ... @overload - def __setitem__(self, i: SupportsIndex, o: SupportsIndex) -> None: ... + def __setitem__(self, __i: SupportsIndex, __o: SupportsIndex) -> None: ... if sys.version_info >= (3, 8): def tobytes(self, order: Literal["C", "F", "A"] | None = ...) -> bytes: ... else: @@ -675,65 +694,66 @@ class memoryview(Sized, Sequence[int]): class bool(int): def __new__(cls: Type[_T], __o: object = ...) -> _T: ... @overload - def __and__(self, x: bool) -> bool: ... + def __and__(self, __x: bool) -> bool: ... @overload - def __and__(self, x: int) -> int: ... + def __and__(self, __x: int) -> int: ... @overload - def __or__(self, x: bool) -> bool: ... + def __or__(self, __x: bool) -> bool: ... @overload - def __or__(self, x: int) -> int: ... + def __or__(self, __x: int) -> int: ... @overload - def __xor__(self, x: bool) -> bool: ... + def __xor__(self, __x: bool) -> bool: ... @overload - def __xor__(self, x: int) -> int: ... + def __xor__(self, __x: int) -> int: ... @overload - def __rand__(self, x: bool) -> bool: ... + def __rand__(self, __x: bool) -> bool: ... @overload - def __rand__(self, x: int) -> int: ... + def __rand__(self, __x: int) -> int: ... @overload - def __ror__(self, x: bool) -> bool: ... + def __ror__(self, __x: bool) -> bool: ... @overload - def __ror__(self, x: int) -> int: ... + def __ror__(self, __x: int) -> int: ... @overload - def __rxor__(self, x: bool) -> bool: ... + def __rxor__(self, __x: bool) -> bool: ... @overload - def __rxor__(self, x: int) -> int: ... + def __rxor__(self, __x: int) -> int: ... def __getnewargs__(self) -> tuple[int]: ... +@final class slice(object): start: Any step: Any stop: Any @overload - def __init__(self, stop: Any) -> None: ... + def __init__(self, __stop: Any) -> None: ... @overload - def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... - __hash__: None # type: ignore - def indices(self, len: SupportsIndex) -> tuple[int, int, int]: ... + def __init__(self, __start: Any, __stop: Any, __step: Any = ...) -> None: ... + __hash__: None # type: ignore[assignment] + def indices(self, __len: SupportsIndex) -> tuple[int, int, int]: ... class tuple(Sequence[_T_co], Generic[_T_co]): - def __new__(cls: Type[_T], iterable: Iterable[_T_co] = ...) -> _T: ... + def __new__(cls: Type[_T], __iterable: Iterable[_T_co] = ...) -> _T: ... def __len__(self) -> int: ... - def __contains__(self, x: object) -> bool: ... + def __contains__(self, __x: object) -> bool: ... @overload - def __getitem__(self, x: int) -> _T_co: ... + def __getitem__(self, __x: int) -> _T_co: ... @overload - def __getitem__(self, x: slice) -> Tuple[_T_co, ...]: ... + def __getitem__(self, __x: slice) -> Tuple[_T_co, ...]: ... def __iter__(self) -> Iterator[_T_co]: ... - def __lt__(self, x: Tuple[_T_co, ...]) -> bool: ... - def __le__(self, x: Tuple[_T_co, ...]) -> bool: ... - def __gt__(self, x: Tuple[_T_co, ...]) -> bool: ... - def __ge__(self, x: Tuple[_T_co, ...]) -> bool: ... + def __lt__(self, __x: Tuple[_T_co, ...]) -> bool: ... + def __le__(self, __x: Tuple[_T_co, ...]) -> bool: ... + def __gt__(self, __x: Tuple[_T_co, ...]) -> bool: ... + def __ge__(self, __x: Tuple[_T_co, ...]) -> bool: ... @overload - def __add__(self, x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... + def __add__(self, __x: Tuple[_T_co, ...]) -> Tuple[_T_co, ...]: ... @overload - def __add__(self, x: Tuple[_T, ...]) -> Tuple[_T_co | _T, ...]: ... - def __mul__(self, n: SupportsIndex) -> Tuple[_T_co, ...]: ... - def __rmul__(self, n: SupportsIndex) -> Tuple[_T_co, ...]: ... + def __add__(self, __x: Tuple[_T, ...]) -> Tuple[_T_co | _T, ...]: ... + def __mul__(self, __n: SupportsIndex) -> Tuple[_T_co, ...]: ... + def __rmul__(self, __n: SupportsIndex) -> Tuple[_T_co, ...]: ... def count(self, __value: Any) -> int: ... def index(self, __value: Any, __start: SupportsIndex = ..., __stop: SupportsIndex = ...) -> int: ... if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, __item: Any) -> GenericAlias: ... class function: # TODO not defined in builtins! @@ -747,7 +767,7 @@ class list(MutableSequence[_T], Generic[_T]): @overload def __init__(self) -> None: ... @overload - def __init__(self, iterable: Iterable[_T]) -> None: ... + def __init__(self, __iterable: Iterable[_T]) -> None: ... def clear(self) -> None: ... def copy(self) -> list[_T]: ... def append(self, __object: _T) -> None: ... @@ -765,43 +785,29 @@ class list(MutableSequence[_T], Generic[_T]): def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... def __str__(self) -> str: ... - __hash__: None # type: ignore + __hash__: None # type: ignore[assignment] @overload - def __getitem__(self, i: SupportsIndex) -> _T: ... + def __getitem__(self, __i: SupportsIndex) -> _T: ... @overload - def __getitem__(self, s: slice) -> list[_T]: ... + def __getitem__(self, __s: slice) -> list[_T]: ... @overload - def __setitem__(self, i: SupportsIndex, o: _T) -> None: ... + def __setitem__(self, __i: SupportsIndex, __o: _T) -> None: ... @overload - def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... - def __delitem__(self, i: SupportsIndex | slice) -> None: ... - def __add__(self, x: list[_T]) -> list[_T]: ... - def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... - def __mul__(self, n: SupportsIndex) -> list[_T]: ... - def __rmul__(self, n: SupportsIndex) -> list[_T]: ... - def __imul__(self: _S, n: SupportsIndex) -> _S: ... - def __contains__(self, o: object) -> bool: ... + def __setitem__(self, __s: slice, __o: Iterable[_T]) -> None: ... + def __delitem__(self, __i: SupportsIndex | slice) -> None: ... + def __add__(self, __x: list[_T]) -> list[_T]: ... + def __iadd__(self: _S, __x: Iterable[_T]) -> _S: ... + def __mul__(self, __n: SupportsIndex) -> list[_T]: ... + def __rmul__(self, __n: SupportsIndex) -> list[_T]: ... + def __imul__(self: _S, __n: SupportsIndex) -> _S: ... + def __contains__(self, __o: object) -> bool: ... def __reversed__(self) -> Iterator[_T]: ... - def __gt__(self, x: list[_T]) -> bool: ... - def __ge__(self, x: list[_T]) -> bool: ... - def __lt__(self, x: list[_T]) -> bool: ... - def __le__(self, x: list[_T]) -> bool: ... + def __gt__(self, __x: list[_T]) -> bool: ... + def __ge__(self, __x: list[_T]) -> bool: ... + def __lt__(self, __x: list[_T]) -> bool: ... + def __le__(self, __x: list[_T]) -> bool: ... if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -class _dict_keys(KeysView[_KT_co], Generic[_KT_co, _VT_co]): - if sys.version_info >= (3, 10): - mapping: MappingProxyType[_KT_co, _VT_co] - -# The generics are the wrong way around because of a mypy limitation -# https://github.com/python/mypy/issues/11138 -class _dict_values(ValuesView[_VT_co], Generic[_VT_co, _KT_co]): - if sys.version_info >= (3, 10): - mapping: MappingProxyType[_KT_co, _VT_co] - -class _dict_items(ItemsView[_KT_co, _VT_co], Generic[_KT_co, _VT_co]): - if sys.version_info >= (3, 10): - mapping: MappingProxyType[_KT_co, _VT_co] + def __class_getitem__(cls, __item: Any) -> GenericAlias: ... class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @overload @@ -809,13 +815,13 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @overload def __init__(self: dict[str, _VT], **kwargs: _VT) -> None: ... @overload - def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... + def __init__(self, __map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... @overload - def __init__(self, iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __init__(self, __iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... # Next overload is for dict(string.split(sep) for string in iterable) # Cannot be Iterable[Sequence[_T]] or otherwise dict(["foo", "bar", "baz"]) is not an error @overload - def __init__(self: dict[str, str], iterable: Iterable[list[str]]) -> None: ... + def __init__(self: dict[str, str], __iterable: Iterable[list[str]]) -> None: ... def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... def clear(self) -> None: ... def copy(self) -> dict[_KT, _VT]: ... @@ -827,9 +833,9 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def update(self, __m: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... @overload def update(self, **kwargs: _VT) -> None: ... - def keys(self) -> _dict_keys[_KT, _VT]: ... - def values(self) -> _dict_values[_VT, _KT]: ... - def items(self) -> _dict_items[_KT, _VT]: ... + def keys(self) -> dict_keys[_KT, _VT]: ... + def values(self) -> dict_values[_KT, _VT]: ... + def items(self) -> dict_items[_KT, _VT]: ... @classmethod @overload def fromkeys(cls, __iterable: Iterable[_T], __value: None = ...) -> dict[_T, Any | None]: ... @@ -837,108 +843,109 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @overload def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> dict[_T, _S]: ... def __len__(self) -> int: ... - def __getitem__(self, k: _KT) -> _VT: ... - def __setitem__(self, k: _KT, v: _VT) -> None: ... - def __delitem__(self, v: _KT) -> None: ... + def __getitem__(self, __k: _KT) -> _VT: ... + def __setitem__(self, __k: _KT, v: _VT) -> None: ... + def __delitem__(self, __v: _KT) -> None: ... def __iter__(self) -> Iterator[_KT]: ... if sys.version_info >= (3, 8): def __reversed__(self) -> Iterator[_KT]: ... def __str__(self) -> str: ... - __hash__: None # type: ignore + __hash__: None # type: ignore[assignment] if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, __item: Any) -> GenericAlias: ... def __or__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ... def __ror__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT | _T2]: ... - def __ior__(self, __value: Mapping[_KT, _VT]) -> dict[_KT, _VT]: ... # type: ignore + def __ior__(self, __value: Mapping[_KT, _VT]) -> dict[_KT, _VT]: ... # type: ignore[misc] class set(MutableSet[_T], Generic[_T]): - def __init__(self, iterable: Iterable[_T] = ...) -> None: ... - def add(self, element: _T) -> None: ... + def __init__(self, __iterable: Iterable[_T] = ...) -> None: ... + def add(self, __element: _T) -> None: ... def clear(self) -> None: ... - def copy(self) -> Set[_T]: ... - def difference(self, *s: Iterable[Any]) -> Set[_T]: ... + def copy(self) -> set[_T]: ... + def difference(self, *s: Iterable[Any]) -> set[_T]: ... def difference_update(self, *s: Iterable[Any]) -> None: ... - def discard(self, element: _T) -> None: ... - def intersection(self, *s: Iterable[Any]) -> Set[_T]: ... + def discard(self, __element: _T) -> None: ... + def intersection(self, *s: Iterable[Any]) -> set[_T]: ... def intersection_update(self, *s: Iterable[Any]) -> None: ... - def isdisjoint(self, s: Iterable[Any]) -> bool: ... - def issubset(self, s: Iterable[Any]) -> bool: ... - def issuperset(self, s: Iterable[Any]) -> bool: ... + def isdisjoint(self, __s: Iterable[Any]) -> bool: ... + def issubset(self, __s: Iterable[Any]) -> bool: ... + def issuperset(self, __s: Iterable[Any]) -> bool: ... def pop(self) -> _T: ... - def remove(self, element: _T) -> None: ... - def symmetric_difference(self, s: Iterable[_T]) -> Set[_T]: ... - def symmetric_difference_update(self, s: Iterable[_T]) -> None: ... - def union(self, *s: Iterable[_T]) -> Set[_T]: ... + def remove(self, __element: _T) -> None: ... + def symmetric_difference(self, __s: Iterable[_T]) -> set[_T]: ... + def symmetric_difference_update(self, __s: Iterable[_T]) -> None: ... + def union(self, *s: Iterable[_S]) -> set[_T | _S]: ... def update(self, *s: Iterable[_T]) -> None: ... def __len__(self) -> int: ... - def __contains__(self, o: object) -> bool: ... + def __contains__(self, __o: object) -> bool: ... def __iter__(self) -> Iterator[_T]: ... def __str__(self) -> str: ... - def __and__(self, s: AbstractSet[object]) -> Set[_T]: ... - def __iand__(self, s: AbstractSet[object]) -> Set[_T]: ... - def __or__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... - def __ior__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... - def __sub__(self, s: AbstractSet[_T | None]) -> Set[_T]: ... - def __isub__(self, s: AbstractSet[_T | None]) -> Set[_T]: ... - def __xor__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... - def __ixor__(self, s: AbstractSet[_S]) -> Set[_T | _S]: ... - def __le__(self, s: AbstractSet[object]) -> bool: ... - def __lt__(self, s: AbstractSet[object]) -> bool: ... - def __ge__(self, s: AbstractSet[object]) -> bool: ... - def __gt__(self, s: AbstractSet[object]) -> bool: ... - __hash__: None # type: ignore + def __and__(self, __s: AbstractSet[object]) -> set[_T]: ... + def __iand__(self, __s: AbstractSet[object]) -> set[_T]: ... + def __or__(self, __s: AbstractSet[_S]) -> set[_T | _S]: ... + def __ior__(self, __s: AbstractSet[_S]) -> set[_T | _S]: ... + def __sub__(self, __s: AbstractSet[_T | None]) -> set[_T]: ... + def __isub__(self, __s: AbstractSet[_T | None]) -> set[_T]: ... + def __xor__(self, __s: AbstractSet[_S]) -> set[_T | _S]: ... + def __ixor__(self, __s: AbstractSet[_S]) -> set[_T | _S]: ... + def __le__(self, __s: AbstractSet[object]) -> bool: ... + def __lt__(self, __s: AbstractSet[object]) -> bool: ... + def __ge__(self, __s: AbstractSet[object]) -> bool: ... + def __gt__(self, __s: AbstractSet[object]) -> bool: ... + __hash__: None # type: ignore[assignment] if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, __item: Any) -> GenericAlias: ... class frozenset(AbstractSet[_T_co], Generic[_T_co]): - def __init__(self, iterable: Iterable[_T_co] = ...) -> None: ... - def copy(self) -> FrozenSet[_T_co]: ... - def difference(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... - def intersection(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... - def isdisjoint(self, s: Iterable[_T_co]) -> bool: ... - def issubset(self, s: Iterable[object]) -> bool: ... - def issuperset(self, s: Iterable[object]) -> bool: ... - def symmetric_difference(self, s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... - def union(self, *s: Iterable[_T_co]) -> FrozenSet[_T_co]: ... + def __init__(self, __iterable: Iterable[_T_co] = ...) -> None: ... + def copy(self) -> frozenset[_T_co]: ... + def difference(self, *s: Iterable[object]) -> frozenset[_T_co]: ... + def intersection(self, *s: Iterable[object]) -> frozenset[_T_co]: ... + def isdisjoint(self, __s: Iterable[_T_co]) -> bool: ... + def issubset(self, __s: Iterable[object]) -> bool: ... + def issuperset(self, __s: Iterable[object]) -> bool: ... + def symmetric_difference(self, __s: Iterable[_T_co]) -> frozenset[_T_co]: ... + def union(self, *s: Iterable[_S]) -> frozenset[_T_co | _S]: ... def __len__(self) -> int: ... - def __contains__(self, o: object) -> bool: ... + def __contains__(self, __o: object) -> bool: ... def __iter__(self) -> Iterator[_T_co]: ... def __str__(self) -> str: ... - def __and__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... - def __or__(self, s: AbstractSet[_S]) -> FrozenSet[_T_co | _S]: ... - def __sub__(self, s: AbstractSet[_T_co]) -> FrozenSet[_T_co]: ... - def __xor__(self, s: AbstractSet[_S]) -> FrozenSet[_T_co | _S]: ... - def __le__(self, s: AbstractSet[object]) -> bool: ... - def __lt__(self, s: AbstractSet[object]) -> bool: ... - def __ge__(self, s: AbstractSet[object]) -> bool: ... - def __gt__(self, s: AbstractSet[object]) -> bool: ... + def __and__(self, __s: AbstractSet[_T_co]) -> frozenset[_T_co]: ... + def __or__(self, __s: AbstractSet[_S]) -> frozenset[_T_co | _S]: ... + def __sub__(self, __s: AbstractSet[_T_co]) -> frozenset[_T_co]: ... + def __xor__(self, __s: AbstractSet[_S]) -> frozenset[_T_co | _S]: ... + def __le__(self, __s: AbstractSet[object]) -> bool: ... + def __lt__(self, __s: AbstractSet[object]) -> bool: ... + def __ge__(self, __s: AbstractSet[object]) -> bool: ... + def __gt__(self, __s: AbstractSet[object]) -> bool: ... if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, __item: Any) -> GenericAlias: ... class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): def __init__(self, iterable: Iterable[_T], start: int = ...) -> None: ... def __iter__(self) -> Iterator[tuple[int, _T]]: ... def __next__(self) -> tuple[int, _T]: ... if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + def __class_getitem__(cls, __item: Any) -> GenericAlias: ... +@final class range(Sequence[int]): start: int stop: int step: int @overload - def __init__(self, stop: SupportsIndex) -> None: ... + def __init__(self, __stop: SupportsIndex) -> None: ... @overload - def __init__(self, start: SupportsIndex, stop: SupportsIndex, step: SupportsIndex = ...) -> None: ... - def count(self, value: int) -> int: ... - def index(self, value: int) -> int: ... # type: ignore + def __init__(self, __start: SupportsIndex, __stop: SupportsIndex, __step: SupportsIndex = ...) -> None: ... + def count(self, __value: int) -> int: ... + def index(self, __value: int) -> int: ... # type: ignore[override] def __len__(self) -> int: ... - def __contains__(self, o: object) -> bool: ... + def __contains__(self, __o: object) -> bool: ... def __iter__(self) -> Iterator[int]: ... @overload - def __getitem__(self, i: SupportsIndex) -> int: ... + def __getitem__(self, __i: SupportsIndex) -> int: ... @overload - def __getitem__(self, s: slice) -> range: ... + def __getitem__(self, __s: slice) -> range: ... def __repr__(self) -> str: ... def __reversed__(self) -> Iterator[int]: ... @@ -953,17 +960,18 @@ class property(object): fdel: Callable[[Any], None] | None = ..., doc: str | None = ..., ) -> None: ... - def getter(self, fget: Callable[[Any], Any]) -> property: ... - def setter(self, fset: Callable[[Any, Any], None]) -> property: ... - def deleter(self, fdel: Callable[[Any], None]) -> property: ... - def __get__(self, obj: Any, type: type | None = ...) -> Any: ... - def __set__(self, obj: Any, value: Any) -> None: ... - def __delete__(self, obj: Any) -> None: ... - -class _NotImplementedType(Any): # type: ignore + def getter(self, __fget: Callable[[Any], Any]) -> property: ... + def setter(self, __fset: Callable[[Any, Any], None]) -> property: ... + def deleter(self, __fdel: Callable[[Any], None]) -> property: ... + def __get__(self, __obj: Any, __type: type | None = ...) -> Any: ... + def __set__(self, __obj: Any, __value: Any) -> None: ... + def __delete__(self, __obj: Any) -> None: ... + +@final +class _NotImplementedType(Any): # type: ignore[misc] # A little weird, but typing the __call__ as NotImplemented makes the error message # for NotImplemented() much better - __call__: NotImplemented # type: ignore + __call__: NotImplemented # type: ignore[valid-type] NotImplemented: _NotImplementedType @@ -976,7 +984,7 @@ def bin(__number: int | SupportsIndex) -> str: ... if sys.version_info >= (3, 7): def breakpoint(*args: Any, **kws: Any) -> None: ... -def callable(__obj: object) -> bool: ... +def callable(__obj: object) -> TypeGuard[Callable[..., object]]: ... def chr(__i: int) -> str: ... # We define this here instead of using os.PathLike to avoid import cycle issues. @@ -993,9 +1001,10 @@ if sys.version_info >= (3, 10): @overload async def anext(__i: SupportsAnext[_T], default: _VT) -> _T | _VT: ... +# TODO: `compile` has a more precise return type in reality; work on a way of expressing that? if sys.version_info >= (3, 8): def compile( - source: str | bytes | mod | AST, + source: str | bytes | AST, filename: str | bytes | _PathLike[Any], mode: str, flags: int = ..., @@ -1007,7 +1016,7 @@ if sys.version_info >= (3, 8): else: def compile( - source: str | bytes | mod | AST, + source: str | bytes | AST, filename: str | bytes | _PathLike[Any], mode: str, flags: int = ..., @@ -1017,18 +1026,23 @@ else: def copyright() -> None: ... def credits() -> None: ... -def delattr(__obj: Any, __name: str) -> None: ... +def delattr(__obj: object, __name: str) -> None: ... def dir(__o: object = ...) -> list[str]: ... @overload def divmod(__x: SupportsDivMod[_T_contra, _T_co], __y: _T_contra) -> _T_co: ... @overload def divmod(__x: _T_contra, __y: SupportsRDivMod[_T_contra, _T_co]) -> _T_co: ... + +# The `globals` argument to `eval` has to be `dict[str, Any]` rather than `dict[str, object]` due to invariance. +# (The `globals` argument has to be a "real dict", rather than any old mapping, unlike the `locals` argument.) def eval( - __source: str | bytes | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, Any] | None = ... + __source: str | bytes | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, object] | None = ... ) -> Any: ... + +# Comment above regarding `eval` applies to `exec` as well def exec( - __source: str | bytes | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, Any] | None = ... -) -> Any: ... + __source: str | bytes | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, object] | None = ... +) -> None: ... def exit(code: object = ...) -> NoReturn: ... class filter(Iterator[_T], Generic[_T]): @@ -1041,30 +1055,36 @@ class filter(Iterator[_T], Generic[_T]): def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode @overload -def getattr(__o: object, name: str) -> Any: ... +def getattr(__o: object, __name: str) -> Any: ... -# While technically covered by the last overload, spelling out the types for None and bool -# help mypy out in some tricky situations involving type context (aka bidirectional inference) +# While technically covered by the last overload, spelling out the types for None, bool +# and basic containers help mypy out in some tricky situations involving type context +# (aka bidirectional inference) @overload -def getattr(__o: object, name: str, __default: None) -> Any | None: ... +def getattr(__o: object, __name: str, __default: None) -> Any | None: ... @overload -def getattr(__o: object, name: str, __default: bool) -> Any | bool: ... +def getattr(__o: object, __name: str, __default: bool) -> Any | bool: ... @overload -def getattr(__o: object, name: str, __default: _T) -> Any | _T: ... +def getattr(__o: object, name: str, __default: list[Any]) -> Any | list[Any]: ... +@overload +def getattr(__o: object, name: str, __default: dict[Any, Any]) -> Any | dict[Any, Any]: ... +@overload +def getattr(__o: object, __name: str, __default: _T) -> Any | _T: ... def globals() -> dict[str, Any]: ... def hasattr(__obj: object, __name: str) -> bool: ... def hash(__obj: object) -> int: ... def help(*args: Any, **kwds: Any) -> None: ... def hex(__number: int | SupportsIndex) -> str: ... def id(__obj: object) -> int: ... -def input(__prompt: Any = ...) -> str: ... +def input(__prompt: object = ...) -> str: ... @overload def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... @overload def iter(__function: Callable[[], _T | None], __sentinel: None) -> Iterator[_T]: ... @overload -def iter(__function: Callable[[], _T], __sentinel: Any) -> Iterator[_T]: ... +def iter(__function: Callable[[], _T], __sentinel: object) -> Iterator[_T]: ... +# We need recursive types to express the type of the second argument to `isinstance` properly, hence the use of `Any` if sys.version_info >= (3, 10): def isinstance( __obj: object, __class_or_tuple: type | types.UnionType | Tuple[type | types.UnionType | Tuple[Any, ...], ...] @@ -1126,18 +1146,18 @@ class map(Iterator[_S], Generic[_S]): @overload def max( - __arg1: SupportsLessThanT, __arg2: SupportsLessThanT, *_args: SupportsLessThanT, key: None = ... -) -> SupportsLessThanT: ... + __arg1: SupportsGreaterThanT, __arg2: SupportsGreaterThanT, *_args: SupportsGreaterThanT, key: None = ... +) -> SupportsGreaterThanT: ... @overload -def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], SupportsLessThan]) -> _T: ... +def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], SupportsGreaterThan]) -> _T: ... @overload -def max(__iterable: Iterable[SupportsLessThanT], *, key: None = ...) -> SupportsLessThanT: ... +def max(__iterable: Iterable[SupportsGreaterThanT], *, key: None = ...) -> SupportsGreaterThanT: ... @overload -def max(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsLessThan]) -> _T: ... +def max(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsGreaterThan]) -> _T: ... @overload -def max(__iterable: Iterable[SupportsLessThanT], *, key: None = ..., default: _T) -> SupportsLessThanT | _T: ... +def max(__iterable: Iterable[SupportsGreaterThanT], *, key: None = ..., default: _T) -> SupportsGreaterThanT | _T: ... @overload -def max(__iterable: Iterable[_T1], *, key: Callable[[_T1], SupportsLessThan], default: _T2) -> _T1 | _T2: ... +def max(__iterable: Iterable[_T1], *, key: Callable[[_T1], SupportsGreaterThan], default: _T2) -> _T1 | _T2: ... @overload def min( __arg1: SupportsLessThanT, __arg2: SupportsLessThanT, *_args: SupportsLessThanT, key: None = ... @@ -1248,8 +1268,21 @@ def open( opener: _Opener | None = ..., ) -> IO[Any]: ... def ord(__c: str | bytes) -> int: ... + +class _SupportsWriteAndFlush(SupportsWrite[_T_contra], Protocol[_T_contra]): + def flush(self) -> None: ... + +@overload +def print( + *values: object, + sep: str | None = ..., + end: str | None = ..., + file: SupportsWrite[str] | None = ..., + flush: Literal[False] = ..., +) -> None: ... +@overload def print( - *values: object, sep: str | None = ..., end: str | None = ..., file: SupportsWrite[str] | None = ..., flush: bool = ... + *values: object, sep: str | None = ..., end: str | None = ..., file: _SupportsWriteAndFlush[str] | None = ..., flush: bool ) -> None: ... _E = TypeVar("_E", contravariant=True) @@ -1258,34 +1291,74 @@ _M = TypeVar("_M", contravariant=True) class _SupportsPow2(Protocol[_E, _T_co]): def __pow__(self, __other: _E) -> _T_co: ... +class _SupportsPow3NoneOnly(Protocol[_E, _T_co]): + def __pow__(self, __other: _E, __modulo: None = ...) -> _T_co: ... + class _SupportsPow3(Protocol[_E, _M, _T_co]): def __pow__(self, __other: _E, __modulo: _M) -> _T_co: ... +_SupportsSomeKindOfPow = Union[_SupportsPow2[Any, Any], _SupportsPow3NoneOnly[Any, Any], _SupportsPow3[Any, Any, Any]] + if sys.version_info >= (3, 8): @overload - def pow(base: int, exp: int, mod: None = ...) -> Any: ... # returns int or float depending on whether exp is non-negative + def pow(base: int, exp: int, mod: Literal[0]) -> NoReturn: ... @overload def pow(base: int, exp: int, mod: int) -> int: ... @overload - def pow(base: float, exp: float, mod: None = ...) -> float: ... + def pow(base: int, exp: _PositiveInteger, mod: None = ...) -> int: ... # type: ignore[misc] + @overload + def pow(base: int, exp: _NegativeInteger, mod: None = ...) -> float: ... # type: ignore[misc] + # int base & positive-int exp -> int; int base & negative-int exp -> float + # return type must be Any as `int | float` causes too many false-positive errors + @overload + def pow(base: int, exp: int, mod: None = ...) -> Any: ... + @overload + def pow(base: float, exp: int, mod: None = ...) -> float: ... + # float base & float exp could return float or complex + # return type must be Any (same as complex base, complex exp), + # as `float | complex` causes too many false-positive errors + @overload + def pow(base: float, exp: complex | _SupportsSomeKindOfPow, mod: None = ...) -> Any: ... + @overload + def pow(base: complex, exp: complex | _SupportsSomeKindOfPow, mod: None = ...) -> complex: ... + @overload + def pow(base: _SupportsPow2[_E, _T_co], exp: _E, mod: None = ...) -> _T_co: ... + @overload + def pow(base: _SupportsPow3NoneOnly[_E, _T_co], exp: _E, mod: None = ...) -> _T_co: ... @overload - def pow(base: _SupportsPow2[_E, _T_co], exp: _E) -> _T_co: ... + def pow(base: _SupportsPow3[_E, _M, _T_co], exp: _E, mod: _M = ...) -> _T_co: ... @overload - def pow(base: _SupportsPow3[_E, _M, _T_co], exp: _E, mod: _M) -> _T_co: ... + def pow(base: _SupportsSomeKindOfPow, exp: float, mod: None = ...) -> Any: ... + @overload + def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = ...) -> complex: ... else: @overload - def pow( - __base: int, __exp: int, __mod: None = ... - ) -> Any: ... # returns int or float depending on whether exp is non-negative + def pow(__base: int, __exp: int, __mod: Literal[0]) -> NoReturn: ... @overload def pow(__base: int, __exp: int, __mod: int) -> int: ... @overload - def pow(__base: float, __exp: float, __mod: None = ...) -> float: ... + def pow(__base: int, __exp: _PositiveInteger, __mod: None = ...) -> int: ... # type: ignore[misc] + @overload + def pow(__base: int, __exp: _NegativeInteger, __mod: None = ...) -> float: ... # type: ignore[misc] + @overload + def pow(__base: int, __exp: int, __mod: None = ...) -> Any: ... + @overload + def pow(__base: float, __exp: int, __mod: None = ...) -> float: ... + @overload + def pow(__base: float, __exp: complex | _SupportsSomeKindOfPow, __mod: None = ...) -> Any: ... + @overload + def pow(__base: complex, __exp: complex | _SupportsSomeKindOfPow, __mod: None = ...) -> complex: ... @overload - def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E) -> _T_co: ... + def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E, __mod: None = ...) -> _T_co: ... @overload - def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M) -> _T_co: ... + def pow(__base: _SupportsPow3NoneOnly[_E, _T_co], __exp: _E, __mod: None = ...) -> _T_co: ... + @overload + def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M = ...) -> _T_co: ... + @overload + def pow(__base: _SupportsSomeKindOfPow, __exp: float, __mod: None = ...) -> Any: ... + @overload + def pow(__base: _SupportsSomeKindOfPow, __exp: complex, __mod: None = ...) -> complex: ... def quit(code: object = ...) -> NoReturn: ... @@ -1304,6 +1377,9 @@ def round(number: SupportsRound[Any]) -> int: ... def round(number: SupportsRound[Any], ndigits: None) -> int: ... @overload def round(number: SupportsRound[_T], ndigits: SupportsIndex) -> _T: ... + +# See https://github.com/python/typeshed/pull/6292#discussion_r748875189 +# for why arg 3 of `setattr` should be annotated with `Any` and not `object` def setattr(__obj: object, __name: str, __value: Any) -> None: ... @overload def sorted(__iterable: Iterable[SupportsLessThanT], *, key: None = ..., reverse: bool = ...) -> list[SupportsLessThanT]: ... @@ -1322,6 +1398,8 @@ else: @overload def sum(__iterable: Iterable[_T], __start: _S) -> _T | _S: ... +# The argument to `vars()` has to have a `__dict__` attribute, so can't be annotated with `object` +# (A "SupportsDunderDict" protocol doesn't work) def vars(__object: Any = ...) -> dict[str, Any]: ... class zip(Iterator[_T_co], Generic[_T_co]): @@ -1401,16 +1479,19 @@ class zip(Iterator[_T_co], Generic[_T_co]): def __iter__(self) -> Iterator[_T_co]: ... def __next__(self) -> _T_co: ... +# Signature of `builtins.__import__` should be kept identical to `importlib.__import__` +# Return type of `__import__` should be kept the same as return type of `importlib.import_module` def __import__( name: str, - globals: Mapping[str, Any] | None = ..., - locals: Mapping[str, Any] | None = ..., + globals: Mapping[str, object] | None = ..., + locals: Mapping[str, object] | None = ..., fromlist: Sequence[str] = ..., level: int = ..., -) -> Any: ... +) -> types.ModuleType: ... # Actually the type of Ellipsis is , but since it's # not exposed anywhere under that name, we make it private here. +@final class ellipsis: ... Ellipsis: ellipsis @@ -1424,7 +1505,7 @@ class BaseException(object): def __init__(self, *args: object) -> None: ... def __str__(self) -> str: ... def __repr__(self) -> str: ... - def with_traceback(self: _TBE, tb: TracebackType | None) -> _TBE: ... + def with_traceback(self: _TBE, __tb: TracebackType | None) -> _TBE: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ... diff --git a/mypy/typeshed/stdlib/bz2.pyi b/mypy/typeshed/stdlib/bz2.pyi index e7b57ec54db0..c49832759fa8 100644 --- a/mypy/typeshed/stdlib/bz2.pyi +++ b/mypy/typeshed/stdlib/bz2.pyi @@ -3,7 +3,7 @@ import sys from _compression import BaseStream from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer from typing import IO, Any, Iterable, Protocol, TextIO, TypeVar, overload -from typing_extensions import Literal, SupportsIndex +from typing_extensions import Literal, SupportsIndex, final # The following attributes and methods are optional: # def fileno(self) -> int: ... @@ -118,11 +118,13 @@ class BZ2File(BaseStream, IO[bytes]): def write(self, data: ReadableBuffer) -> int: ... def writelines(self, seq: Iterable[ReadableBuffer]) -> None: ... +@final class BZ2Compressor(object): def __init__(self, compresslevel: int = ...) -> None: ... def compress(self, __data: bytes) -> bytes: ... def flush(self) -> bytes: ... +@final class BZ2Decompressor(object): def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... @property diff --git a/mypy/typeshed/stdlib/cmath.pyi b/mypy/typeshed/stdlib/cmath.pyi index 3f3327074579..04c2b632d411 100644 --- a/mypy/typeshed/stdlib/cmath.pyi +++ b/mypy/typeshed/stdlib/cmath.pyi @@ -1,5 +1,9 @@ +import sys from typing import SupportsComplex, SupportsFloat, Union +if sys.version_info >= (3, 8): + from typing import SupportsIndex + e: float pi: float inf: float @@ -8,7 +12,10 @@ nan: float nanj: complex tau: float -_C = Union[SupportsFloat, SupportsComplex, complex] +if sys.version_info >= (3, 8): + _C = Union[SupportsFloat, SupportsComplex, SupportsIndex, complex] +else: + _C = Union[SupportsFloat, SupportsComplex, complex] def acos(__z: _C) -> complex: ... def acosh(__z: _C) -> complex: ... diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index 8802a255e471..66a76941beee 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -1,7 +1,8 @@ import sys +from _collections_abc import dict_items, dict_keys, dict_values from _typeshed import Self -from builtins import _dict_items, _dict_keys, _dict_values from typing import Any, Dict, Generic, NoReturn, Tuple, Type, TypeVar, overload +from typing_extensions import final if sys.version_info >= (3, 10): from typing import Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Reversible, Sequence @@ -40,9 +41,9 @@ class UserDict(MutableMapping[_KT, _VT]): def __delitem__(self, key: _KT) -> None: ... def __iter__(self) -> Iterator[_KT]: ... def __contains__(self, key: object) -> bool: ... - def copy(self: _S) -> _S: ... + def copy(self: Self) -> Self: ... @classmethod - def fromkeys(cls: Type[_S], iterable: Iterable[_KT], value: _VT | None = ...) -> _S: ... + def fromkeys(cls: Type[Self], iterable: Iterable[_KT], value: _VT | None = ...) -> Self: ... class UserList(MutableSequence[_T]): data: list[_T] @@ -160,43 +161,45 @@ class deque(MutableSequence[_T], Generic[_T]): @property def maxlen(self) -> int | None: ... def __init__(self, iterable: Iterable[_T] = ..., maxlen: int | None = ...) -> None: ... - def append(self, x: _T) -> None: ... - def appendleft(self, x: _T) -> None: ... + def append(self, __x: _T) -> None: ... + def appendleft(self, __x: _T) -> None: ... def clear(self) -> None: ... - def copy(self) -> deque[_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 = ..., stop: int = ...) -> int: ... + def copy(self: _S) -> _S: ... + 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 = ..., __stop: int = ...) -> int: ... def pop(self) -> _T: ... # type: ignore def popleft(self) -> _T: ... - def remove(self, value: _T) -> None: ... + def remove(self, __value: _T) -> None: ... def reverse(self) -> None: ... - def rotate(self, n: int = ...) -> None: ... + def rotate(self, __n: int = ...) -> None: ... + def __copy__(self: _S) -> _S: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... def __str__(self) -> str: ... # These methods of deque don't really take slices, but we need to # define them as taking a slice to satisfy MutableSequence. @overload - def __getitem__(self, index: int) -> _T: ... + def __getitem__(self, __index: int) -> _T: ... @overload - def __getitem__(self, s: slice) -> MutableSequence[_T]: ... + def __getitem__(self, __s: slice) -> MutableSequence[_T]: ... @overload - def __setitem__(self, i: int, x: _T) -> None: ... + def __setitem__(self, __i: int, __x: _T) -> None: ... @overload - def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + def __setitem__(self, __s: slice, __o: Iterable[_T]) -> None: ... @overload - def __delitem__(self, i: int) -> None: ... + def __delitem__(self, __i: int) -> None: ... @overload - def __delitem__(self, s: slice) -> None: ... - def __contains__(self, o: object) -> bool: ... + def __delitem__(self, __s: slice) -> None: ... + def __contains__(self, __o: object) -> bool: ... + def __reduce__(self: Self) -> tuple[Type[Self], tuple[()], None, Iterator[_T]]: ... def __reversed__(self) -> Iterator[_T]: ... - def __iadd__(self: _S, iterable: Iterable[_T]) -> _S: ... - def __add__(self, other: deque[_T]) -> deque[_T]: ... - def __mul__(self, other: int) -> deque[_T]: ... - def __imul__(self, other: int) -> None: ... + def __iadd__(self: _S, __iterable: Iterable[_T]) -> _S: ... + def __add__(self: _S, __other: _S) -> _S: ... + def __mul__(self: _S, __other: int) -> _S: ... + def __imul__(self: _S, __other: int) -> _S: ... class Counter(Dict[_T, int], Generic[_T]): @overload @@ -205,7 +208,7 @@ class Counter(Dict[_T, int], Generic[_T]): def __init__(self, __mapping: Mapping[_T, int]) -> None: ... @overload def __init__(self, __iterable: Iterable[_T]) -> None: ... - def copy(self: _S) -> _S: ... + def copy(self: Self) -> Self: ... def elements(self) -> Iterator[_T]: ... def most_common(self, n: int | None = ...) -> list[tuple[_T, int]]: ... @classmethod @@ -238,44 +241,47 @@ class Counter(Dict[_T, int], Generic[_T]): def __iand__(self, other: Counter[_T]) -> Counter[_T]: ... def __ior__(self, other: Counter[_T]) -> Counter[_T]: ... # type: ignore -class _OrderedDictKeysView(_dict_keys[_KT_co, _VT_co], Reversible[_KT_co]): +@final +class _OrderedDictKeysView(dict_keys[_KT_co, _VT_co], Reversible[_KT_co]): # type: ignore[misc] def __reversed__(self) -> Iterator[_KT_co]: ... -class _OrderedDictItemsView(_dict_items[_KT_co, _VT_co], Reversible[Tuple[_KT_co, _VT_co]]): +@final +class _OrderedDictItemsView(dict_items[_KT_co, _VT_co], Reversible[Tuple[_KT_co, _VT_co]]): # type: ignore[misc] def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... -# The generics are the wrong way around because of a mypy limitation -# https://github.com/python/mypy/issues/11138 -class _OrderedDictValuesView(_dict_values[_VT_co, _KT_co], Reversible[_VT_co], Generic[_VT_co, _KT_co]): +@final +class _OrderedDictValuesView(dict_values[_KT_co, _VT_co], Reversible[_VT_co], Generic[_KT_co, _VT_co]): # type: ignore[misc] def __reversed__(self) -> Iterator[_VT_co]: ... class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): def popitem(self, last: bool = ...) -> tuple[_KT, _VT]: ... def move_to_end(self, key: _KT, last: bool = ...) -> None: ... - def copy(self: _S) -> _S: ... + def copy(self: Self) -> Self: ... def __reversed__(self) -> Iterator[_KT]: ... def keys(self) -> _OrderedDictKeysView[_KT, _VT]: ... def items(self) -> _OrderedDictItemsView[_KT, _VT]: ... - def values(self) -> _OrderedDictValuesView[_VT, _KT]: ... + def values(self) -> _OrderedDictValuesView[_KT, _VT]: ... class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): default_factory: Callable[[], _VT] | None @overload def __init__(self, **kwargs: _VT) -> None: ... @overload - def __init__(self, default_factory: Callable[[], _VT] | None) -> None: ... + def __init__(self, __default_factory: Callable[[], _VT] | None) -> None: ... @overload - def __init__(self, default_factory: Callable[[], _VT] | None, **kwargs: _VT) -> None: ... + def __init__(self, __default_factory: Callable[[], _VT] | None, **kwargs: _VT) -> None: ... @overload - def __init__(self, default_factory: Callable[[], _VT] | None, map: Mapping[_KT, _VT]) -> None: ... + def __init__(self, __default_factory: Callable[[], _VT] | None, __map: Mapping[_KT, _VT]) -> None: ... @overload - def __init__(self, default_factory: Callable[[], _VT] | None, map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + def __init__(self, __default_factory: Callable[[], _VT] | None, __map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... @overload - def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]]) -> None: ... + def __init__(self, __default_factory: Callable[[], _VT] | None, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ... @overload - def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - def __missing__(self, key: _KT) -> _VT: ... - # TODO __reversed__ + def __init__( + self, __default_factory: Callable[[], _VT] | None, __iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT + ) -> None: ... + def __missing__(self, __key: _KT) -> _VT: ... + def __copy__(self: _S) -> _S: ... def copy(self: _S) -> _S: ... class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @@ -290,3 +296,8 @@ class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def __iter__(self) -> Iterator[_KT]: ... def __len__(self) -> int: ... def __missing__(self, key: _KT) -> _VT: ... # undocumented + def setdefault(self, key: _KT, default: _VT = ...) -> _VT: ... + @overload + def pop(self, key: _KT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi index 7a35bfc6ed77..5ad5b65d3bec 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi @@ -1,6 +1,6 @@ import queue import sys -from collections.abc import Iterable, Mapping, Set +from collections.abc import Iterable, Mapping, Set # equivalent to typing.AbstractSet, not builtins.set from threading import Lock, Semaphore, Thread from typing import Any, Callable, Generic, Tuple, TypeVar from weakref import ref diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index 8c362cfd1633..9d968e092ca5 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -1,14 +1,14 @@ import sys -from _typeshed import Self +from _typeshed import Self, StrOrBytesPath from types import TracebackType from typing import ( IO, Any, - AsyncContextManager, AsyncIterator, Awaitable, Callable, ContextManager, + Generic, Iterator, Optional, Type, @@ -19,6 +19,8 @@ from typing_extensions import ParamSpec, Protocol AbstractContextManager = ContextManager if sys.version_info >= (3, 7): + from typing import AsyncContextManager + AbstractAsyncContextManager = AsyncContextManager _T = TypeVar("_T") @@ -28,53 +30,53 @@ _F = TypeVar("_F", bound=Callable[..., Any]) _P = ParamSpec("_P") _ExitFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], bool] -_CM_EF = TypeVar("_CM_EF", ContextManager[Any], _ExitFunc) +_CM_EF = TypeVar("_CM_EF", AbstractContextManager[Any], _ExitFunc) -class _GeneratorContextManager(ContextManager[_T_co]): +class _GeneratorContextManager(AbstractContextManager[_T_co]): def __call__(self, func: _F) -> _F: ... # type ignore to deal with incomplete ParamSpec support in mypy def contextmanager(func: Callable[_P, Iterator[_T]]) -> Callable[_P, _GeneratorContextManager[_T]]: ... # type: ignore if sys.version_info >= (3, 7): - def asynccontextmanager(func: Callable[_P, AsyncIterator[_T]]) -> Callable[_P, AsyncContextManager[_T]]: ... # type: ignore + def asynccontextmanager(func: Callable[_P, AsyncIterator[_T]]) -> Callable[_P, AbstractAsyncContextManager[_T]]: ... # type: ignore class _SupportsClose(Protocol): def close(self) -> object: ... _SupportsCloseT = TypeVar("_SupportsCloseT", bound=_SupportsClose) -class closing(ContextManager[_SupportsCloseT]): +class closing(AbstractContextManager[_SupportsCloseT]): def __init__(self, thing: _SupportsCloseT) -> None: ... if sys.version_info >= (3, 10): class _SupportsAclose(Protocol): def aclose(self) -> Awaitable[object]: ... _SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) - class aclosing(AsyncContextManager[_SupportsAcloseT]): + class aclosing(AbstractAsyncContextManager[_SupportsAcloseT]): def __init__(self, thing: _SupportsAcloseT) -> None: ... _AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]]) class AsyncContextDecorator: def __call__(self, func: _AF) -> _AF: ... -class suppress(ContextManager[None]): +class suppress(AbstractContextManager[None]): def __init__(self, *exceptions: Type[BaseException]) -> None: ... def __exit__( self, exctype: Type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None ) -> bool: ... -class redirect_stdout(ContextManager[_T_io]): +class redirect_stdout(AbstractContextManager[_T_io]): def __init__(self, new_target: _T_io) -> None: ... -class redirect_stderr(ContextManager[_T_io]): +class redirect_stderr(AbstractContextManager[_T_io]): def __init__(self, new_target: _T_io) -> None: ... class ContextDecorator: def __call__(self, func: _F) -> _F: ... -class ExitStack(ContextManager[ExitStack]): +class ExitStack(AbstractContextManager[ExitStack]): def __init__(self) -> None: ... - def enter_context(self, cm: ContextManager[_T]) -> _T: ... + def enter_context(self, cm: AbstractContextManager[_T]) -> _T: ... def push(self, exit: _CM_EF) -> _CM_EF: ... def callback(self, __callback: Callable[..., Any], *args: Any, **kwds: Any) -> Callable[..., Any]: ... def pop_all(self: Self) -> Self: ... @@ -87,11 +89,11 @@ class ExitStack(ContextManager[ExitStack]): if sys.version_info >= (3, 7): _ExitCoroFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], Awaitable[bool]] _CallbackCoroFunc = Callable[..., Awaitable[Any]] - _ACM_EF = TypeVar("_ACM_EF", AsyncContextManager[Any], _ExitCoroFunc) - class AsyncExitStack(AsyncContextManager[AsyncExitStack]): + _ACM_EF = TypeVar("_ACM_EF", AbstractAsyncContextManager[Any], _ExitCoroFunc) + class AsyncExitStack(AbstractAsyncContextManager[AsyncExitStack]): def __init__(self) -> None: ... - def enter_context(self, cm: ContextManager[_T]) -> _T: ... - def enter_async_context(self, cm: AsyncContextManager[_T]) -> Awaitable[_T]: ... + def enter_context(self, cm: AbstractContextManager[_T]) -> _T: ... + def enter_async_context(self, cm: AbstractAsyncContextManager[_T]) -> Awaitable[_T]: ... def push(self, exit: _CM_EF) -> _CM_EF: ... def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: ... def callback(self, __callback: Callable[..., Any], *args: Any, **kwds: Any) -> Callable[..., Any]: ... @@ -124,3 +126,11 @@ elif sys.version_info >= (3, 7): def __init__(self: nullcontext[_T], enter_result: _T) -> None: ... def __enter__(self) -> _T: ... def __exit__(self, *exctype: Any) -> None: ... + +if sys.version_info >= (3, 11): + _T_fd_or_any_path = TypeVar("_T_fd_or_any_path", bound=int | StrOrBytesPath) + class chdir(AbstractContextManager[None], Generic[_T_fd_or_any_path]): + path: _T_fd_or_any_path + def __init__(self, path: _T_fd_or_any_path) -> None: ... + def __enter__(self) -> None: ... + def __exit__(self, *excinfo: object) -> None: ... diff --git a/mypy/typeshed/stdlib/ctypes/__init__.pyi b/mypy/typeshed/stdlib/ctypes/__init__.pyi index 4b3dd4b15b51..bbe083f5d4c4 100644 --- a/mypy/typeshed/stdlib/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/ctypes/__init__.pyi @@ -173,7 +173,7 @@ def POINTER(type: Type[_CT]) -> Type[pointer[_CT]]: ... # ctypes._Pointer in that it is the base class for all pointer types. Unlike the real _Pointer, # it can be instantiated directly (to mimic the behavior of the real pointer function). class pointer(Generic[_CT], _PointerLike, _CData): - _type_: ClassVar[Type[_CT]] + _type_: Type[_CT] contents: _CT def __init__(self, arg: _CT = ...) -> None: ... @overload @@ -268,8 +268,8 @@ class BigEndianStructure(Structure): ... class LittleEndianStructure(Structure): ... class Array(Generic[_CT], _CData): - _length_: ClassVar[int] - _type_: ClassVar[Type[_CT]] + _length_: int + _type_: Type[_CT] raw: bytes # Note: only available if _CT == c_char value: Any # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise # TODO These methods cannot be annotated correctly at the moment. diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index 746643d8433c..bd4d47e051ec 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -1,21 +1,24 @@ import sys from time import struct_time -from typing import ClassVar, NamedTuple, SupportsAbs, Type, TypeVar, overload +from typing import ClassVar, NamedTuple, NoReturn, SupportsAbs, Type, TypeVar, overload +from typing_extensions import final _S = TypeVar("_S") +_D = TypeVar("_D", bound=date) MINYEAR: int MAXYEAR: int class tzinfo: - def tzname(self, dt: datetime | None) -> str | None: ... - def utcoffset(self, dt: datetime | None) -> timedelta | None: ... - def dst(self, dt: datetime | None) -> timedelta | None: ... - def fromutc(self, dt: datetime) -> datetime: ... + def tzname(self, __dt: datetime | None) -> str | None: ... + def utcoffset(self, __dt: datetime | None) -> timedelta | None: ... + def dst(self, __dt: datetime | None) -> timedelta | None: ... + def fromutc(self, __dt: datetime) -> datetime: ... # Alias required to avoid name conflicts with date(time).tzinfo. _tzinfo = tzinfo +@final class timezone(tzinfo): utc: ClassVar[timezone] min: ClassVar[timezone] @@ -39,10 +42,10 @@ class date: @classmethod def today(cls: Type[_S]) -> _S: ... @classmethod - def fromordinal(cls: Type[_S], n: int) -> _S: ... + def fromordinal(cls: Type[_S], __n: int) -> _S: ... if sys.version_info >= (3, 7): @classmethod - def fromisoformat(cls: Type[_S], date_string: str) -> _S: ... + def fromisoformat(cls: Type[_S], __date_string: str) -> _S: ... if sys.version_info >= (3, 8): @classmethod def fromisocalendar(cls: Type[_S], year: int, week: int, day: int) -> _S: ... @@ -54,25 +57,34 @@ class date: def day(self) -> int: ... def ctime(self) -> str: ... def strftime(self, fmt: str) -> str: ... - def __format__(self, fmt: str) -> str: ... + def __format__(self, __fmt: str) -> str: ... def isoformat(self) -> str: ... def timetuple(self) -> struct_time: ... def toordinal(self) -> int: ... def replace(self, year: int = ..., month: int = ..., day: int = ...) -> date: ... - def __le__(self, other: date) -> bool: ... - def __lt__(self, other: date) -> bool: ... - def __ge__(self, other: date) -> bool: ... - def __gt__(self, other: date) -> bool: ... + def __le__(self, __other: date) -> bool: ... + def __lt__(self, __other: date) -> bool: ... + def __ge__(self, __other: date) -> bool: ... + def __gt__(self, __other: date) -> bool: ... if sys.version_info >= (3, 8): - def __add__(self: _S, other: timedelta) -> _S: ... - def __radd__(self: _S, other: timedelta) -> _S: ... + def __add__(self: _S, __other: timedelta) -> _S: ... + def __radd__(self: _S, __other: timedelta) -> _S: ... + @overload + def __sub__(self: _D, __other: timedelta) -> _D: ... + @overload + def __sub__(self, __other: datetime) -> NoReturn: ... + @overload + def __sub__(self: _D, __other: _D) -> timedelta: ... else: - def __add__(self, other: timedelta) -> date: ... - def __radd__(self, other: timedelta) -> date: ... - @overload - def __sub__(self, other: timedelta) -> date: ... - @overload - def __sub__(self, other: date) -> timedelta: ... + # Prior to Python 3.8, arithmetic operations always returned `date`, even in subclasses + def __add__(self, __other: timedelta) -> date: ... + def __radd__(self, __other: timedelta) -> date: ... + @overload + def __sub__(self, __other: timedelta) -> date: ... + @overload + def __sub__(self, __other: datetime) -> NoReturn: ... + @overload + def __sub__(self, __other: date) -> timedelta: ... def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... @@ -107,17 +119,17 @@ class time: def tzinfo(self) -> _tzinfo | None: ... @property def fold(self) -> int: ... - def __le__(self, other: time) -> bool: ... - def __lt__(self, other: time) -> bool: ... - def __ge__(self, other: time) -> bool: ... - def __gt__(self, other: time) -> bool: ... + def __le__(self, __other: time) -> bool: ... + def __lt__(self, __other: time) -> bool: ... + def __ge__(self, __other: time) -> bool: ... + def __gt__(self, __other: time) -> bool: ... def __hash__(self) -> int: ... def isoformat(self, timespec: str = ...) -> str: ... if sys.version_info >= (3, 7): @classmethod - def fromisoformat(cls: Type[_S], time_string: str) -> _S: ... + def fromisoformat(cls: Type[_S], __time_string: str) -> _S: ... def strftime(self, fmt: str) -> str: ... - def __format__(self, fmt: str) -> str: ... + def __format__(self, __fmt: str) -> str: ... def utcoffset(self) -> timedelta | None: ... def tzname(self) -> str | None: ... def dst(self) -> timedelta | None: ... @@ -156,29 +168,29 @@ class timedelta(SupportsAbs[timedelta]): @property def microseconds(self) -> int: ... def total_seconds(self) -> float: ... - def __add__(self, other: timedelta) -> timedelta: ... - def __radd__(self, other: timedelta) -> timedelta: ... - def __sub__(self, other: timedelta) -> timedelta: ... - def __rsub__(self, other: timedelta) -> timedelta: ... + def __add__(self, __other: timedelta) -> timedelta: ... + def __radd__(self, __other: timedelta) -> timedelta: ... + def __sub__(self, __other: timedelta) -> timedelta: ... + def __rsub__(self, __other: timedelta) -> timedelta: ... def __neg__(self) -> timedelta: ... def __pos__(self) -> timedelta: ... def __abs__(self) -> timedelta: ... - def __mul__(self, other: float) -> timedelta: ... - def __rmul__(self, other: float) -> timedelta: ... + def __mul__(self, __other: float) -> timedelta: ... + def __rmul__(self, __other: float) -> timedelta: ... @overload - def __floordiv__(self, other: timedelta) -> int: ... + def __floordiv__(self, __other: timedelta) -> int: ... @overload - def __floordiv__(self, other: int) -> timedelta: ... + def __floordiv__(self, __other: int) -> timedelta: ... @overload - def __truediv__(self, other: timedelta) -> float: ... + def __truediv__(self, __other: timedelta) -> float: ... @overload - def __truediv__(self, other: float) -> timedelta: ... - def __mod__(self, other: timedelta) -> timedelta: ... - def __divmod__(self, other: timedelta) -> tuple[int, timedelta]: ... - def __le__(self, other: timedelta) -> bool: ... - def __lt__(self, other: timedelta) -> bool: ... - def __ge__(self, other: timedelta) -> bool: ... - def __gt__(self, other: timedelta) -> bool: ... + def __truediv__(self, __other: float) -> timedelta: ... + def __mod__(self, __other: timedelta) -> timedelta: ... + def __divmod__(self, __other: timedelta) -> tuple[int, timedelta]: ... + def __le__(self, __other: timedelta) -> bool: ... + def __lt__(self, __other: timedelta) -> bool: ... + def __ge__(self, __other: timedelta) -> bool: ... + def __gt__(self, __other: timedelta) -> bool: ... def __bool__(self) -> bool: ... def __hash__(self) -> int: ... @@ -200,12 +212,6 @@ class datetime(date): fold: int = ..., ) -> _S: ... @property - def year(self) -> int: ... - @property - def month(self) -> int: ... - @property - def day(self) -> int: ... - @property def hour(self) -> int: ... @property def minute(self) -> int: ... @@ -217,14 +223,13 @@ class datetime(date): def tzinfo(self) -> _tzinfo | None: ... @property def fold(self) -> int: ... + # The first parameter in `fromtimestamp` is actually positional-or-keyword, + # but it is named "timestamp" in the C implementation and "t" in the Python implementation, + # so it is only truly *safe* to pass it as a positional argument. @classmethod - def fromtimestamp(cls: Type[_S], t: float, tz: _tzinfo | None = ...) -> _S: ... - @classmethod - def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ... - @classmethod - def today(cls: Type[_S]) -> _S: ... + def fromtimestamp(cls: Type[_S], __timestamp: float, tz: _tzinfo | None = ...) -> _S: ... @classmethod - def fromordinal(cls: Type[_S], n: int) -> _S: ... + def utcfromtimestamp(cls: Type[_S], __t: float) -> _S: ... if sys.version_info >= (3, 8): @classmethod def now(cls: Type[_S], tz: _tzinfo | None = ...) -> _S: ... @@ -241,11 +246,7 @@ class datetime(date): def combine(cls, date: _date, time: _time, tzinfo: _tzinfo | None = ...) -> datetime: ... if sys.version_info >= (3, 7): @classmethod - def fromisoformat(cls: Type[_S], date_string: str) -> _S: ... - def strftime(self, fmt: str) -> str: ... - def __format__(self, fmt: str) -> str: ... - def toordinal(self) -> int: ... - def timetuple(self) -> struct_time: ... + def fromisoformat(cls: Type[_S], __date_string: str) -> _S: ... def timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... def date(self) -> _date: ... @@ -271,27 +272,27 @@ class datetime(date): def ctime(self) -> str: ... def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... @classmethod - def strptime(cls, date_string: str, format: str) -> datetime: ... + def strptime(cls, __date_string: str, __format: str) -> datetime: ... def utcoffset(self) -> timedelta | None: ... def tzname(self) -> str | None: ... def dst(self) -> timedelta | None: ... - def __le__(self, other: datetime) -> bool: ... # type: ignore - def __lt__(self, other: datetime) -> bool: ... # type: ignore - def __ge__(self, other: datetime) -> bool: ... # type: ignore - def __gt__(self, other: datetime) -> bool: ... # type: ignore + def __le__(self, __other: datetime) -> bool: ... # type: ignore + def __lt__(self, __other: datetime) -> bool: ... # type: ignore + def __ge__(self, __other: datetime) -> bool: ... # type: ignore + def __gt__(self, __other: datetime) -> bool: ... # type: ignore if sys.version_info >= (3, 8): - def __add__(self: _S, other: timedelta) -> _S: ... - def __radd__(self: _S, other: timedelta) -> _S: ... + @overload # type: ignore[override] + def __sub__(self: _D, __other: timedelta) -> _D: ... + @overload + def __sub__(self: _D, __other: _D) -> timedelta: ... else: - def __add__(self, other: timedelta) -> datetime: ... - def __radd__(self, other: timedelta) -> datetime: ... - @overload # type: ignore - def __sub__(self, other: datetime) -> timedelta: ... - @overload - def __sub__(self, other: timedelta) -> datetime: ... - def __hash__(self) -> int: ... - def weekday(self) -> int: ... - def isoweekday(self) -> int: ... + # Prior to Python 3.8, arithmetic operations always returned `datetime`, even in subclasses + def __add__(self, __other: timedelta) -> datetime: ... + def __radd__(self, __other: timedelta) -> datetime: ... + @overload # type: ignore[override] + def __sub__(self, __other: datetime) -> timedelta: ... + @overload + def __sub__(self, __other: timedelta) -> datetime: ... if sys.version_info >= (3, 9): def isocalendar(self) -> _IsoCalendarDate: ... else: diff --git a/mypy/typeshed/stdlib/decimal.pyi b/mypy/typeshed/stdlib/decimal.pyi index f08ed02d6482..30c8e973348d 100644 --- a/mypy/typeshed/stdlib/decimal.pyi +++ b/mypy/typeshed/stdlib/decimal.pyi @@ -57,29 +57,29 @@ class Decimal(object): def as_integer_ratio(self) -> tuple[int, int]: ... def to_eng_string(self, context: Context | None = ...) -> str: ... def __abs__(self) -> Decimal: ... - def __add__(self, other: _Decimal) -> Decimal: ... - def __divmod__(self, other: _Decimal) -> tuple[Decimal, Decimal]: ... - def __eq__(self, other: object) -> bool: ... - def __floordiv__(self, other: _Decimal) -> Decimal: ... - def __ge__(self, other: _ComparableNum) -> bool: ... - def __gt__(self, other: _ComparableNum) -> bool: ... - def __le__(self, other: _ComparableNum) -> bool: ... - def __lt__(self, other: _ComparableNum) -> bool: ... - def __mod__(self, other: _Decimal) -> Decimal: ... - def __mul__(self, other: _Decimal) -> Decimal: ... + def __add__(self, __other: _Decimal) -> Decimal: ... + def __divmod__(self, __other: _Decimal) -> tuple[Decimal, Decimal]: ... + def __eq__(self, __other: object) -> bool: ... + def __floordiv__(self, __other: _Decimal) -> Decimal: ... + def __ge__(self, __other: _ComparableNum) -> bool: ... + def __gt__(self, __other: _ComparableNum) -> bool: ... + def __le__(self, __other: _ComparableNum) -> bool: ... + def __lt__(self, __other: _ComparableNum) -> bool: ... + def __mod__(self, __other: _Decimal) -> Decimal: ... + def __mul__(self, __other: _Decimal) -> Decimal: ... def __neg__(self) -> Decimal: ... def __pos__(self) -> Decimal: ... - def __pow__(self, other: _Decimal, modulo: _Decimal | None = ...) -> Decimal: ... - def __radd__(self, other: _Decimal) -> Decimal: ... - def __rdivmod__(self, other: _Decimal) -> tuple[Decimal, Decimal]: ... - def __rfloordiv__(self, other: _Decimal) -> Decimal: ... - def __rmod__(self, other: _Decimal) -> Decimal: ... - def __rmul__(self, other: _Decimal) -> Decimal: ... - def __rsub__(self, other: _Decimal) -> Decimal: ... - def __rtruediv__(self, other: _Decimal) -> Decimal: ... + def __pow__(self, __other: _Decimal, __modulo: _Decimal | None = ...) -> Decimal: ... + def __radd__(self, __other: _Decimal) -> Decimal: ... + def __rdivmod__(self, __other: _Decimal) -> tuple[Decimal, Decimal]: ... + def __rfloordiv__(self, __other: _Decimal) -> Decimal: ... + def __rmod__(self, __other: _Decimal) -> Decimal: ... + def __rmul__(self, __other: _Decimal) -> Decimal: ... + def __rsub__(self, __other: _Decimal) -> Decimal: ... + def __rtruediv__(self, __other: _Decimal) -> Decimal: ... def __str__(self) -> str: ... - def __sub__(self, other: _Decimal) -> Decimal: ... - def __truediv__(self, other: _Decimal) -> Decimal: ... + def __sub__(self, __other: _Decimal) -> Decimal: ... + def __truediv__(self, __other: _Decimal) -> Decimal: ... def remainder_near(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def __float__(self) -> float: ... def __int__(self) -> int: ... @@ -93,11 +93,11 @@ class Decimal(object): @overload def __round__(self) -> int: ... @overload - def __round__(self, ndigits: int) -> Decimal: ... + def __round__(self, __ndigits: int) -> Decimal: ... def __floor__(self) -> int: ... def __ceil__(self) -> int: ... def fma(self, other: _Decimal, third: _Decimal, context: Context | None = ...) -> Decimal: ... - def __rpow__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... + def __rpow__(self, __other: _Decimal, __context: Context | None = ...) -> Decimal: ... def normalize(self, context: Context | None = ...) -> Decimal: ... def quantize(self, exp: _Decimal, rounding: str | None = ..., context: Context | None = ...) -> Decimal: ... def same_quantum(self, other: _Decimal, context: Context | None = ...) -> bool: ... @@ -145,8 +145,8 @@ class Decimal(object): def shift(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def __reduce__(self) -> tuple[Type[Decimal], tuple[str]]: ... def __copy__(self) -> Decimal: ... - def __deepcopy__(self, memo: Any) -> Decimal: ... - def __format__(self, specifier: str, context: Context | None = ...) -> str: ... + def __deepcopy__(self, __memo: Any) -> Decimal: ... + def __format__(self, __specifier: str, __context: Context | None = ...) -> str: ... class _ContextManager(object): new_context: Context @@ -180,7 +180,7 @@ class Context(object): ) -> None: ... # __setattr__() only allows to set a specific set of attributes, # already defined above. - def __delattr__(self, name: str) -> None: ... + def __delattr__(self, __name: str) -> None: ... def __reduce__(self) -> tuple[Type[Context], Tuple[Any, ...]]: ... def clear_flags(self) -> None: ... def clear_traps(self) -> None: ... diff --git a/mypy/typeshed/stdlib/email/_header_value_parser.pyi b/mypy/typeshed/stdlib/email/_header_value_parser.pyi index a4c060ef46a5..f1b08b5d5805 100644 --- a/mypy/typeshed/stdlib/email/_header_value_parser.pyi +++ b/mypy/typeshed/stdlib/email/_header_value_parser.pyi @@ -1,22 +1,22 @@ import sys from email.errors import HeaderParseError, MessageDefect from email.policy import Policy -from typing import Any, Iterable, Iterator, List, Pattern, Set, Type, TypeVar, Union +from typing import Any, Iterable, Iterator, List, Pattern, Type, TypeVar, Union from typing_extensions import Final _T = TypeVar("_T") -WSP: Final[Set[str]] -CFWS_LEADER: Final[Set[str]] -SPECIALS: Final[Set[str]] -ATOM_ENDS: Final[Set[str]] -DOT_ATOM_ENDS: Final[Set[str]] -PHRASE_ENDS: Final[Set[str]] -TSPECIALS: Final[Set[str]] -TOKEN_ENDS: Final[Set[str]] -ASPECIALS: Final[Set[str]] -ATTRIBUTE_ENDS: Final[Set[str]] -EXTENDED_ATTRIBUTE_ENDS: Final[Set[str]] +WSP: Final[set[str]] +CFWS_LEADER: Final[set[str]] +SPECIALS: Final[set[str]] +ATOM_ENDS: Final[set[str]] +DOT_ATOM_ENDS: Final[set[str]] +PHRASE_ENDS: Final[set[str]] +TSPECIALS: Final[set[str]] +TOKEN_ENDS: Final[set[str]] +ASPECIALS: Final[set[str]] +ATTRIBUTE_ENDS: Final[set[str]] +EXTENDED_ATTRIBUTE_ENDS: Final[set[str]] def quote_string(value: Any) -> str: ... diff --git a/mypy/typeshed/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index 6fe4bb6f8e9e..b5e52bf59920 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -1,7 +1,8 @@ import sys import types from _typeshed import SupportsItems, SupportsLessThan -from typing import Any, Callable, Generic, Hashable, Iterable, NamedTuple, Sequence, Set, Sized, Tuple, Type, TypeVar, overload +from typing import Any, Callable, Generic, Hashable, Iterable, NamedTuple, Sequence, Sized, Tuple, Type, TypeVar, overload +from typing_extensions import final if sys.version_info >= (3, 9): from types import GenericAlias @@ -22,6 +23,7 @@ class _CacheInfo(NamedTuple): maxsize: int currsize: int +@final class _lru_cache_wrapper(Generic[_T]): __wrapped__: Callable[..., _T] def __call__(self, *args: Hashable, **kwargs: Hashable) -> _T: ... @@ -122,7 +124,7 @@ def _make_key( kwds: SupportsItems[Any, Any], typed: bool, kwd_mark: Tuple[object, ...] = ..., - fasttypes: Set[type] = ..., + fasttypes: set[type] = ..., tuple: type = ..., type: Any = ..., len: Callable[[Sized], int] = ..., diff --git a/mypy/typeshed/stdlib/http/client.pyi b/mypy/typeshed/stdlib/http/client.pyi index f27cb0b602ed..c450db587135 100644 --- a/mypy/typeshed/stdlib/http/client.pyi +++ b/mypy/typeshed/stdlib/http/client.pyi @@ -83,6 +83,7 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): headers: HTTPMessage version: int debuglevel: int + fp: io.BufferedReader closed: bool status: int reason: str diff --git a/mypy/typeshed/stdlib/importlib/__init__.pyi b/mypy/typeshed/stdlib/importlib/__init__.pyi index b7986de57a45..1b91cc55f2df 100644 --- a/mypy/typeshed/stdlib/importlib/__init__.pyi +++ b/mypy/typeshed/stdlib/importlib/__init__.pyi @@ -1,15 +1,18 @@ -import types from importlib.abc import Loader -from typing import Any, Mapping, Sequence +from types import ModuleType +from typing import Mapping, Sequence +# Signature of `builtins.__import__` should be kept identical to `importlib.__import__` def __import__( name: str, - globals: Mapping[str, Any] | None = ..., - locals: Mapping[str, Any] | None = ..., + globals: Mapping[str, object] | None = ..., + locals: Mapping[str, object] | None = ..., fromlist: Sequence[str] = ..., level: int = ..., -) -> types.ModuleType: ... -def import_module(name: str, package: str | None = ...) -> types.ModuleType: ... +) -> ModuleType: ... + +# `importlib.import_module` return type should be kept the same as `builtins.__import__` +def import_module(name: str, package: str | None = ...) -> ModuleType: ... def find_loader(name: str, path: str | None = ...) -> Loader | None: ... def invalidate_caches() -> None: ... -def reload(module: types.ModuleType) -> types.ModuleType: ... +def reload(module: ModuleType) -> ModuleType: ... diff --git a/mypy/typeshed/stdlib/importlib/resources.pyi b/mypy/typeshed/stdlib/importlib/resources.pyi index 075761abf9da..194c0bac2b6a 100644 --- a/mypy/typeshed/stdlib/importlib/resources.pyi +++ b/mypy/typeshed/stdlib/importlib/resources.pyi @@ -4,9 +4,10 @@ from typing import Any # This is a >=3.7 module, so we conditionally include its source. if sys.version_info >= (3, 7): import os + from contextlib import AbstractContextManager from pathlib import Path from types import ModuleType - from typing import BinaryIO, ContextManager, Iterator, TextIO, Union + from typing import BinaryIO, Iterator, TextIO, Union Package = Union[str, ModuleType] Resource = Union[str, os.PathLike[Any]] @@ -14,12 +15,11 @@ if sys.version_info >= (3, 7): def open_text(package: Package, resource: Resource, encoding: str = ..., errors: str = ...) -> TextIO: ... def read_binary(package: Package, resource: Resource) -> bytes: ... def read_text(package: Package, resource: Resource, encoding: str = ..., errors: str = ...) -> str: ... - def path(package: Package, resource: Resource) -> ContextManager[Path]: ... + def path(package: Package, resource: Resource) -> AbstractContextManager[Path]: ... def is_resource(package: Package, name: str) -> bool: ... def contents(package: Package) -> Iterator[str]: ... if sys.version_info >= (3, 9): - from contextlib import AbstractContextManager from importlib.abc import Traversable def files(package: Package) -> Traversable: ... def as_file(path: Traversable) -> AbstractContextManager[Path]: ... diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index ddb7293ae701..e3711cc85fbe 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -3,20 +3,27 @@ import sys import types from _typeshed import Self from collections import OrderedDict -from collections.abc import Awaitable, Callable, Generator, Mapping, Sequence, Set +from collections.abc import Awaitable, Callable, Generator, Mapping, Sequence from types import ( AsyncGeneratorType, BuiltinFunctionType, + BuiltinMethodType, CodeType, CoroutineType, FrameType, FunctionType, GeneratorType, + GetSetDescriptorType, + LambdaType, MethodType, ModuleType, TracebackType, ) -from typing import Any, ClassVar, NamedTuple, Tuple, Type, Union + +if sys.version_info >= (3, 7): + from types import ClassMethodDescriptorType, WrapperDescriptorType, MemberDescriptorType, MethodDescriptorType + +from typing import Any, ClassVar, NamedTuple, Protocol, Tuple, Type, TypeVar, Union from typing_extensions import Literal, TypeGuard # @@ -71,17 +78,47 @@ if sys.version_info >= (3, 8): else: def isasyncgenfunction(object: object) -> bool: ... +_T_cont = TypeVar("_T_cont", contravariant=True) +_V_cont = TypeVar("_V_cont", contravariant=True) + +class _SupportsSet(Protocol[_T_cont, _V_cont]): + def __set__(self, __instance: _T_cont, __value: _V_cont) -> None: ... + +class _SupportsDelete(Protocol[_T_cont]): + def __delete__(self, __instance: _T_cont) -> None: ... + def isasyncgen(object: object) -> TypeGuard[AsyncGeneratorType[Any, Any]]: ... def istraceback(object: object) -> TypeGuard[TracebackType]: ... def isframe(object: object) -> TypeGuard[FrameType]: ... def iscode(object: object) -> TypeGuard[CodeType]: ... def isbuiltin(object: object) -> TypeGuard[BuiltinFunctionType]: ... -def isroutine(object: object) -> bool: ... + +if sys.version_info < (3, 7): + def isroutine( + object: object, + ) -> TypeGuard[FunctionType | LambdaType | MethodType | BuiltinFunctionType | BuiltinMethodType]: ... + def ismethoddescriptor(object: object) -> bool: ... + def ismemberdescriptor(object: object) -> bool: ... + +else: + def isroutine( + object: object, + ) -> TypeGuard[ + FunctionType + | LambdaType + | MethodType + | BuiltinFunctionType + | BuiltinMethodType + | WrapperDescriptorType + | MethodDescriptorType + | ClassMethodDescriptorType + ]: ... + def ismethoddescriptor(object: object) -> TypeGuard[MethodDescriptorType]: ... + def ismemberdescriptor(object: object) -> TypeGuard[MemberDescriptorType]: ... + def isabstract(object: object) -> bool: ... -def ismethoddescriptor(object: object) -> bool: ... -def isdatadescriptor(object: object) -> bool: ... -def isgetsetdescriptor(object: object) -> bool: ... -def ismemberdescriptor(object: object) -> bool: ... +def isgetsetdescriptor(object: object) -> TypeGuard[GetSetDescriptorType]: ... +def isdatadescriptor(object: object) -> TypeGuard[_SupportsSet[Any, Any] | _SupportsDelete[Any]]: ... # # Retrieving source code @@ -276,7 +313,7 @@ class ClosureVars(NamedTuple): nonlocals: Mapping[str, Any] globals: Mapping[str, Any] builtins: Mapping[str, Any] - unbound: Set[str] + unbound: set[str] def getclosurevars(func: Callable[..., Any]) -> ClosureVars: ... def unwrap(func: Callable[..., Any], *, stop: Callable[[Any], Any] | None = ...) -> Any: ... diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi index feed7269e6bc..e776ed1e5a61 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi @@ -1,6 +1,6 @@ from lib2to3.pgen2.grammar import _DFAS, Grammar from lib2to3.pytree import _NL, _Convert, _RawNode -from typing import Any, Sequence, Set +from typing import Any, Sequence _Context = Sequence[Any] @@ -16,7 +16,7 @@ class Parser: convert: _Convert stack: list[tuple[_DFAS, int, _RawNode]] rootnode: _NL | None - used_names: Set[str] + used_names: set[str] def __init__(self, grammar: Grammar, convert: _Convert | None = ...) -> None: ... def setup(self, start: int | None = ...) -> None: ... def addtoken(self, type: int, value: str | None, context: _Context) -> bool: ... diff --git a/mypy/typeshed/stdlib/lzma.pyi b/mypy/typeshed/stdlib/lzma.pyi index 7a26d15292d4..e1da3024c4ac 100644 --- a/mypy/typeshed/stdlib/lzma.pyi +++ b/mypy/typeshed/stdlib/lzma.pyi @@ -1,7 +1,7 @@ import io from _typeshed import ReadableBuffer, Self, StrOrBytesPath from typing import IO, Any, Mapping, Sequence, TextIO, Union, overload -from typing_extensions import Literal +from typing_extensions import Literal, final _OpenBinaryWritingMode = Literal["w", "wb", "x", "xb", "a", "ab"] _OpenTextWritingMode = Literal["wt", "xt", "at"] @@ -40,6 +40,7 @@ PRESET_DEFAULT: int PRESET_EXTREME: int # from _lzma.c +@final class LZMADecompressor(object): def __init__(self, format: int | None = ..., memlimit: int | None = ..., filters: _FilterChain | None = ...) -> None: ... def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... @@ -53,6 +54,7 @@ class LZMADecompressor(object): def needs_input(self) -> bool: ... # from _lzma.c +@final class LZMACompressor(object): def __init__( self, format: int | None = ..., check: int = ..., preset: int | None = ..., filters: _FilterChain | None = ... diff --git a/mypy/typeshed/stdlib/math.pyi b/mypy/typeshed/stdlib/math.pyi index 19042962b28f..f92a3d94f978 100644 --- a/mypy/typeshed/stdlib/math.pyi +++ b/mypy/typeshed/stdlib/math.pyi @@ -3,7 +3,10 @@ from _typeshed import SupportsTrunc from typing import Iterable, SupportsFloat, Union, overload from typing_extensions import SupportsIndex -_SupportsFloatOrIndex = Union[SupportsFloat, SupportsIndex] +if sys.version_info >= (3, 8): + _SupportsFloatOrIndex = Union[SupportsFloat, SupportsIndex] +else: + _SupportsFloatOrIndex = SupportsFloat e: float pi: float @@ -36,7 +39,13 @@ def erfc(__x: _SupportsFloatOrIndex) -> float: ... def exp(__x: _SupportsFloatOrIndex) -> float: ... def expm1(__x: _SupportsFloatOrIndex) -> float: ... def fabs(__x: _SupportsFloatOrIndex) -> float: ... -def factorial(__x: SupportsIndex) -> int: ... + +if sys.version_info >= (3, 8): + def factorial(__x: SupportsIndex) -> int: ... + +else: + def factorial(__x: int) -> int: ... + def floor(__x: _SupportsFloatOrIndex) -> int: ... def fmod(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... def frexp(__x: _SupportsFloatOrIndex) -> tuple[float, int]: ... diff --git a/mypy/typeshed/stdlib/msilib/__init__.pyi b/mypy/typeshed/stdlib/msilib/__init__.pyi index d72c8efc8452..4e1a7e6a7c02 100644 --- a/mypy/typeshed/stdlib/msilib/__init__.pyi +++ b/mypy/typeshed/stdlib/msilib/__init__.pyi @@ -1,6 +1,6 @@ import sys from types import ModuleType -from typing import Any, Container, Iterable, Sequence, Set, Tuple, Type +from typing import Any, Container, Iterable, Sequence, Tuple, Type from typing_extensions import Literal if sys.platform == "win32": @@ -49,13 +49,13 @@ if sys.platform == "win32": name: str files: list[tuple[str, str]] - filenames: Set[str] + filenames: set[str] index: int def __init__(self, name: str) -> None: ... def gen_id(self, file: str) -> str: ... def append(self, full: str, file: str, logical: str) -> tuple[int, str]: ... def commit(self, db: _Database) -> None: ... - _directories: Set[str] + _directories: set[str] class Directory: db: _Database @@ -64,8 +64,8 @@ if sys.platform == "win32": physical: str logical: str component: str | None - short_names: Set[str] - ids: Set[str] + short_names: set[str] + ids: set[str] keyfiles: dict[str, str] componentflags: int | None absolute: str diff --git a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi index 53b0c983fbcf..000fed79f3e4 100644 --- a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi @@ -53,7 +53,7 @@ _SemaphoreType = synchronize.Semaphore # multiprocessing.context.BaseContext's methods, so the two signatures should # be identical (modulo self). -# Sychronization primitives +# Synchronization primitives _LockLike = Union[synchronize.Lock, synchronize.RLock] RawValue = context._default_context.RawValue RawArray = context._default_context.RawArray diff --git a/mypy/typeshed/stdlib/operator.pyi b/mypy/typeshed/stdlib/operator.pyi index 5cbfda7a84d1..bb8e23733f87 100644 --- a/mypy/typeshed/stdlib/operator.pyi +++ b/mypy/typeshed/stdlib/operator.pyi @@ -11,6 +11,7 @@ from typing import ( TypeVar, overload, ) +from typing_extensions import final _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) @@ -115,7 +116,7 @@ def __setitem__(a: MutableSequence[_T], b: slice, c: Sequence[_T]) -> None: ... @overload def __setitem__(a: MutableMapping[_K, _V], b: _K, c: _V) -> None: ... def length_hint(__obj: Any, __default: int = ...) -> int: ... - +@final class attrgetter(Generic[_T_co]): @overload def __new__(cls, attr: str) -> attrgetter[Any]: ... @@ -129,6 +130,7 @@ class attrgetter(Generic[_T_co]): def __new__(cls, attr: str, *attrs: str) -> attrgetter[Tuple[Any, ...]]: ... def __call__(self, obj: Any) -> _T_co: ... +@final class itemgetter(Generic[_T_co]): @overload def __new__(cls, item: Any) -> itemgetter[Any]: ... @@ -142,6 +144,7 @@ class itemgetter(Generic[_T_co]): def __new__(cls, item: Any, *items: Any) -> itemgetter[Tuple[Any, ...]]: ... def __call__(self, obj: Any) -> _T_co: ... +@final class methodcaller: def __init__(self, __name: str, *args: Any, **kwargs: Any) -> None: ... def __call__(self, obj: Any) -> Any: ... diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index b2bfa0d64d14..b432f6931a3f 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -30,14 +30,13 @@ from typing import ( NoReturn, Protocol, Sequence, - Set, Tuple, TypeVar, Union, overload, runtime_checkable, ) -from typing_extensions import Literal +from typing_extensions import Literal, final from . import path as _path @@ -56,10 +55,10 @@ error = OSError supports_bytes_environ: bool -supports_dir_fd: Set[Callable[..., Any]] -supports_fd: Set[Callable[..., Any]] -supports_effective_ids: Set[Callable[..., Any]] -supports_follow_symlinks: Set[Callable[..., Any]] +supports_dir_fd: set[Callable[..., Any]] +supports_fd: set[Callable[..., Any]] +supports_effective_ids: set[Callable[..., Any]] +supports_follow_symlinks: set[Callable[..., Any]] if sys.platform != "win32": # Unix only @@ -262,6 +261,7 @@ if sys.platform != "win32": TMP_MAX: int # Undocumented, but used by tempfile # ----- os classes (structures) ----- +@final class stat_result: # For backward compatibility, the return value of stat() is also # accessible as a tuple of at least 10 integers giving the most important @@ -314,8 +314,9 @@ class PathLike(Protocol[_AnyStr_co]): _FdOrAnyPath = Union[int, StrOrBytesPath] +@final class DirEntry(Generic[AnyStr]): - # This is what the scandir interator yields + # This is what the scandir iterator yields # The constructor is hidden name: AnyStr @@ -334,6 +335,7 @@ if sys.platform != "win32": _Tuple11Int = Tuple[int, int, int, int, int, int, int, int, int, int, int] if sys.version_info >= (3, 7): # f_fsid was added in https://github.com/python/cpython/pull/4571 + @final class statvfs_result(_Tuple10Int): # Unix only def __new__(cls, seq: _Tuple10Int | _Tuple11Int, dict: dict[str, int] = ...) -> statvfs_result: ... n_fields: int @@ -566,6 +568,7 @@ if sys.platform != "win32": def readv(__fd: int, __buffers: Sequence[bytearray]) -> int: ... def writev(__fd: int, __buffers: Sequence[bytes]) -> int: ... +@final class terminal_size(Tuple[int, int]): columns: int lines: int @@ -826,7 +829,7 @@ if sys.platform != "win32": def sched_setparam(pid: int, param: sched_param) -> None: ... # some flavors of Unix def sched_getparam(pid: int) -> sched_param: ... # some flavors of Unix def sched_setaffinity(pid: int, mask: Iterable[int]) -> None: ... # some flavors of Unix - def sched_getaffinity(pid: int) -> Set[int]: ... # some flavors of Unix + def sched_getaffinity(pid: int) -> set[int]: ... # some flavors of Unix def cpu_count() -> int | None: ... diff --git a/mypy/typeshed/stdlib/pathlib.pyi b/mypy/typeshed/stdlib/pathlib.pyi index e8577ebc18d4..7d5f7ff2dba8 100644 --- a/mypy/typeshed/stdlib/pathlib.pyi +++ b/mypy/typeshed/stdlib/pathlib.pyi @@ -68,8 +68,12 @@ class Path(PurePath): ) -> bool | None: ... @classmethod def cwd(cls: Type[_P]) -> _P: ... - def stat(self) -> stat_result: ... - def chmod(self, mode: int) -> None: ... + if sys.version_info >= (3, 10): + def stat(self, *, follow_symlinks: bool = ...) -> stat_result: ... + def chmod(self, mode: int, *, follow_symlinks: bool = ...) -> None: ... + else: + def stat(self) -> stat_result: ... + def chmod(self, mode: int) -> None: ... def exists(self) -> bool: ... def glob(self: _P, pattern: str) -> Generator[_P, None, None]: ... def group(self) -> str: ... @@ -154,6 +158,8 @@ class Path(PurePath): def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ... def rmdir(self) -> None: ... def symlink_to(self, target: str | Path, target_is_directory: bool = ...) -> None: ... + if sys.version_info >= (3, 10): + def hardlink_to(self, target: str | Path) -> None: ... def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ... if sys.version_info >= (3, 8): def unlink(self, missing_ok: bool = ...) -> None: ... @@ -167,7 +173,12 @@ class Path(PurePath): def read_text(self, encoding: str | None = ..., errors: str | None = ...) -> str: ... def samefile(self, other_path: str | bytes | int | Path) -> bool: ... def write_bytes(self, data: bytes) -> int: ... - def write_text(self, data: str, encoding: str | None = ..., errors: str | None = ...) -> int: ... + if sys.version_info >= (3, 10): + def write_text( + self, data: str, encoding: str | None = ..., errors: str | None = ..., newline: str | None = ... + ) -> int: ... + else: + def write_text(self, data: str, encoding: str | None = ..., errors: str | None = ...) -> int: ... if sys.version_info >= (3, 8): def link_to(self, target: StrPath | bytes) -> None: ... diff --git a/mypy/typeshed/stdlib/pickle.pyi b/mypy/typeshed/stdlib/pickle.pyi index da6c5d11794a..cef1ffe9eb9b 100644 --- a/mypy/typeshed/stdlib/pickle.pyi +++ b/mypy/typeshed/stdlib/pickle.pyi @@ -1,5 +1,6 @@ import sys from typing import Any, Callable, ClassVar, Iterable, Iterator, Mapping, Optional, Protocol, Tuple, Type, Union +from typing_extensions import final HIGHEST_PROTOCOL: int DEFAULT_PROTOCOL: int @@ -15,6 +16,7 @@ class _WritableFileobj(Protocol): if sys.version_info >= (3, 8): # TODO: holistic design for buffer interface (typing.Buffer?) + @final class PickleBuffer: # buffer must be a buffer-providing object def __init__(self, buffer: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/posix.pyi b/mypy/typeshed/stdlib/posix.pyi index 4993371b5333..14cea87cde29 100644 --- a/mypy/typeshed/stdlib/posix.pyi +++ b/mypy/typeshed/stdlib/posix.pyi @@ -2,7 +2,9 @@ import sys from _typeshed import StrOrBytesPath from os import PathLike, _ExecEnv, _ExecVArgs, stat_result as stat_result from typing import Any, Iterable, NamedTuple, Sequence, Tuple, overload +from typing_extensions import final +@final class uname_result(NamedTuple): sysname: str nodename: str @@ -10,6 +12,7 @@ class uname_result(NamedTuple): version: str machine: str +@final class times_result(NamedTuple): user: float system: float diff --git a/mypy/typeshed/stdlib/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/pyexpat/__init__.pyi index d1993496aee7..6a3d6cd56791 100644 --- a/mypy/typeshed/stdlib/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/pyexpat/__init__.pyi @@ -2,6 +2,7 @@ import pyexpat.errors as errors import pyexpat.model as model from _typeshed import SupportsRead from typing import Any, Callable, Optional, Tuple +from typing_extensions import final EXPAT_VERSION: str # undocumented version_info: tuple[int, int, int] # undocumented @@ -21,6 +22,7 @@ XML_PARAM_ENTITY_PARSING_ALWAYS: int _Model = Tuple[int, int, Optional[str], Tuple[Any, ...]] +@final class XMLParserType(object): def Parse(self, __data: str | bytes, __isfinal: bool = ...) -> int: ... def ParseFile(self, __file: SupportsRead[bytes]) -> int: ... diff --git a/mypy/typeshed/stdlib/random.pyi b/mypy/typeshed/stdlib/random.pyi index f284fe831b42..699c56351051 100644 --- a/mypy/typeshed/stdlib/random.pyi +++ b/mypy/typeshed/stdlib/random.pyi @@ -1,6 +1,6 @@ import _random import sys -from collections.abc import Callable, Iterable, MutableSequence, Sequence, Set +from collections.abc import Callable, Iterable, MutableSequence, Sequence from fractions import Fraction from typing import Any, NoReturn, Tuple, TypeVar @@ -27,9 +27,9 @@ class Random(_random.Random): ) -> list[_T]: ... def shuffle(self, x: MutableSequence[Any], random: Callable[[], float] | None = ...) -> None: ... if sys.version_info >= (3, 9): - def sample(self, population: Sequence[_T] | Set[_T], k: int, *, counts: Iterable[_T] | None = ...) -> list[_T]: ... + def sample(self, population: Sequence[_T] | set[_T], k: int, *, counts: Iterable[_T] | None = ...) -> list[_T]: ... else: - def sample(self, population: Sequence[_T] | Set[_T], k: int) -> list[_T]: ... + def sample(self, population: Sequence[_T] | set[_T], k: int) -> list[_T]: ... def random(self) -> float: ... def uniform(self, a: float, b: float) -> float: ... def triangular(self, low: float = ..., high: float = ..., mode: float | None = ...) -> float: ... @@ -66,10 +66,10 @@ def choices( def shuffle(x: MutableSequence[Any], random: Callable[[], float] | None = ...) -> None: ... if sys.version_info >= (3, 9): - def sample(population: Sequence[_T] | Set[_T], k: int, *, counts: Iterable[_T] | None = ...) -> list[_T]: ... + def sample(population: Sequence[_T] | set[_T], k: int, *, counts: Iterable[_T] | None = ...) -> list[_T]: ... else: - def sample(population: Sequence[_T] | Set[_T], k: int) -> list[_T]: ... + def sample(population: Sequence[_T] | set[_T], k: int) -> list[_T]: ... def random() -> float: ... def uniform(a: float, b: float) -> float: ... diff --git a/mypy/typeshed/stdlib/reprlib.pyi b/mypy/typeshed/stdlib/reprlib.pyi index 1529220c9bfc..4d400554a4ff 100644 --- a/mypy/typeshed/stdlib/reprlib.pyi +++ b/mypy/typeshed/stdlib/reprlib.pyi @@ -1,5 +1,6 @@ from array import array -from typing import Any, Callable, Deque, FrozenSet, Set, Tuple +from collections import deque +from typing import Any, Callable, Tuple _ReprFunc = Callable[[Any], str] @@ -23,9 +24,9 @@ class Repr: def repr_tuple(self, x: Tuple[Any, ...], level: int) -> str: ... def repr_list(self, x: list[Any], level: int) -> str: ... def repr_array(self, x: array[Any], level: int) -> str: ... - def repr_set(self, x: Set[Any], level: int) -> str: ... - def repr_frozenset(self, x: FrozenSet[Any], level: int) -> str: ... - def repr_deque(self, x: Deque[Any], level: int) -> str: ... + def repr_set(self, x: set[Any], level: int) -> str: ... + def repr_frozenset(self, x: frozenset[Any], level: int) -> str: ... + def repr_deque(self, x: deque[Any], level: int) -> str: ... def repr_dict(self, x: dict[Any, Any], level: int) -> str: ... def repr_str(self, x: str, level: int) -> str: ... def repr_int(self, x: int, level: int) -> str: ... diff --git a/mypy/typeshed/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi index 12341d72e8c3..f4c492caccaf 100644 --- a/mypy/typeshed/stdlib/shutil.pyi +++ b/mypy/typeshed/stdlib/shutil.pyi @@ -1,7 +1,7 @@ import os import sys from _typeshed import StrOrBytesPath, StrPath, SupportsRead, SupportsWrite -from typing import Any, AnyStr, Callable, Iterable, NamedTuple, Sequence, Set, TypeVar, Union, overload +from typing import Any, AnyStr, Callable, Iterable, NamedTuple, Sequence, TypeVar, Union, overload _PathT = TypeVar("_PathT", str, os.PathLike[str]) # Return value of some functions that may either return a path-like object that was passed in or @@ -21,7 +21,7 @@ def copymode(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> None def copystat(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> None: ... def copy(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... def copy2(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... -def ignore_patterns(*patterns: StrPath) -> Callable[[Any, list[str]], Set[str]]: ... +def ignore_patterns(*patterns: StrPath) -> Callable[[Any, list[str]], set[str]]: ... if sys.version_info >= (3, 8): def copytree( diff --git a/mypy/typeshed/stdlib/signal.pyi b/mypy/typeshed/stdlib/signal.pyi index d36dbc2d6aa7..d617e24f227f 100644 --- a/mypy/typeshed/stdlib/signal.pyi +++ b/mypy/typeshed/stdlib/signal.pyi @@ -1,7 +1,7 @@ import sys from enum import IntEnum from types import FrameType -from typing import Any, Callable, Iterable, Optional, Set, Tuple, Union +from typing import Any, Callable, Iterable, Optional, Tuple, Union if sys.platform != "win32": class ItimerError(IOError): ... @@ -167,13 +167,13 @@ def getsignal(__signalnum: _SIGNUM) -> _HANDLER: ... if sys.version_info >= (3, 8): def strsignal(__signalnum: _SIGNUM) -> str | None: ... - def valid_signals() -> Set[Signals]: ... + def valid_signals() -> set[Signals]: ... def raise_signal(__signalnum: _SIGNUM) -> None: ... if sys.platform != "win32": def pause() -> None: ... def pthread_kill(__thread_id: int, __signalnum: int) -> None: ... - def pthread_sigmask(__how: int, __mask: Iterable[int]) -> Set[_SIGNUM]: ... + def pthread_sigmask(__how: int, __mask: Iterable[int]) -> set[_SIGNUM]: ... if sys.version_info >= (3, 7): def set_wakeup_fd(fd: int, *, warn_on_full_buffer: bool = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/smtpd.pyi b/mypy/typeshed/stdlib/smtpd.pyi index 5d9307300c7e..2b6020524827 100644 --- a/mypy/typeshed/stdlib/smtpd.pyi +++ b/mypy/typeshed/stdlib/smtpd.pyi @@ -1,7 +1,8 @@ import asynchat import asyncore import socket -from typing import Any, DefaultDict, Tuple, Type +from collections import defaultdict +from typing import Any, Tuple, Type _Address = Tuple[str, int] # (host, port) @@ -9,7 +10,7 @@ class SMTPChannel(asynchat.async_chat): COMMAND: int DATA: int - command_size_limits: DefaultDict[str, int] + command_size_limits: defaultdict[str, int] smtp_server: SMTPServer conn: socket.socket addr: Any diff --git a/mypy/typeshed/stdlib/socketserver.pyi b/mypy/typeshed/stdlib/socketserver.pyi index 5966b8d10e32..6f5eeefb84fd 100644 --- a/mypy/typeshed/stdlib/socketserver.pyi +++ b/mypy/typeshed/stdlib/socketserver.pyi @@ -2,7 +2,7 @@ import sys import types from _typeshed import Self from socket import socket as _socket -from typing import Any, BinaryIO, Callable, ClassVar, Set, Tuple, Type, TypeVar, Union +from typing import Any, BinaryIO, Callable, ClassVar, Tuple, Type, TypeVar, Union _T = TypeVar("_T") _RequestType = Union[_socket, Tuple[bytes, _socket]] @@ -88,7 +88,7 @@ if sys.platform != "win32": if sys.platform != "win32": class ForkingMixIn: timeout: float | None # undocumented - active_children: Set[int] | None # undocumented + active_children: set[int] | None # undocumented max_children: int # undocumented if sys.version_info >= (3, 7): block_on_close: bool diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index fa817b089254..e2e45d538da9 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -35,6 +35,8 @@ SQLITE_CREATE_TEMP_TRIGGER: int SQLITE_CREATE_TEMP_VIEW: int SQLITE_CREATE_TRIGGER: int SQLITE_CREATE_VIEW: int +if sys.version_info >= (3, 7): + SQLITE_CREATE_VTABLE: int SQLITE_DELETE: int SQLITE_DENY: int SQLITE_DETACH: int @@ -46,12 +48,31 @@ SQLITE_DROP_TEMP_TRIGGER: int SQLITE_DROP_TEMP_VIEW: int SQLITE_DROP_TRIGGER: int SQLITE_DROP_VIEW: int +if sys.version_info >= (3, 7): + SQLITE_DROP_VTABLE: int + SQLITE_FUNCTION: int SQLITE_IGNORE: int SQLITE_INSERT: int SQLITE_OK: int +if sys.version_info >= (3, 11): + SQLITE_LIMIT_LENGTH: int + SQLITE_LIMIT_SQL_LENGTH: int + SQLITE_LIMIT_COLUMN: int + SQLITE_LIMIT_EXPR_DEPTH: int + SQLITE_LIMIT_COMPOUND_SELECT: int + SQLITE_LIMIT_VDBE_OP: int + SQLITE_LIMIT_FUNCTION_ARG: int + SQLITE_LIMIT_ATTACHED: int + SQLITE_LIMIT_LIKE_PATTERN_LENGTH: int + SQLITE_LIMIT_VARIABLE_NUMBER: int + SQLITE_LIMIT_TRIGGER_DEPTH: int + SQLITE_LIMIT_WORKER_THREADS: int SQLITE_PRAGMA: int SQLITE_READ: int SQLITE_REINDEX: int +if sys.version_info >= (3, 7): + SQLITE_RECURSIVE: int + SQLITE_SAVEPOINT: int SQLITE_SELECT: int SQLITE_TRANSACTION: int SQLITE_UPDATE: int diff --git a/mypy/typeshed/stdlib/sre_parse.pyi b/mypy/typeshed/stdlib/sre_parse.pyi index f493bee945de..2d00bedc2c81 100644 --- a/mypy/typeshed/stdlib/sre_parse.pyi +++ b/mypy/typeshed/stdlib/sre_parse.pyi @@ -1,14 +1,14 @@ import sys from sre_constants import _NamedIntConstant as _NIC, error as _Error -from typing import Any, FrozenSet, Iterable, List, Match, Optional, Pattern as _Pattern, Tuple, Union, overload +from typing import Any, Iterable, List, Match, Optional, Pattern as _Pattern, Tuple, Union, overload SPECIAL_CHARS: str REPEAT_CHARS: str -DIGITS: FrozenSet[str] -OCTDIGITS: FrozenSet[str] -HEXDIGITS: FrozenSet[str] -ASCIILETTERS: FrozenSet[str] -WHITESPACE: FrozenSet[str] +DIGITS: frozenset[str] +OCTDIGITS: frozenset[str] +HEXDIGITS: frozenset[str] +ASCIILETTERS: frozenset[str] +WHITESPACE: frozenset[str] ESCAPES: dict[str, tuple[_NIC, int]] CATEGORIES: dict[str, tuple[_NIC, _NIC] | tuple[_NIC, list[tuple[_NIC, _NIC]]]] FLAGS: dict[str, int] diff --git a/mypy/typeshed/stdlib/sys.pyi b/mypy/typeshed/stdlib/sys.pyi index 43d33ec62135..274e4b90fd6e 100644 --- a/mypy/typeshed/stdlib/sys.pyi +++ b/mypy/typeshed/stdlib/sys.pyi @@ -1,6 +1,6 @@ import sys from builtins import object as _object -from importlib.abc import Loader, PathEntryFinder +from importlib.abc import PathEntryFinder from importlib.machinery import ModuleSpec from io import TextIOWrapper from types import FrameType, ModuleType, TracebackType @@ -8,7 +8,6 @@ from typing import ( Any, AsyncGenerator, Callable, - FrozenSet, NoReturn, Optional, Protocol, @@ -27,12 +26,10 @@ _T = TypeVar("_T") # The following type alias are stub-only and do not exist during runtime _ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] _OptExcInfo = Union[_ExcInfo, Tuple[None, None, None]] -_PathSequence = Sequence[Union[bytes, str]] -# Unlike importlib.abc.MetaPathFinder, invalidate_caches() might not exist (see python docs) +# Intentionally omits one deprecated and one optional method of `importlib.abc.MetaPathFinder` class _MetaPathFinder(Protocol): - def find_module(self, fullname: str, path: _PathSequence | None) -> Loader | None: ... - def find_spec(self, fullname: str, path: _PathSequence | None, target: ModuleType | None = ...) -> ModuleSpec | None: ... + def find_spec(self, fullname: str, path: Sequence[str] | None, target: ModuleType | None = ...) -> ModuleSpec | None: ... # ----- sys variables ----- if sys.platform != "win32": @@ -76,7 +73,7 @@ stdin: TextIO stdout: TextIO stderr: TextIO if sys.version_info >= (3, 10): - stdlib_module_names: FrozenSet[str] + stdlib_module_names: frozenset[str] __stdin__: TextIOWrapper __stdout__: TextIOWrapper __stderr__: TextIOWrapper diff --git a/mypy/typeshed/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi index 53c986a3f017..0134316d8107 100644 --- a/mypy/typeshed/stdlib/tarfile.pyi +++ b/mypy/typeshed/stdlib/tarfile.pyi @@ -5,7 +5,7 @@ from _typeshed import Self, StrOrBytesPath, StrPath from collections.abc import Callable, Iterable, Iterator, Mapping from gzip import _ReadableFileobj as _GzipReadableFileobj, _WritableFileobj as _GzipWritableFileobj from types import TracebackType -from typing import IO, Protocol, Set, Tuple, Type, TypeVar, overload +from typing import IO, Protocol, Tuple, Type, TypeVar, overload from typing_extensions import Literal _TF = TypeVar("_TF", bound=TarFile) @@ -67,7 +67,7 @@ REGULAR_TYPES: Tuple[bytes, ...] GNU_TYPES: Tuple[bytes, ...] PAX_FIELDS: Tuple[str, ...] PAX_NUMBER_FIELDS: dict[str, type] -PAX_NAME_FIELDS: Set[str] +PAX_NAME_FIELDS: set[str] ENCODING: str diff --git a/mypy/typeshed/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi index 9f69f3da4778..119c111bc4e1 100644 --- a/mypy/typeshed/stdlib/tempfile.pyi +++ b/mypy/typeshed/stdlib/tempfile.pyi @@ -321,10 +321,28 @@ class SpooledTemporaryFile(IO[AnyStr]): class TemporaryDirectory(Generic[AnyStr]): name: AnyStr - @overload - def __init__(self: TemporaryDirectory[str], suffix: None = ..., prefix: None = ..., dir: None = ...) -> None: ... - @overload - def __init__(self, suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., dir: _DirT[AnyStr] | None = ...) -> None: ... + if sys.version_info >= (3, 10): + @overload + def __init__( + self: TemporaryDirectory[str], + suffix: None = ..., + prefix: None = ..., + dir: None = ..., + ignore_cleanup_errors: bool = ..., + ) -> None: ... + @overload + def __init__( + self, + suffix: AnyStr | None = ..., + prefix: AnyStr | None = ..., + dir: _DirT[AnyStr] | None = ..., + ignore_cleanup_errors: bool = ..., + ) -> None: ... + else: + @overload + def __init__(self: TemporaryDirectory[str], suffix: None = ..., prefix: None = ..., dir: None = ...) -> None: ... + @overload + def __init__(self, suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., dir: _DirT[AnyStr] | None = ...) -> None: ... def cleanup(self) -> None: ... def __enter__(self) -> AnyStr: ... def __exit__( diff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi index 29bfebed62d3..bf370d68e83d 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -1,6 +1,7 @@ import sys from types import SimpleNamespace from typing import Any, NamedTuple, Tuple +from typing_extensions import final _TimeTuple = Tuple[int, int, int, int, int, int, int, int, int] @@ -48,6 +49,7 @@ class _struct_time(NamedTuple): @property def n_unnamed_fields(self) -> int: ... +@final class struct_time(_struct_time): def __init__( self, diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index f994b843c5d4..bda37b406fc3 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -338,30 +338,40 @@ class Misc: # binds do. The default value of func is not str. @overload def bind( - self, sequence: str | None = ..., func: Callable[[Event[Misc]], Any] | None = ..., add: bool | None = ... + self, + sequence: str | None = ..., + func: Callable[[Event[Misc]], Any] | None = ..., + add: Literal["", "+"] | bool | None = ..., ) -> str: ... @overload - def bind(self, sequence: str | None, func: str, add: bool | None = ...) -> None: ... + def bind(self, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... @overload - def bind(self, *, func: str, add: bool | None = ...) -> None: ... + def bind(self, *, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... # There's no way to know what type of widget bind_all and bind_class # callbacks will get, so those are Misc. @overload def bind_all( - self, sequence: str | None = ..., func: Callable[[Event[Misc]], Any] | None = ..., add: bool | None = ... + self, + sequence: str | None = ..., + func: Callable[[Event[Misc]], Any] | None = ..., + add: Literal["", "+"] | bool | None = ..., ) -> str: ... @overload - def bind_all(self, sequence: str | None, func: str, add: bool | None = ...) -> None: ... + def bind_all(self, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... @overload - def bind_all(self, *, func: str, add: bool | None = ...) -> None: ... + def bind_all(self, *, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... @overload def bind_class( - self, className: str, sequence: str | None = ..., func: Callable[[Event[Misc]], Any] | None = ..., add: bool | None = ... + self, + className: str, + sequence: str | None = ..., + func: Callable[[Event[Misc]], Any] | None = ..., + add: Literal["", "+"] | bool | None = ..., ) -> str: ... @overload - def bind_class(self, className: str, sequence: str | None, func: str, add: bool | None = ...) -> None: ... + def bind_class(self, className: str, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... @overload - def bind_class(self, className: str, *, func: str, add: bool | None = ...) -> None: ... + def bind_class(self, className: str, *, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... def unbind(self, sequence: str, funcid: str | None = ...) -> None: ... def unbind_all(self, sequence: str) -> None: ... def unbind_class(self, className: str, sequence: str) -> None: ... @@ -407,7 +417,7 @@ class Misc: pad: _ScreenUnits = ..., uniform: str = ..., weight: int = ..., - ) -> _GridIndexInfo | Any: ... # can be None but annoyying to check + ) -> _GridIndexInfo | Any: ... # can be None but annoying to check columnconfigure = grid_columnconfigure rowconfigure = grid_rowconfigure def grid_location(self, x: _ScreenUnits, y: _ScreenUnits) -> tuple[int, int]: ... @@ -730,7 +740,7 @@ class Pack: forget = pack_forget propagate = Misc.pack_propagate # commented out to avoid mypy getting confused with multiple - # inheritance and how things get overrided with different things + # inheritance and how things get overridden with different things # info = pack_info # pack_propagate = Misc.pack_propagate # configure = pack_configure @@ -774,7 +784,7 @@ class Place: place = place_configure info = place_info # commented out to avoid mypy getting confused with multiple - # inheritance and how things get overrided with different things + # inheritance and how things get overridden with different things # config = place_configure # configure = place_configure # forget = place_forget @@ -816,7 +826,7 @@ class Grid: location = Misc.grid_location size = Misc.grid_size # commented out to avoid mypy getting confused with multiple - # inheritance and how things get overrided with different things + # inheritance and how things get overridden with different things # bbox = Misc.grid_bbox # grid_bbox = Misc.grid_bbox # forget = grid_forget @@ -847,12 +857,15 @@ class Widget(BaseWidget, Pack, Place, Grid): # widgets don't. @overload def bind( - self: _W, sequence: str | None = ..., func: Callable[[Event[_W]], Any] | None = ..., add: bool | None = ... + self: _W, + sequence: str | None = ..., + func: Callable[[Event[_W]], Any] | None = ..., + add: Literal["", "+"] | bool | None = ..., ) -> str: ... @overload - def bind(self, sequence: str | None, func: str, add: bool | None = ...) -> None: ... + def bind(self, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... @overload - def bind(self, *, func: str, add: bool | None = ...) -> None: ... + def bind(self, *, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... class Toplevel(BaseWidget, Wm): # Toplevel and Tk have the same options because they correspond to the same @@ -954,7 +967,7 @@ class Button(Widget): state: Literal["normal", "active", "disabled"] = ..., takefocus: _TakeFocusValue = ..., text: float | str = ..., - # We allow the textvariable to be any Variable, not necessarly + # We allow the textvariable to be any Variable, not necessarily # StringVar. This is useful for e.g. a button that displays the value # of an IntVar. textvariable: Variable = ..., @@ -1129,12 +1142,14 @@ class Canvas(Widget, XView, YView): tagOrId: str | int, sequence: str | None = ..., func: Callable[[Event[Canvas]], Any] | None = ..., - add: bool | None = ..., + add: Literal["", "+"] | bool | None = ..., ) -> str: ... @overload - def tag_bind(self, tagOrId: str | int, sequence: str | None, func: str, add: bool | None = ...) -> None: ... + def tag_bind( + self, tagOrId: str | int, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = ... + ) -> None: ... @overload - def tag_bind(self, tagOrId: str | int, *, func: str, add: bool | None = ...) -> None: ... + def tag_bind(self, tagOrId: str | int, *, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... def tag_unbind(self, tagOrId: str | int, sequence: str, funcid: str | None = ...) -> None: ... def canvasx(self, screenx, gridspacing: Any | None = ...): ... def canvasy(self, screeny, gridspacing: Any | None = ...): ... @@ -2879,10 +2894,14 @@ class Text(Widget, XView, YView): # tag_bind stuff is very similar to Canvas @overload def tag_bind( - self, tagName: str, sequence: str | None, func: Callable[[Event[Text]], Any] | None, add: bool | None = ... + self, + tagName: str, + sequence: str | None, + func: Callable[[Event[Text]], Any] | None, + add: Literal["", "+"] | bool | None = ..., ) -> str: ... @overload - def tag_bind(self, tagName: str, sequence: str | None, func: str, add: bool | None = ...) -> None: ... + def tag_bind(self, tagName: str, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... def tag_unbind(self, tagName: str, sequence: str, funcid: str | None = ...) -> None: ... # allowing any string for cget instead of just Literals because there's no other way to look up tag options def tag_cget(self, tagName: str, option: str) -> Any: ... @@ -2960,7 +2979,7 @@ class OptionMenu(Menubutton): command: Callable[[StringVar], Any] | None = ..., ) -> None: ... # configure, config, cget are inherited from Menubutton - # destroy and __getitem__ are overrided, signature does not change + # destroy and __getitem__ are overridden, signature does not change class _Image(Protocol): tk: _tkinter.TkappType diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index 20f74d4a5ec2..be0713ec2e4b 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -1122,7 +1122,7 @@ class LabeledScale(Frame): compound: Literal["top"] | Literal["bottom"] = ..., **kw: Any, ) -> None: ... - # destroy is overrided, signature does not change + # destroy is overridden, signature does not change value: Any class OptionMenu(Menubutton): @@ -1138,5 +1138,5 @@ class OptionMenu(Menubutton): command: Callable[[tkinter.StringVar], Any] | None = ..., ) -> None: ... # configure, config, cget, destroy are inherited from Menubutton - # destroy and __setitem__ are overrided, signature does not change + # destroy and __setitem__ are overridden, signature does not change def set_menu(self, default: Any | None = ..., *values): ... diff --git a/mypy/typeshed/stdlib/tokenize.pyi b/mypy/typeshed/stdlib/tokenize.pyi index 4a42795b9491..a8294adb653f 100644 --- a/mypy/typeshed/stdlib/tokenize.pyi +++ b/mypy/typeshed/stdlib/tokenize.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import StrOrBytesPath from builtins import open as _builtin_open from token import * # noqa: F403 -from typing import Any, Callable, Generator, Iterable, NamedTuple, Pattern, Sequence, Set, TextIO, Tuple, Union +from typing import Any, Callable, Generator, Iterable, NamedTuple, Pattern, Sequence, TextIO, Tuple, Union if sys.version_info < (3, 7): COMMENT: int @@ -69,7 +69,7 @@ Floatnumber: str # undocumented Imagnumber: str # undocumented Number: str # undocumented -def _all_string_prefixes() -> Set[str]: ... # undocumented +def _all_string_prefixes() -> set[str]: ... # undocumented StringPrefix: str # undocumented @@ -95,7 +95,7 @@ PseudoExtras: str # undocumented PseudoToken: str # undocumented endpats: dict[str, str] # undocumented -single_quoted: Set[str] # undocumented -triple_quoted: Set[str] # undocumented +single_quoted: set[str] # undocumented +triple_quoted: set[str] # undocumented tabsize: int # undocumented diff --git a/mypy/typeshed/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi index eaf9850b2126..e685b09a6ae4 100644 --- a/mypy/typeshed/stdlib/traceback.pyi +++ b/mypy/typeshed/stdlib/traceback.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import SupportsWrite from types import FrameType, TracebackType -from typing import IO, Any, Generator, Iterable, Iterator, List, Mapping, Optional, Set, Tuple, Type +from typing import IO, Any, Generator, Iterable, Iterator, List, Mapping, Optional, Tuple, Type _PT = Tuple[str, int, str, Optional[str]] @@ -90,7 +90,7 @@ class TracebackException: lookup_lines: bool = ..., capture_locals: bool = ..., compact: bool = ..., - _seen: Set[int] | None = ..., + _seen: set[int] | None = ..., ) -> None: ... @classmethod def from_exception( @@ -112,7 +112,7 @@ class TracebackException: limit: int | None = ..., lookup_lines: bool = ..., capture_locals: bool = ..., - _seen: Set[int] | None = ..., + _seen: set[int] | None = ..., ) -> None: ... @classmethod def from_exception( diff --git a/mypy/typeshed/stdlib/tracemalloc.pyi b/mypy/typeshed/stdlib/tracemalloc.pyi index e812b8247332..ca4d5901b870 100644 --- a/mypy/typeshed/stdlib/tracemalloc.pyi +++ b/mypy/typeshed/stdlib/tracemalloc.pyi @@ -1,7 +1,6 @@ import sys -from typing import Optional, Sequence, Tuple, Union, overload - from _tracemalloc import * +from typing import Optional, Sequence, Tuple, Union, overload def get_object_traceback(obj: object) -> Traceback | None: ... def take_snapshot() -> Snapshot: ... diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index e60c6475e2e9..899024f2dd4d 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -21,7 +21,7 @@ from typing import ( ValuesView, overload, ) -from typing_extensions import Literal, final +from typing_extensions import Literal, ParamSpec, final # Note, all classes "defined" here require special handling. @@ -144,6 +144,8 @@ class CodeType: co_name: str = ..., co_lnotab: bytes = ..., ) -> CodeType: ... + if sys.version_info >= (3, 11): + def co_positions(self) -> Iterable[tuple[int | None, int | None, int | None, int | None]]: ... @final class MappingProxyType(Mapping[_KT, _VT_co], Generic[_KT, _VT_co]): @@ -171,13 +173,17 @@ class SimpleNamespace: class ModuleType: __name__: str - __file__: str + __file__: str | None __dict__: dict[str, Any] __loader__: _LoaderProtocol | None __package__: str | None __path__: MutableSequence[str] __spec__: ModuleSpec | None def __init__(self, name: str, doc: str | None = ...) -> None: ... + # __getattr__ doesn't exist at runtime, + # but having it here in typeshed makes dynamic imports + # using `builtins.__import__` or `importlib.import_module` less painful + def __getattr__(self, name: str) -> Any: ... @final class GeneratorType(Generator[_T_co, _T_contra, _V_co]): @@ -370,7 +376,15 @@ def prepare_class( # Actually a different type, but `property` is special and we want that too. DynamicClassAttribute = property -def coroutine(func: Callable[..., Any]) -> CoroutineType[Any, Any, Any]: ... +_Fn = TypeVar("_Fn", bound=Callable[..., object]) +_R = TypeVar("_R") +_P = ParamSpec("_P") + +# it's not really an Awaitable, but can be used in an await expression. Real type: Generator & Awaitable +@overload +def coroutine(func: Callable[_P, Generator[_R, Any, Any]]) -> Callable[_P, Awaitable[_R]]: ... # type: ignore +@overload +def coroutine(func: _Fn) -> _Fn: ... # type: ignore if sys.version_info >= (3, 8): CellType = _Cell diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 9df12664be01..4656add7ec21 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -2,7 +2,7 @@ import collections # Needed by aliases like DefaultDict, see mypy issue 2986 import sys from abc import ABCMeta, abstractmethod from types import BuiltinFunctionType, CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType -from typing_extensions import Literal as _Literal, ParamSpec as _ParamSpec +from typing_extensions import Literal as _Literal, ParamSpec as _ParamSpec, final as _final if sys.version_info >= (3, 7): from types import MethodDescriptorType, MethodWrapperType, WrapperDescriptorType @@ -50,6 +50,7 @@ Protocol: _SpecialForm = ... Callable: _SpecialForm = ... Type: _SpecialForm = ... ClassVar: _SpecialForm = ... +NoReturn: _SpecialForm = ... if sys.version_info >= (3, 8): Final: _SpecialForm = ... def final(f: _T) -> _T: ... @@ -83,11 +84,6 @@ if sys.version_info >= (3, 10): TypeAlias: _SpecialForm = ... TypeGuard: _SpecialForm = ... -# Return type that indicates a function does not return. -# This type is equivalent to the None type, but the no-op Union is necessary to -# distinguish the None type from the None value. -NoReturn = Union[None] - # These type variables are used by the container types. _S = TypeVar("_S") _KT = TypeVar("_KT") # Key type. @@ -167,7 +163,7 @@ class SupportsRound(Protocol[_T_co]): def __round__(self) -> int: ... @overload @abstractmethod - def __round__(self, ndigits: int) -> _T_co: ... + def __round__(self, __ndigits: int) -> _T_co: ... @runtime_checkable class Sized(Protocol, metaclass=ABCMeta): @@ -382,33 +378,33 @@ class MappingView(Sized): class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... # undocumented - def __and__(self, o: Iterable[Any]) -> Set[tuple[_KT_co, _VT_co]]: ... - def __rand__(self, o: Iterable[_T]) -> Set[_T]: ... + def __and__(self, o: Iterable[Any]) -> set[tuple[_KT_co, _VT_co]]: ... + def __rand__(self, o: Iterable[_T]) -> set[_T]: ... def __contains__(self, o: object) -> bool: ... def __iter__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... if sys.version_info >= (3, 8): def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ... - def __or__(self, o: Iterable[_T]) -> Set[tuple[_KT_co, _VT_co] | _T]: ... - def __ror__(self, o: Iterable[_T]) -> Set[tuple[_KT_co, _VT_co] | _T]: ... - def __sub__(self, o: Iterable[Any]) -> Set[tuple[_KT_co, _VT_co]]: ... - def __rsub__(self, o: Iterable[_T]) -> Set[_T]: ... - def __xor__(self, o: Iterable[_T]) -> Set[tuple[_KT_co, _VT_co] | _T]: ... - def __rxor__(self, o: Iterable[_T]) -> Set[tuple[_KT_co, _VT_co] | _T]: ... + def __or__(self, o: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... + def __ror__(self, o: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... + def __sub__(self, o: Iterable[Any]) -> set[tuple[_KT_co, _VT_co]]: ... + def __rsub__(self, o: Iterable[_T]) -> set[_T]: ... + def __xor__(self, o: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... + def __rxor__(self, o: Iterable[_T]) -> set[tuple[_KT_co, _VT_co] | _T]: ... class KeysView(MappingView, AbstractSet[_KT_co], Generic[_KT_co]): def __init__(self, mapping: Mapping[_KT_co, Any]) -> None: ... # undocumented - def __and__(self, o: Iterable[Any]) -> Set[_KT_co]: ... - def __rand__(self, o: Iterable[_T]) -> Set[_T]: ... + def __and__(self, o: Iterable[Any]) -> set[_KT_co]: ... + def __rand__(self, o: Iterable[_T]) -> set[_T]: ... def __contains__(self, o: object) -> bool: ... def __iter__(self) -> Iterator[_KT_co]: ... if sys.version_info >= (3, 8): def __reversed__(self) -> Iterator[_KT_co]: ... - def __or__(self, o: Iterable[_T]) -> Set[_KT_co | _T]: ... - def __ror__(self, o: Iterable[_T]) -> Set[_KT_co | _T]: ... - def __sub__(self, o: Iterable[Any]) -> Set[_KT_co]: ... - def __rsub__(self, o: Iterable[_T]) -> Set[_T]: ... - def __xor__(self, o: Iterable[_T]) -> Set[_KT_co | _T]: ... - def __rxor__(self, o: Iterable[_T]) -> Set[_KT_co | _T]: ... + def __or__(self, o: Iterable[_T]) -> set[_KT_co | _T]: ... + def __ror__(self, o: Iterable[_T]) -> set[_KT_co | _T]: ... + def __sub__(self, o: Iterable[Any]) -> set[_KT_co]: ... + def __rsub__(self, o: Iterable[_T]) -> set[_T]: ... + def __xor__(self, o: Iterable[_T]) -> set[_KT_co | _T]: ... + def __rxor__(self, o: Iterable[_T]) -> set[_KT_co | _T]: ... class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): def __init__(self, mapping: Mapping[Any, _VT_co]) -> None: ... # undocumented @@ -435,29 +431,29 @@ class Mapping(Collection[_KT], Generic[_KT, _VT_co]): # TODO: We wish the key type could also be covariant, but that doesn't work, # see discussion in https://github.com/python/typing/pull/273. @abstractmethod - def __getitem__(self, k: _KT) -> _VT_co: ... + def __getitem__(self, __k: _KT) -> _VT_co: ... # Mixin methods @overload def get(self, key: _KT) -> _VT_co | None: ... @overload - def get(self, key: _KT, default: _VT_co | _T) -> _VT_co | _T: ... + def get(self, __key: _KT, __default: _VT_co | _T) -> _VT_co | _T: ... def items(self) -> ItemsView[_KT, _VT_co]: ... def keys(self) -> KeysView[_KT]: ... def values(self) -> ValuesView[_VT_co]: ... - def __contains__(self, o: object) -> bool: ... + def __contains__(self, __o: object) -> bool: ... class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): @abstractmethod - def __setitem__(self, k: _KT, v: _VT) -> None: ... + def __setitem__(self, __k: _KT, __v: _VT) -> None: ... @abstractmethod - def __delitem__(self, v: _KT) -> None: ... + def __delitem__(self, __v: _KT) -> None: ... def clear(self) -> None: ... @overload - def pop(self, key: _KT) -> _VT: ... + def pop(self, __key: _KT) -> _VT: ... @overload - def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... + def pop(self, __key: _KT, __default: _VT | _T = ...) -> _VT | _T: ... def popitem(self) -> tuple[_KT, _VT]: ... - def setdefault(self, key: _KT, default: _VT = ...) -> _VT: ... + def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ... # 'update' used to take a Union, but using overloading is better. # The second overloaded type here is a bit too general, because # Mapping[Tuple[_KT, _VT], W] is a subclass of Iterable[Tuple[_KT, _VT]], @@ -549,6 +545,7 @@ class TextIO(IO[str]): class ByteString(Sequence[int], metaclass=ABCMeta): ... +@_final class Match(Generic[AnyStr]): pos: int endpos: int @@ -592,6 +589,7 @@ class Match(Generic[AnyStr]): if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... +@_final class Pattern(Generic[AnyStr]): flags: int groupindex: Mapping[str, int] diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index 59fe3df390d2..ce407f996022 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -43,6 +43,9 @@ def runtime_checkable(cls: _TC) -> _TC: ... runtime = runtime_checkable Protocol: _SpecialForm = ... Final: _SpecialForm = ... +Self: _SpecialForm = ... +Required: _SpecialForm = ... +NotRequired: _SpecialForm = ... def final(f: _F) -> _F: ... @@ -52,6 +55,9 @@ def IntVar(name: str) -> Any: ... # returns a new TypeVar # Internal mypy fallback type for all typed dicts (does not exist at runtime) class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): + __required_keys__: frozenset[str] + __optional_keys__: frozenset[str] + __total__: bool def copy(self: _T) -> _T: ... # Using NoReturn so that only calls using mypy plugin hook that specialize the signature # can go through. @@ -69,14 +75,13 @@ TypedDict: object = ... OrderedDict = _Alias() -def get_type_hints( - obj: Callable[..., Any], - globalns: dict[str, Any] | None = ..., - localns: dict[str, Any] | None = ..., - include_extras: bool = ..., -) -> dict[str, Any]: ... - if sys.version_info >= (3, 7): + def get_type_hints( + obj: Callable[..., Any], + globalns: dict[str, Any] | None = ..., + localns: dict[str, Any] | None = ..., + include_extras: bool = ..., + ) -> dict[str, Any]: ... def get_args(tp: Any) -> Tuple[Any, ...]: ... def get_origin(tp: Any) -> Any | None: ... diff --git a/mypy/typeshed/stdlib/unittest/case.pyi b/mypy/typeshed/stdlib/unittest/case.pyi index ebb1f2457e68..2ae07144373c 100644 --- a/mypy/typeshed/stdlib/unittest/case.pyi +++ b/mypy/typeshed/stdlib/unittest/case.pyi @@ -3,14 +3,14 @@ import logging import sys import unittest.result from _typeshed import Self -from collections.abc import Set +from collections.abc import Set # equivalent to typing.AbstractSet, not builtins.set +from contextlib import AbstractContextManager from types import TracebackType from typing import ( Any, AnyStr, Callable, Container, - ContextManager, Generic, Iterable, Mapping, @@ -61,7 +61,7 @@ class TestCase: def run(self, result: unittest.result.TestResult | None = ...) -> unittest.result.TestResult | None: ... def __call__(self, result: unittest.result.TestResult | None = ...) -> unittest.result.TestResult | None: ... def skipTest(self, reason: Any) -> None: ... - def subTest(self, msg: Any = ..., **params: Any) -> ContextManager[None]: ... + def subTest(self, msg: Any = ..., **params: Any) -> AbstractContextManager[None]: ... def debug(self) -> None: ... def _addSkip(self, result: unittest.result.TestResult, test_case: TestCase, reason: str) -> None: ... def assertEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/warnings.pyi b/mypy/typeshed/stdlib/warnings.pyi index f6ab5a456d33..b1c9f4dda8ed 100644 --- a/mypy/typeshed/stdlib/warnings.pyi +++ b/mypy/typeshed/stdlib/warnings.pyi @@ -1,9 +1,8 @@ +from _warnings import warn as warn, warn_explicit as warn_explicit from types import ModuleType, TracebackType from typing import Any, Sequence, TextIO, Type, overload from typing_extensions import Literal -from _warnings import warn as warn, warn_explicit as warn_explicit - _ActionKind = Literal["default", "error", "ignore", "always", "module", "once"] filters: Sequence[tuple[str, str | None, Type[Warning], str | None, int]] # undocumented, do not mutate diff --git a/mypy/typeshed/stdlib/weakref.pyi b/mypy/typeshed/stdlib/weakref.pyi index 64abec36c7ec..dbb6b49f2f2e 100644 --- a/mypy/typeshed/stdlib/weakref.pyi +++ b/mypy/typeshed/stdlib/weakref.pyi @@ -42,6 +42,11 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore def itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: ... def valuerefs(self) -> list[KeyedRef[_KT, _VT]]: ... + def setdefault(self, key: _KT, default: _VT = ...) -> _VT: ... + @overload + def pop(self, key: _KT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... class KeyedRef(ref[_T], Generic[_KT, _T]): key: _KT @@ -67,6 +72,11 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def values(self) -> Iterator[_VT]: ... # type: ignore def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore def keyrefs(self) -> list[ref[_KT]]: ... + def setdefault(self, key: _KT, default: _VT = ...) -> _VT: ... + @overload + def pop(self, key: _KT) -> _VT: ... + @overload + def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... class finalize: def __init__(self, __obj: object, __func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/winreg.pyi b/mypy/typeshed/stdlib/winreg.pyi index aeba48630a75..5fff1104e246 100644 --- a/mypy/typeshed/stdlib/winreg.pyi +++ b/mypy/typeshed/stdlib/winreg.pyi @@ -1,6 +1,7 @@ from _typeshed import Self from types import TracebackType from typing import Any, Type, Union +from typing_extensions import final _KeyType = Union[HKEYType, int] @@ -88,6 +89,7 @@ REG_WHOLE_HIVE_VOLATILE: int # undocumented error = OSError # Though this class has a __name__ of PyHKEY, it's exposed as HKEYType for some reason +@final class HKEYType: def __bool__(self) -> bool: ... def __int__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi index 2a188c7d0477..4f924e0cc4bf 100644 --- a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi +++ b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi @@ -1,7 +1,7 @@ import typing from _typeshed import StrPath from datetime import tzinfo -from typing import Any, Iterable, Protocol, Sequence, Set, Type +from typing import Any, Iterable, Protocol, Sequence, Type _T = typing.TypeVar("_T", bound="ZoneInfo") @@ -24,7 +24,7 @@ class ZoneInfo(tzinfo): # a sequence of strings is required. This should be remedied if a solution # to this typing bug is found: https://github.com/python/typing/issues/256 def reset_tzpath(to: Sequence[StrPath] | None = ...) -> None: ... -def available_timezones() -> Set[str]: ... +def available_timezones() -> set[str]: ... TZPATH: Sequence[str] From 91dd388a774093a3985a1a982a76e45d3ecbb965 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 23 Nov 2021 11:09:30 +0000 Subject: [PATCH 2/3] Prepare for typeshed sync: simplify test case --- test-data/unit/cmdline.test | 4 ---- 1 file changed, 4 deletions(-) diff --git a/test-data/unit/cmdline.test b/test-data/unit/cmdline.test index 93eb893d3c00..b760d3af6504 100644 --- a/test-data/unit/cmdline.test +++ b/test-data/unit/cmdline.test @@ -642,10 +642,6 @@ reveal_type(a**(-2)) # N: Revealed type is "builtins.float" reveal_type(a**b) # N: Revealed type is "Any" reveal_type(a.__pow__(2)) # N: Revealed type is "builtins.int" reveal_type(a.__pow__(a)) # N: Revealed type is "Any" -a.__pow__() # E: All overload variants of "__pow__" of "int" require at least one argument \ - # N: Possible overload variants: \ - # N: def __pow__(self, Literal[2], Optional[int] = ...) -> int \ - # N: def __pow__(self, int, Optional[int] = ...) -> Any [case testDisallowAnyGenericsBuiltinCollections] # cmd: mypy m.py From b590dc0ebbc48c24dbe105e016ff94fb156f0c18 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 23 Nov 2021 11:23:45 +0000 Subject: [PATCH 3/3] Update tests --- test-data/unit/pythoneval.test | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test-data/unit/pythoneval.test b/test-data/unit/pythoneval.test index 183aac9a1985..90588a86d8bf 100644 --- a/test-data/unit/pythoneval.test +++ b/test-data/unit/pythoneval.test @@ -1085,7 +1085,7 @@ _testTypedDictGet.py:9: note: Revealed type is "builtins.object*" _testTypedDictGet.py:10: error: All overload variants of "get" of "Mapping" require at least one argument _testTypedDictGet.py:10: note: Possible overload variants: _testTypedDictGet.py:10: note: def get(self, key: str) -> object -_testTypedDictGet.py:10: note: def [_T] get(self, key: str, default: object) -> object +_testTypedDictGet.py:10: note: def [_T] get(self, str, object) -> object _testTypedDictGet.py:12: note: Revealed type is "builtins.object*" [case testTypedDictMappingMethods] @@ -1456,9 +1456,9 @@ frozenset({1}) == [1] # Error {1: 2}.keys() == [1] # Error [out] _testStrictEqualityAllowlist.py:5: error: Non-overlapping equality check (left operand type: "FrozenSet[int]", right operand type: "List[int]") -_testStrictEqualityAllowlist.py:11: error: Non-overlapping equality check (left operand type: "_dict_keys[int, int]", right operand type: "Set[str]") -_testStrictEqualityAllowlist.py:12: error: Non-overlapping equality check (left operand type: "_dict_values[int, int]", right operand type: "Set[int]") -_testStrictEqualityAllowlist.py:13: error: Non-overlapping equality check (left operand type: "_dict_keys[int, int]", right operand type: "List[int]") +_testStrictEqualityAllowlist.py:11: error: Non-overlapping equality check (left operand type: "dict_keys[int, int]", right operand type: "Set[str]") +_testStrictEqualityAllowlist.py:12: error: Non-overlapping equality check (left operand type: "dict_values[int, int]", right operand type: "Set[int]") +_testStrictEqualityAllowlist.py:13: error: Non-overlapping equality check (left operand type: "dict_keys[int, int]", right operand type: "List[int]") [case testUnreachableWithStdlibContextManagers] # mypy: warn-unreachable, strict-optional