diff --git a/mypy/typeshed/stdlib/@python2/__builtin__.pyi b/mypy/typeshed/stdlib/@python2/__builtin__.pyi index 453a95871463..95252ef2dd66 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: ... 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..95252ef2dd66 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: ... 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/_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/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 4694042cab24..0b952f1e6fb6 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, @@ -17,11 +19,11 @@ from _typeshed import ( 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, @@ -33,10 +35,8 @@ from typing import ( Callable, FrozenSet, Generic, - ItemsView, Iterable, Iterator, - KeysView, Mapping, MutableMapping, MutableSequence, @@ -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,39 @@ 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: ... 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 +200,53 @@ 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: Literal[2, 3, 4, 5], __modulo: int | None = ...) -> int: ... + # 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: int | 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 +267,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 +322,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 +346,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 +410,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 + 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 +432,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 +513,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 + 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: ... @@ -604,29 +615,30 @@ class bytearray(MutableSequence[int], ByteString): def __repr__(self) -> str: ... __hash__: None # type: ignore @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 + 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 +656,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 +687,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: ... + def __init__(self, __start: Any, __stop: Any, __step: Any = ...) -> None: ... __hash__: None # type: ignore - def indices(self, len: SupportsIndex) -> tuple[int, int, int]: ... + 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 +760,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: ... @@ -767,41 +780,27 @@ class list(MutableSequence[_T], Generic[_T]): def __str__(self) -> str: ... __hash__: None # type: ignore @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 +808,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 +826,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 +836,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 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 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 difference_update(self, *s: Iterable[Any]) -> None: ... - def discard(self, element: _T) -> None: ... + 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: ... + 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 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 __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 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 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,13 +953,14 @@ 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: ... + 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 # A little weird, but typing the __call__ as NotImplemented makes the error message # for NotImplemented() much better @@ -976,7 +977,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 +994,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 +1009,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 +1019,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 +1048,31 @@ 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) @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: _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, ...], ...] @@ -1248,8 +1256,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) @@ -1263,11 +1284,19 @@ class _SupportsPow3(Protocol[_E, _M, _T_co]): 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: ... + # 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: int, exp: int, mod: int) -> int: ... @overload - def pow(base: float, exp: float, mod: None = ...) -> float: ... + def pow(base: float, exp: int, mod: None = ...) -> float: ... + # float base & float exp could return float or complex + # return type must be Any as `float | complex` causes too many false-positive errors + @overload + def pow(base: float, exp: float, mod: None = ...) -> Any: ... @overload def pow(base: _SupportsPow2[_E, _T_co], exp: _E) -> _T_co: ... @overload @@ -1275,13 +1304,15 @@ if sys.version_info >= (3, 8): 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: None = ...) -> Any: ... @overload def pow(__base: int, __exp: int, __mod: int) -> int: ... @overload - def pow(__base: float, __exp: float, __mod: None = ...) -> float: ... + def pow(__base: float, __exp: int, __mod: None = ...) -> float: ... + @overload + def pow(__base: float, __exp: float, __mod: None = ...) -> Any: ... @overload def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E) -> _T_co: ... @overload @@ -1304,6 +1335,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 +1356,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 +1437,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 +1463,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..9b26a756cc76 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 @@ -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 @@ -238,15 +241,16 @@ 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]): @@ -256,26 +260,28 @@ class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): 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]): diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index 8c362cfd1633..f0ae8312b6bc 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import Self +from _typeshed import Self, StrOrBytesPath from types import TracebackType from typing import ( IO, @@ -9,6 +9,7 @@ from typing import ( Awaitable, Callable, ContextManager, + Generic, Iterator, Optional, Type, @@ -124,3 +125,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/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index 746643d8433c..dc651cb3b5ad 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -1,6 +1,7 @@ import sys from time import struct_time from typing import ClassVar, NamedTuple, SupportsAbs, Type, TypeVar, overload +from typing_extensions import final _S = TypeVar("_S") @@ -16,6 +17,7 @@ class tzinfo: # Alias required to avoid name conflicts with date(time).tzinfo. _tzinfo = tzinfo +@final class timezone(tzinfo): utc: ClassVar[timezone] min: ClassVar[timezone] @@ -200,12 +202,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: ... @@ -221,10 +217,6 @@ class datetime(date): 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: ... - @classmethod - def fromordinal(cls: Type[_S], n: int) -> _S: ... if sys.version_info >= (3, 8): @classmethod def now(cls: Type[_S], tz: _tzinfo | None = ...) -> _S: ... @@ -242,10 +234,6 @@ class datetime(date): 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 timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... def date(self) -> _date: ... @@ -279,19 +267,13 @@ class datetime(date): 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: ... - else: + if sys.version_info < (3, 8): 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: ... 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/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index 6fe4bb6f8e9e..8b3ac58ac310 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -2,6 +2,7 @@ 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_extensions import ParamSpec, final if sys.version_info >= (3, 9): from types import GenericAlias @@ -10,6 +11,7 @@ _AnyCallable = Callable[..., Any] _T = TypeVar("_T") _S = TypeVar("_S") +_P = ParamSpec("_P") @overload def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ... @@ -22,20 +24,21 @@ class _CacheInfo(NamedTuple): maxsize: int currsize: int -class _lru_cache_wrapper(Generic[_T]): - __wrapped__: Callable[..., _T] - def __call__(self, *args: Hashable, **kwargs: Hashable) -> _T: ... +@final +class _lru_cache_wrapper(Generic[_P, _T]): # type: ignore + __wrapped__: Callable[_P, _T] # type: ignore + def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _T: ... # type: ignore def cache_info(self) -> _CacheInfo: ... def cache_clear(self) -> None: ... if sys.version_info >= (3, 8): @overload - def lru_cache(maxsize: int | None = ..., typed: bool = ...) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... + def lru_cache(maxsize: int | None = ..., typed: bool = ...) -> Callable[[Callable[_P, _T]], _lru_cache_wrapper[_P, _T]]: ... # type: ignore @overload - def lru_cache(maxsize: Callable[..., _T], typed: bool = ...) -> _lru_cache_wrapper[_T]: ... + def lru_cache(maxsize: Callable[_P, _T], typed: bool = ...) -> _lru_cache_wrapper[_P, _T]: ... # type: ignore else: - def lru_cache(maxsize: int | None = ..., typed: bool = ...) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ... + def lru_cache(maxsize: int | None = ..., typed: bool = ...) -> Callable[[Callable[_P, _T]], _lru_cache_wrapper[_P, _T]]: ... # type: ignore WRAPPER_ASSIGNMENTS: Sequence[str] WRAPPER_UPDATES: Sequence[str] @@ -115,7 +118,7 @@ if sys.version_info >= (3, 8): def __class_getitem__(cls, item: Any) -> GenericAlias: ... if sys.version_info >= (3, 9): - def cache(__user_function: Callable[..., _T]) -> _lru_cache_wrapper[_T]: ... + def cache(__user_function: Callable[_P, _T]) -> _lru_cache_wrapper[_P, _T]: ... # type: ignore def _make_key( args: Tuple[Hashable, ...], 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/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index ddb7293ae701..c94b9b105920 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -7,16 +7,23 @@ from collections.abc import Awaitable, Callable, Generator, Mapping, Sequence, S 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 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/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..7a4588a9793b 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -37,7 +37,7 @@ from typing import ( overload, runtime_checkable, ) -from typing_extensions import Literal +from typing_extensions import Literal, final from . import path as _path @@ -262,6 +262,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 +315,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 +336,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 +569,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 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/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/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..829db6c012d6 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -407,7 +407,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 +730,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 +774,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 +816,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 @@ -954,7 +954,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 = ..., @@ -2960,7 +2960,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/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..ebf95db5795b 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. @@ -171,13 +171,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 +374,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..bd9c9d873069 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): @@ -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/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/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: ...