diff --git a/mypy/typeshed/stdlib/@python2/BaseHTTPServer.pyi b/mypy/typeshed/stdlib/@python2/BaseHTTPServer.pyi index 46946aa37c46..9aad705bde6c 100644 --- a/mypy/typeshed/stdlib/@python2/BaseHTTPServer.pyi +++ b/mypy/typeshed/stdlib/@python2/BaseHTTPServer.pyi @@ -1,14 +1,14 @@ import mimetools import SocketServer -from typing import Any, BinaryIO, Callable, Mapping, Tuple +from typing import Any, BinaryIO, Callable, Mapping class HTTPServer(SocketServer.TCPServer): server_name: str server_port: int - def __init__(self, server_address: Tuple[str, int], RequestHandlerClass: Callable[..., BaseHTTPRequestHandler]) -> None: ... + def __init__(self, server_address: tuple[str, int], RequestHandlerClass: Callable[..., BaseHTTPRequestHandler]) -> None: ... class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): - client_address: Tuple[str, int] + client_address: tuple[str, int] server: SocketServer.BaseServer close_connection: bool command: str @@ -23,8 +23,8 @@ class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): error_content_type: str protocol_version: str MessageClass: type - responses: Mapping[int, Tuple[str, str]] - def __init__(self, request: bytes, client_address: Tuple[str, int], server: SocketServer.BaseServer) -> None: ... + responses: Mapping[int, tuple[str, str]] + def __init__(self, request: bytes, client_address: tuple[str, int], server: SocketServer.BaseServer) -> None: ... def handle(self) -> None: ... def handle_one_request(self) -> None: ... def send_error(self, code: int, message: str | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/CGIHTTPServer.pyi b/mypy/typeshed/stdlib/@python2/CGIHTTPServer.pyi index 393dcb83217f..cc08bc02d666 100644 --- a/mypy/typeshed/stdlib/@python2/CGIHTTPServer.pyi +++ b/mypy/typeshed/stdlib/@python2/CGIHTTPServer.pyi @@ -1,6 +1,5 @@ import SimpleHTTPServer -from typing import List class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): - cgi_directories: List[str] + cgi_directories: list[str] def do_POST(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/ConfigParser.pyi b/mypy/typeshed/stdlib/@python2/ConfigParser.pyi index 89167b3e7ec8..ebf2a434e596 100644 --- a/mypy/typeshed/stdlib/@python2/ConfigParser.pyi +++ b/mypy/typeshed/stdlib/@python2/ConfigParser.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsNoArgReadline -from typing import IO, Any, Dict, List, Sequence, Tuple +from typing import IO, Any, Sequence DEFAULTSECT: str MAX_INTERPOLATION_DEPTH: int @@ -9,8 +9,6 @@ class Error(Exception): def __init__(self, msg: str = ...) -> None: ... def _get_message(self) -> None: ... def _set_message(self, value: str) -> None: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... class NoSectionError(Error): section: str @@ -42,7 +40,7 @@ class InterpolationDepthError(InterpolationError): class ParsingError(Error): filename: str - errors: List[Tuple[Any, Any]] + errors: list[tuple[Any, Any]] def __init__(self, filename: str) -> None: ... def append(self, lineno: Any, line: Any) -> None: ... @@ -53,26 +51,26 @@ class MissingSectionHeaderError(ParsingError): class RawConfigParser: _dict: Any - _sections: Dict[Any, Any] - _defaults: Dict[Any, Any] + _sections: dict[Any, Any] + _defaults: dict[Any, Any] _optcre: Any SECTCRE: Any OPTCRE: Any OPTCRE_NV: Any - def __init__(self, defaults: Dict[Any, Any] = ..., dict_type: Any = ..., allow_no_value: bool = ...) -> None: ... - def defaults(self) -> Dict[Any, Any]: ... - def sections(self) -> List[str]: ... + def __init__(self, defaults: dict[Any, Any] = ..., dict_type: Any = ..., allow_no_value: bool = ...) -> None: ... + def defaults(self) -> dict[Any, Any]: ... + def sections(self) -> list[str]: ... def add_section(self, section: str) -> None: ... def has_section(self, section: str) -> bool: ... - def options(self, section: str) -> List[str]: ... - def read(self, filenames: str | Sequence[str]) -> List[str]: ... + def options(self, section: str) -> list[str]: ... + def read(self, filenames: str | Sequence[str]) -> list[str]: ... def readfp(self, fp: SupportsNoArgReadline[str], filename: str = ...) -> None: ... def get(self, section: str, option: str) -> str: ... - def items(self, section: str) -> List[Tuple[Any, Any]]: ... + def items(self, section: str) -> list[tuple[Any, Any]]: ... def _get(self, section: str, conv: type, option: str) -> Any: ... def getint(self, section: str, option: str) -> int: ... def getfloat(self, section: str, option: str) -> float: ... - _boolean_states: Dict[str, bool] + _boolean_states: dict[str, bool] def getboolean(self, section: str, option: str) -> bool: ... def optionxform(self, optionstr: str) -> str: ... def has_option(self, section: str, option: str) -> bool: ... @@ -84,8 +82,8 @@ class RawConfigParser: class ConfigParser(RawConfigParser): _KEYCRE: Any - def get(self, section: str, option: str, raw: bool = ..., vars: Dict[Any, Any] | None = ...) -> Any: ... - def items(self, section: str, raw: bool = ..., vars: Dict[Any, Any] | None = ...) -> List[Tuple[str, Any]]: ... + def get(self, section: str, option: str, raw: bool = ..., vars: dict[Any, Any] | None = ...) -> Any: ... + def items(self, section: str, raw: bool = ..., vars: dict[Any, Any] | None = ...) -> list[tuple[str, Any]]: ... def _interpolate(self, section: str, option: str, rawval: Any, vars: Any) -> str: ... def _interpolation_replace(self, match: Any) -> str: ... @@ -93,5 +91,5 @@ class SafeConfigParser(ConfigParser): _interpvar_re: Any def _interpolate(self, section: str, option: str, rawval: Any, vars: Any) -> str: ... def _interpolate_some( - self, option: str, accum: List[Any], rest: str, section: str, map: Dict[Any, Any], depth: int + self, option: str, accum: list[Any], rest: str, section: str, map: dict[Any, Any], depth: int ) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/Cookie.pyi b/mypy/typeshed/stdlib/@python2/Cookie.pyi index 3d01c3c66152..dcc27a2d349d 100644 --- a/mypy/typeshed/stdlib/@python2/Cookie.pyi +++ b/mypy/typeshed/stdlib/@python2/Cookie.pyi @@ -1,8 +1,8 @@ -from typing import Any, Dict +from typing import Any class CookieError(Exception): ... -class Morsel(Dict[Any, Any]): +class Morsel(dict[Any, Any]): key: Any def __init__(self): ... def __setitem__(self, K, V): ... @@ -14,7 +14,7 @@ class Morsel(Dict[Any, Any]): def js_output(self, attrs: Any | None = ...): ... def OutputString(self, attrs: Any | None = ...): ... -class BaseCookie(Dict[Any, Any]): +class BaseCookie(dict[Any, Any]): def value_decode(self, val): ... def value_encode(self, val): ... def __init__(self, input: Any | None = ...): ... diff --git a/mypy/typeshed/stdlib/@python2/HTMLParser.pyi b/mypy/typeshed/stdlib/@python2/HTMLParser.pyi index ebc2735e9c48..755f0d058b15 100644 --- a/mypy/typeshed/stdlib/@python2/HTMLParser.pyi +++ b/mypy/typeshed/stdlib/@python2/HTMLParser.pyi @@ -1,4 +1,4 @@ -from typing import AnyStr, List, Tuple +from typing import AnyStr from markupbase import ParserBase @@ -10,8 +10,8 @@ class HTMLParser(ParserBase): def get_starttag_text(self) -> AnyStr: ... def set_cdata_mode(self, AnyStr) -> None: ... def clear_cdata_mode(self) -> None: ... - def handle_startendtag(self, tag: AnyStr, attrs: List[Tuple[AnyStr, AnyStr]]): ... - def handle_starttag(self, tag: AnyStr, attrs: List[Tuple[AnyStr, AnyStr]]): ... + def handle_startendtag(self, tag: AnyStr, attrs: list[tuple[AnyStr, AnyStr]]): ... + def handle_starttag(self, tag: AnyStr, attrs: list[tuple[AnyStr, AnyStr]]): ... def handle_endtag(self, tag: AnyStr): ... def handle_charref(self, name: AnyStr): ... def handle_entityref(self, name: AnyStr): ... diff --git a/mypy/typeshed/stdlib/@python2/Queue.pyi b/mypy/typeshed/stdlib/@python2/Queue.pyi index 24743a80280d..a53380723188 100644 --- a/mypy/typeshed/stdlib/@python2/Queue.pyi +++ b/mypy/typeshed/stdlib/@python2/Queue.pyi @@ -1,4 +1,5 @@ -from typing import Any, Deque, Generic, TypeVar +from collections import deque +from typing import Any, Generic, TypeVar _T = TypeVar("_T") @@ -12,7 +13,7 @@ class Queue(Generic[_T]): not_full: Any all_tasks_done: Any unfinished_tasks: Any - queue: Deque[Any] # undocumented + queue: deque[Any] # undocumented def __init__(self, maxsize: int = ...) -> None: ... def task_done(self) -> None: ... def join(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/SocketServer.pyi b/mypy/typeshed/stdlib/@python2/SocketServer.pyi index e5a19ffd5e68..809066516b00 100644 --- a/mypy/typeshed/stdlib/@python2/SocketServer.pyi +++ b/mypy/typeshed/stdlib/@python2/SocketServer.pyi @@ -1,11 +1,11 @@ import sys from socket import SocketType -from typing import Any, BinaryIO, Callable, ClassVar, List, Text, Tuple, Union +from typing import Any, BinaryIO, Callable, ClassVar, Text, Union class BaseServer: address_family: int RequestHandlerClass: Callable[..., BaseRequestHandler] - server_address: Tuple[str, int] + server_address: tuple[str, int] socket: SocketType allow_reuse_address: bool request_queue_size: int @@ -17,19 +17,19 @@ class BaseServer: def serve_forever(self, poll_interval: float = ...) -> None: ... def shutdown(self) -> None: ... def server_close(self) -> None: ... - def finish_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... - def get_request(self) -> Tuple[SocketType, Tuple[str, int]]: ... - def handle_error(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + def finish_request(self, request: bytes, client_address: tuple[str, int]) -> None: ... + def get_request(self) -> tuple[SocketType, tuple[str, int]]: ... + def handle_error(self, request: bytes, client_address: tuple[str, int]) -> None: ... def handle_timeout(self) -> None: ... - def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + def process_request(self, request: bytes, client_address: tuple[str, int]) -> None: ... def server_activate(self) -> None: ... def server_bind(self) -> None: ... - def verify_request(self, request: bytes, client_address: Tuple[str, int]) -> bool: ... + def verify_request(self, request: bytes, client_address: tuple[str, int]) -> bool: ... class TCPServer(BaseServer): def __init__( self, - server_address: Tuple[str, int], + server_address: tuple[str, int], RequestHandlerClass: Callable[..., BaseRequestHandler], bind_and_activate: bool = ..., ) -> None: ... @@ -37,7 +37,7 @@ class TCPServer(BaseServer): class UDPServer(BaseServer): def __init__( self, - server_address: Tuple[str, int], + server_address: tuple[str, int], RequestHandlerClass: Callable[..., BaseRequestHandler], bind_and_activate: bool = ..., ) -> None: ... @@ -61,16 +61,16 @@ if sys.platform != "win32": if sys.platform != "win32": class ForkingMixIn: timeout: float | None # undocumented - active_children: List[int] | None # undocumented + active_children: list[int] | None # undocumented max_children: int # undocumented def collect_children(self) -> None: ... # undocumented def handle_timeout(self) -> None: ... # undocumented - def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + def process_request(self, request: bytes, client_address: tuple[str, int]) -> None: ... class ThreadingMixIn: daemon_threads: bool - def process_request_thread(self, request: bytes, client_address: Tuple[str, int]) -> None: ... # undocumented - def process_request(self, request: bytes, client_address: Tuple[str, int]) -> None: ... + def process_request_thread(self, request: bytes, client_address: tuple[str, int]) -> None: ... # undocumented + def process_request(self, request: bytes, client_address: tuple[str, int]) -> None: ... if sys.platform != "win32": class ForkingTCPServer(ForkingMixIn, TCPServer): ... diff --git a/mypy/typeshed/stdlib/@python2/StringIO.pyi b/mypy/typeshed/stdlib/@python2/StringIO.pyi index efa90f8e0330..4aa0cb3fcd5a 100644 --- a/mypy/typeshed/stdlib/@python2/StringIO.pyi +++ b/mypy/typeshed/stdlib/@python2/StringIO.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, List +from typing import IO, Any, AnyStr, Generic, Iterable, Iterator class StringIO(IO[AnyStr], Generic[AnyStr]): closed: bool @@ -14,7 +14,7 @@ class StringIO(IO[AnyStr], Generic[AnyStr]): def tell(self) -> int: ... def read(self, n: int = ...) -> AnyStr: ... def readline(self, length: int = ...) -> AnyStr: ... - def readlines(self, sizehint: int = ...) -> List[AnyStr]: ... + def readlines(self, sizehint: int = ...) -> list[AnyStr]: ... def truncate(self, size: int | None = ...) -> int: ... def write(self, s: AnyStr) -> int: ... def writelines(self, iterable: Iterable[AnyStr]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/UserDict.pyi b/mypy/typeshed/stdlib/@python2/UserDict.pyi index dce7bebafd66..fd21ff0e684b 100644 --- a/mypy/typeshed/stdlib/@python2/UserDict.pyi +++ b/mypy/typeshed/stdlib/@python2/UserDict.pyi @@ -1,11 +1,11 @@ -from typing import Any, Container, Dict, Generic, Iterable, Iterator, List, Mapping, Sized, Tuple, TypeVar, overload +from typing import Any, Container, Generic, Iterable, Iterator, Mapping, Sized, TypeVar, overload _KT = TypeVar("_KT") _VT = TypeVar("_VT") _T = TypeVar("_T") -class UserDict(Dict[_KT, _VT], Generic[_KT, _VT]): - data: Dict[_KT, _VT] +class UserDict(dict[_KT, _VT], Generic[_KT, _VT]): + data: dict[_KT, _VT] def __init__(self, initialdata: Mapping[_KT, _VT] = ...) -> None: ... # TODO: __iter__ is not available for UserDict @@ -21,18 +21,18 @@ class DictMixin(Iterable[_KT], Container[_KT], Sized, Generic[_KT, _VT]): def get(self, k: _KT) -> _VT | None: ... @overload def get(self, k: _KT, default: _VT | _T) -> _VT | _T: ... - def values(self) -> List[_VT]: ... - def items(self) -> List[Tuple[_KT, _VT]]: ... + def values(self) -> list[_VT]: ... + def items(self) -> list[tuple[_KT, _VT]]: ... def iterkeys(self) -> Iterator[_KT]: ... def itervalues(self) -> Iterator[_VT]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def iteritems(self) -> Iterator[tuple[_KT, _VT]]: ... def __contains__(self, o: Any) -> bool: ... # From typing.MutableMapping[_KT, _VT] def clear(self) -> None: ... def pop(self, k: _KT, default: _VT = ...) -> _VT: ... - def popitem(self) -> Tuple[_KT, _VT]: ... + def popitem(self) -> tuple[_KT, _VT]: ... def setdefault(self, k: _KT, default: _VT = ...) -> _VT: ... @overload def update(self, m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... @overload - def update(self, m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def update(self, m: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/UserList.pyi b/mypy/typeshed/stdlib/@python2/UserList.pyi index be4ebce5a815..36a4bc6a001c 100644 --- a/mypy/typeshed/stdlib/@python2/UserList.pyi +++ b/mypy/typeshed/stdlib/@python2/UserList.pyi @@ -1,10 +1,10 @@ -from typing import Iterable, List, MutableSequence, TypeVar, overload +from _typeshed import Self +from typing import Iterable, MutableSequence, TypeVar, overload _T = TypeVar("_T") -_S = TypeVar("_S") class UserList(MutableSequence[_T]): - data: List[_T] + data: list[_T] def insert(self, index: int, object: _T) -> None: ... @overload def __setitem__(self, i: int, o: _T) -> None: ... @@ -15,5 +15,5 @@ class UserList(MutableSequence[_T]): @overload def __getitem__(self, i: int) -> _T: ... @overload - def __getitem__(self: _S, s: slice) -> _S: ... + def __getitem__(self: Self, s: slice) -> Self: ... def sort(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/UserString.pyi b/mypy/typeshed/stdlib/@python2/UserString.pyi index f60dbe18f9b1..be802a9e2c72 100644 --- a/mypy/typeshed/stdlib/@python2/UserString.pyi +++ b/mypy/typeshed/stdlib/@python2/UserString.pyi @@ -1,6 +1,6 @@ -from typing import Any, Iterable, List, MutableSequence, Sequence, Text, Tuple, TypeVar, overload +from _typeshed import Self +from typing import Any, Iterable, MutableSequence, Sequence, Text, TypeVar, overload -_UST = TypeVar("_UST", bound=UserString) _MST = TypeVar("_MST", bound=MutableString) class UserString(Sequence[UserString]): @@ -13,21 +13,21 @@ class UserString(Sequence[UserString]): def __hash__(self) -> int: ... def __len__(self) -> int: ... @overload - def __getitem__(self: _UST, i: int) -> _UST: ... + def __getitem__(self: Self, i: int) -> Self: ... @overload - def __getitem__(self: _UST, s: slice) -> _UST: ... - def __add__(self: _UST, other: Any) -> _UST: ... - def __radd__(self: _UST, other: Any) -> _UST: ... - def __mul__(self: _UST, other: int) -> _UST: ... - def __rmul__(self: _UST, other: int) -> _UST: ... - def __mod__(self: _UST, args: Any) -> _UST: ... - def capitalize(self: _UST) -> _UST: ... - def center(self: _UST, width: int, *args: Any) -> _UST: ... + def __getitem__(self: Self, s: slice) -> Self: ... + def __add__(self: Self, other: Any) -> Self: ... + def __radd__(self: Self, other: Any) -> Self: ... + def __mul__(self: Self, other: int) -> Self: ... + def __rmul__(self: Self, other: int) -> Self: ... + def __mod__(self: Self, args: Any) -> Self: ... + def capitalize(self: Self) -> Self: ... + def center(self: Self, width: int, *args: Any) -> Self: ... def count(self, sub: int, start: int = ..., end: int = ...) -> int: ... - def decode(self: _UST, encoding: str | None = ..., errors: str | None = ...) -> _UST: ... - def encode(self: _UST, encoding: str | None = ..., errors: str | None = ...) -> _UST: ... - def endswith(self, suffix: Text | Tuple[Text, ...], start: int | None = ..., end: int | None = ...) -> bool: ... - def expandtabs(self: _UST, tabsize: int = ...) -> _UST: ... + def decode(self: Self, encoding: str | None = ..., errors: str | None = ...) -> Self: ... + def encode(self: Self, encoding: str | None = ..., errors: str | None = ...) -> Self: ... + def endswith(self, suffix: Text | tuple[Text, ...], start: int | None = ..., end: int | None = ...) -> bool: ... + def expandtabs(self: Self, tabsize: int = ...) -> Self: ... def find(self, sub: Text, start: int = ..., end: int = ...) -> int: ... def index(self, sub: Text, start: int = ..., end: int = ...) -> int: ... def isalpha(self) -> bool: ... @@ -40,35 +40,35 @@ class UserString(Sequence[UserString]): def istitle(self) -> bool: ... def isupper(self) -> bool: ... def join(self, seq: Iterable[Text]) -> Text: ... - def ljust(self: _UST, width: int, *args: Any) -> _UST: ... - def lower(self: _UST) -> _UST: ... - def lstrip(self: _UST, chars: Text | None = ...) -> _UST: ... - def partition(self, sep: Text) -> Tuple[Text, Text, Text]: ... - def replace(self: _UST, old: Text, new: Text, maxsplit: int = ...) -> _UST: ... + def ljust(self: Self, width: int, *args: Any) -> Self: ... + def lower(self: Self) -> Self: ... + def lstrip(self: Self, chars: Text | None = ...) -> Self: ... + def partition(self, sep: Text) -> tuple[Text, Text, Text]: ... + def replace(self: Self, old: Text, new: Text, maxsplit: int = ...) -> Self: ... def rfind(self, sub: Text, start: int = ..., end: int = ...) -> int: ... def rindex(self, sub: Text, start: int = ..., end: int = ...) -> int: ... - def rjust(self: _UST, width: int, *args: Any) -> _UST: ... - def rpartition(self, sep: Text) -> Tuple[Text, Text, Text]: ... - def rstrip(self: _UST, chars: Text | None = ...) -> _UST: ... - def split(self, sep: Text | None = ..., maxsplit: int = ...) -> List[Text]: ... - def rsplit(self, sep: Text | None = ..., maxsplit: int = ...) -> List[Text]: ... - def splitlines(self, keepends: int = ...) -> List[Text]: ... - def startswith(self, prefix: Text | Tuple[Text, ...], start: int | None = ..., end: int | None = ...) -> bool: ... - def strip(self: _UST, chars: Text | None = ...) -> _UST: ... - def swapcase(self: _UST) -> _UST: ... - def title(self: _UST) -> _UST: ... - def translate(self: _UST, *args: Any) -> _UST: ... - def upper(self: _UST) -> _UST: ... - def zfill(self: _UST, width: int) -> _UST: ... + def rjust(self: Self, width: int, *args: Any) -> Self: ... + def rpartition(self, sep: Text) -> tuple[Text, Text, Text]: ... + def rstrip(self: Self, chars: Text | None = ...) -> Self: ... + def split(self, sep: Text | None = ..., maxsplit: int = ...) -> list[Text]: ... + def rsplit(self, sep: Text | None = ..., maxsplit: int = ...) -> list[Text]: ... + def splitlines(self, keepends: int = ...) -> list[Text]: ... + def startswith(self, prefix: Text | tuple[Text, ...], start: int | None = ..., end: int | None = ...) -> bool: ... + def strip(self: Self, chars: Text | None = ...) -> Self: ... + def swapcase(self: Self) -> Self: ... + def title(self: Self) -> Self: ... + def translate(self: Self, *args: Any) -> Self: ... + def upper(self: Self) -> Self: ... + def zfill(self: Self, width: int) -> Self: ... class MutableString(UserString, MutableSequence[MutableString]): @overload - def __getitem__(self: _MST, i: int) -> _MST: ... + def __getitem__(self: Self, i: int) -> Self: ... @overload - def __getitem__(self: _MST, s: slice) -> _MST: ... + def __getitem__(self: Self, s: slice) -> Self: ... def __setitem__(self, index: int | slice, sub: Any) -> None: ... def __delitem__(self, index: int | slice) -> None: ... def immutable(self) -> UserString: ... - def __iadd__(self: _MST, other: Any) -> _MST: ... + def __iadd__(self: Self, other: Any) -> Self: ... def __imul__(self, n: int) -> _MST: ... def insert(self, index: int, value: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/__builtin__.pyi b/mypy/typeshed/stdlib/@python2/__builtin__.pyi index fad8b2b4e7d8..d5e1c2e5e53b 100644 --- a/mypy/typeshed/stdlib/@python2/__builtin__.pyi +++ b/mypy/typeshed/stdlib/@python2/__builtin__.pyi @@ -1,7 +1,7 @@ # True and False are deliberately omitted because they are keywords in # Python 3, and stub files conform to Python 3 syntax. -from _typeshed import ReadableBuffer, SupportsKeysAndGetItem, SupportsWrite +from _typeshed import ReadableBuffer, Self, SupportsKeysAndGetItem, SupportsWrite from abc import ABCMeta from ast import mod from types import CodeType @@ -13,14 +13,11 @@ from typing import ( ByteString, Callable, Container, - Dict, - FrozenSet, Generic, ItemsView, Iterable, Iterator, KeysView, - List, Mapping, MutableMapping, MutableSequence, @@ -29,15 +26,12 @@ from typing import ( Protocol, Reversible, Sequence, - Set, Sized, SupportsAbs, SupportsComplex, SupportsFloat, SupportsInt, Text, - Tuple, - Type, TypeVar, ValuesView, overload, @@ -60,70 +54,68 @@ _T2 = TypeVar("_T2") _T3 = TypeVar("_T3") _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") -_TT = TypeVar("_TT", bound="type") -_TBE = TypeVar("_TBE", bound="BaseException") +_TT = TypeVar("_TT", bound=type) class object: __doc__: str | None - __dict__: Dict[str, Any] - __slots__: Text | Iterable[Text] + __dict__: dict[str, Any] __module__: str @property - def __class__(self: _T) -> Type[_T]: ... + def __class__(self: _T) -> type[_T]: ... @__class__.setter - def __class__(self, __type: Type[object]) -> None: ... # noqa: F811 + def __class__(self, __type: type[object]) -> None: ... # noqa: F811 def __init__(self) -> None: ... def __new__(cls) -> Any: ... 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 __str__(self) -> str: ... # noqa Y029 + def __repr__(self) -> str: ... # noqa Y029 def __hash__(self) -> int: ... 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_ex__(self, protocol: int) -> str | Tuple[Any, ...]: ... + def __reduce__(self) -> str | tuple[Any, ...]: ... + def __reduce_ex__(self, protocol: int) -> str | tuple[Any, ...]: ... class staticmethod(object): # Special, only valid as a decorator. __func__: Callable[..., Any] def __init__(self, f: Callable[..., Any]) -> None: ... - def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, obj: _T, type: Type[_T] | None = ...) -> Callable[..., Any]: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... + def __get__(self, obj: _T, type: type[_T] | None = ...) -> Callable[..., Any]: ... class classmethod(object): # Special, only valid as a decorator. __func__: Callable[..., Any] def __init__(self, f: Callable[..., Any]) -> None: ... - def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, obj: _T, type: Type[_T] | None = ...) -> Callable[..., Any]: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... + def __get__(self, obj: _T, type: type[_T] | None = ...) -> Callable[..., Any]: ... class type(object): __base__: type - __bases__: Tuple[type, ...] + __bases__: tuple[type, ...] __basicsize__: int - __dict__: Dict[str, Any] + __dict__: dict[str, Any] __dictoffset__: int __flags__: int __itemsize__: int __module__: str - __mro__: Tuple[type, ...] + __mro__: tuple[type, ...] __name__: str __weakrefoffset__: int @overload def __init__(self, o: object) -> None: ... @overload - def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: ... + def __init__(self, name: str, bases: tuple[type, ...], dict: dict[str, Any]) -> None: ... @overload def __new__(cls, o: object) -> type: ... @overload - def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... + 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]: ... + def __subclasses__(self: _TT) -> list[_TT]: ... # 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 mro(self) -> list[type]: ... def __instancecheck__(self, instance: Any) -> bool: ... def __subclasscheck__(self, subclass: type) -> bool: ... @@ -135,9 +127,9 @@ class super(object): class int: @overload - def __new__(cls: Type[_T], x: Text | bytes | SupportsInt | _SupportsIndex | _SupportsTrunc = ...) -> _T: ... + def __new__(cls: type[Self], x: Text | bytes | SupportsInt | _SupportsIndex | _SupportsTrunc = ...) -> Self: ... @overload - def __new__(cls: Type[_T], x: Text | bytes | bytearray, base: int) -> _T: ... + def __new__(cls: type[Self], x: Text | bytes | bytearray, base: int) -> Self: ... @property def real(self) -> int: ... @property @@ -155,7 +147,7 @@ class int: def __div__(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 __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: ... @@ -163,7 +155,7 @@ class int: def __rdiv__(self, x: int) -> int: ... def __rtruediv__(self, x: int) -> float: ... def __rmod__(self, x: int) -> int: ... - def __rdivmod__(self, x: int) -> Tuple[int, int]: ... + def __rdivmod__(self, x: int) -> tuple[int, int]: ... @overload def __pow__(self, __x: Literal[2], __modulo: int | None = ...) -> int: ... @overload @@ -183,14 +175,13 @@ class int: def __pos__(self) -> int: ... def __invert__(self) -> int: ... def __trunc__(self) -> int: ... - def __getnewargs__(self) -> Tuple[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 __str__(self) -> str: ... def __float__(self) -> float: ... def __int__(self) -> int: ... def __abs__(self) -> int: ... @@ -199,8 +190,8 @@ class int: def __index__(self) -> int: ... class float: - def __new__(cls: Type[_T], x: SupportsFloat | _SupportsIndex | Text | bytes | bytearray = ...) -> _T: ... - def as_integer_ratio(self) -> Tuple[int, int]: ... + def __new__(cls: type[Self], x: SupportsFloat | _SupportsIndex | Text | bytes | bytearray = ...) -> Self: ... + def as_integer_ratio(self) -> tuple[int, int]: ... def hex(self) -> str: ... def is_integer(self) -> bool: ... @classmethod @@ -217,7 +208,7 @@ class float: def __div__(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 __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 @@ -228,9 +219,9 @@ class float: def __rdiv__(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 __rdivmod__(self, x: float) -> tuple[float, float]: ... def __rpow__(self, x: float, mod: None = ...) -> float: ... - def __getnewargs__(self) -> Tuple[float]: ... + def __getnewargs__(self) -> tuple[float]: ... def __trunc__(self) -> int: ... def __eq__(self, x: object) -> bool: ... def __ne__(self, x: object) -> bool: ... @@ -240,7 +231,6 @@ class float: def __ge__(self, x: float) -> bool: ... def __neg__(self) -> float: ... def __pos__(self) -> float: ... - def __str__(self) -> str: ... def __int__(self) -> int: ... def __float__(self) -> float: ... def __abs__(self) -> float: ... @@ -249,9 +239,9 @@ class float: class complex: @overload - def __new__(cls: Type[_T], real: float = ..., imag: float = ...) -> _T: ... + def __new__(cls: type[Self], real: float = ..., imag: float = ...) -> Self: ... @overload - def __new__(cls: Type[_T], real: str | SupportsComplex | _SupportsIndex) -> _T: ... + def __new__(cls: type[Self], real: str | SupportsComplex | _SupportsIndex) -> Self: ... @property def real(self) -> float: ... @property @@ -273,7 +263,6 @@ class complex: def __ne__(self, x: object) -> bool: ... def __neg__(self) -> complex: ... def __pos__(self) -> complex: ... - def __str__(self) -> str: ... def __complex__(self) -> complex: ... def __abs__(self) -> float: ... def __hash__(self) -> int: ... @@ -293,7 +282,7 @@ class unicode(basestring, Sequence[unicode]): def count(self, x: unicode) -> int: ... def decode(self, encoding: unicode = ..., errors: unicode = ...) -> unicode: ... def encode(self, encoding: unicode = ..., errors: unicode = ...) -> str: ... - def endswith(self, __suffix: unicode | Tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def endswith(self, __suffix: unicode | tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def expandtabs(self, tabsize: int = ...) -> unicode: ... def find(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... def format(self, *args: object, **kwargs: object) -> unicode: ... @@ -313,21 +302,21 @@ class unicode(basestring, Sequence[unicode]): def ljust(self, width: int, fillchar: unicode = ...) -> unicode: ... def lower(self) -> unicode: ... def lstrip(self, chars: unicode = ...) -> unicode: ... - def partition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def partition(self, sep: unicode) -> tuple[unicode, unicode, unicode]: ... def replace(self, old: unicode, new: unicode, count: int = ...) -> unicode: ... def rfind(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... def rindex(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... def rjust(self, width: int, fillchar: unicode = ...) -> unicode: ... - def rpartition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - def rsplit(self, sep: unicode | None = ..., maxsplit: int = ...) -> List[unicode]: ... + def rpartition(self, sep: unicode) -> tuple[unicode, unicode, unicode]: ... + def rsplit(self, sep: unicode | None = ..., maxsplit: int = ...) -> list[unicode]: ... def rstrip(self, chars: unicode = ...) -> unicode: ... - def split(self, sep: unicode | None = ..., maxsplit: int = ...) -> List[unicode]: ... - def splitlines(self, keepends: bool = ...) -> List[unicode]: ... - def startswith(self, __prefix: unicode | Tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def split(self, sep: unicode | None = ..., maxsplit: int = ...) -> list[unicode]: ... + def splitlines(self, keepends: bool = ...) -> list[unicode]: ... + def startswith(self, __prefix: unicode | tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def strip(self, chars: unicode = ...) -> unicode: ... def swapcase(self) -> unicode: ... def title(self) -> unicode: ... - def translate(self, table: Dict[int, Any] | unicode) -> unicode: ... + def translate(self, table: dict[int, Any] | unicode) -> unicode: ... def upper(self) -> unicode: ... def zfill(self, width: int) -> unicode: ... @overload @@ -349,12 +338,10 @@ class unicode(basestring, Sequence[unicode]): # The argument type is incompatible with Sequence def __contains__(self, s: unicode | bytes) -> bool: ... # type: ignore def __iter__(self) -> Iterator[unicode]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... def __int__(self) -> int: ... def __float__(self) -> float: ... def __hash__(self) -> int: ... - def __getnewargs__(self) -> Tuple[unicode]: ... + def __getnewargs__(self) -> tuple[unicode]: ... class _FormatMapMapping(Protocol): def __getitem__(self, __key: str) -> Any: ... @@ -366,7 +353,7 @@ class str(Sequence[str], basestring): def count(self, x: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... - def endswith(self, __suffix: Text | Tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def endswith(self, __suffix: Text | tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def expandtabs(self, tabsize: int = ...) -> str: ... def find(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... def format(self, *args: object, **kwargs: object) -> str: ... @@ -387,35 +374,35 @@ class str(Sequence[str], basestring): @overload def lstrip(self, __chars: unicode) -> unicode: ... @overload - def partition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + def partition(self, __sep: bytearray) -> tuple[str, bytearray, str]: ... @overload - def partition(self, __sep: str) -> Tuple[str, str, str]: ... + def partition(self, __sep: str) -> tuple[str, str, str]: ... @overload - def partition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def partition(self, __sep: unicode) -> tuple[unicode, unicode, unicode]: ... def replace(self, __old: AnyStr, __new: AnyStr, __count: int = ...) -> AnyStr: ... def rfind(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... def rindex(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... def rjust(self, __width: int, __fillchar: str = ...) -> str: ... @overload - def rpartition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + def rpartition(self, __sep: bytearray) -> tuple[str, bytearray, str]: ... @overload - def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... + def rpartition(self, __sep: str) -> tuple[str, str, str]: ... @overload - def rpartition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def rpartition(self, __sep: unicode) -> tuple[unicode, unicode, unicode]: ... @overload - def rsplit(self, sep: str | None = ..., maxsplit: int = ...) -> List[str]: ... + def rsplit(self, sep: str | None = ..., maxsplit: int = ...) -> list[str]: ... @overload - def rsplit(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + def rsplit(self, sep: unicode, maxsplit: int = ...) -> list[unicode]: ... @overload def rstrip(self, __chars: str = ...) -> str: ... @overload def rstrip(self, __chars: unicode) -> unicode: ... @overload - def split(self, sep: str | None = ..., maxsplit: int = ...) -> List[str]: ... + def split(self, sep: str | None = ..., maxsplit: int = ...) -> list[str]: ... @overload - def split(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... - def splitlines(self, keepends: bool = ...) -> List[str]: ... - def startswith(self, __prefix: Text | Tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def split(self, sep: unicode, maxsplit: int = ...) -> list[unicode]: ... + def splitlines(self, keepends: bool = ...) -> list[str]: ... + def startswith(self, __prefix: Text | tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... @overload def strip(self, __chars: str = ...) -> str: ... @overload @@ -440,10 +427,8 @@ class str(Sequence[str], basestring): def __mod__(self, x: Any) -> str: ... def __mul__(self, n: int) -> str: ... def __ne__(self, x: object) -> bool: ... - def __repr__(self) -> str: ... def __rmul__(self, n: int) -> str: ... - def __str__(self) -> str: ... - def __getnewargs__(self) -> Tuple[str]: ... + def __getnewargs__(self) -> tuple[str]: ... def __getslice__(self, start: int, stop: int) -> str: ... def __float__(self) -> float: ... def __int__(self) -> int: ... @@ -465,7 +450,7 @@ class bytearray(MutableSequence[int], ByteString): def center(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... def count(self, __sub: str) -> int: ... def decode(self, encoding: Text = ..., errors: Text = ...) -> str: ... - def endswith(self, __suffix: bytes | Tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def endswith(self, __suffix: bytes | tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def expandtabs(self, tabsize: int = ...) -> bytearray: ... def extend(self, iterable: str | Iterable[int]) -> None: ... def find(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... @@ -482,17 +467,17 @@ class bytearray(MutableSequence[int], ByteString): def ljust(self, __width: int, __fillchar: str = ...) -> bytearray: ... def lower(self) -> bytearray: ... def lstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def partition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + def partition(self, __sep: bytes) -> tuple[bytearray, bytearray, bytearray]: ... def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytearray: ... def rfind(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... def rindex(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... def rjust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... - def rpartition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... - def rsplit(self, sep: bytes | None = ..., maxsplit: int = ...) -> List[bytearray]: ... + def rpartition(self, __sep: bytes) -> tuple[bytearray, bytearray, bytearray]: ... + def rsplit(self, sep: bytes | None = ..., maxsplit: int = ...) -> list[bytearray]: ... def rstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def split(self, sep: bytes | None = ..., maxsplit: int = ...) -> List[bytearray]: ... - def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... - def startswith(self, __prefix: bytes | Tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def split(self, sep: bytes | None = ..., maxsplit: int = ...) -> list[bytearray]: ... + def splitlines(self, keepends: bool = ...) -> list[bytearray]: ... + def startswith(self, __prefix: bytes | tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def strip(self, __bytes: bytes | None = ...) -> bytearray: ... def swapcase(self) -> bytearray: ... def title(self) -> bytearray: ... @@ -503,8 +488,6 @@ class bytearray(MutableSequence[int], ByteString): def fromhex(cls, __string: str) -> bytearray: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... def __int__(self) -> int: ... def __float__(self) -> float: ... __hash__: None # type: ignore @@ -534,9 +517,9 @@ class bytearray(MutableSequence[int], ByteString): class memoryview(Sized, Container[str]): format: str itemsize: int - shape: Tuple[int, ...] | None - strides: Tuple[int, ...] | None - suboffsets: Tuple[int, ...] | None + shape: tuple[int, ...] | None + strides: tuple[int, ...] | None + suboffsets: tuple[int, ...] | None readonly: bool ndim: int def __init__(self, obj: ReadableBuffer) -> None: ... @@ -552,11 +535,11 @@ class memoryview(Sized, Container[str]): @overload def __setitem__(self, i: int, o: int) -> None: ... def tobytes(self) -> bytes: ... - def tolist(self) -> List[int]: ... + def tolist(self) -> list[int]: ... @final class bool(int): - def __new__(cls: Type[_T], __o: object = ...) -> _T: ... + def __new__(cls: type[Self], __o: object = ...) -> Self: ... @overload def __and__(self, x: bool) -> bool: ... @overload @@ -581,7 +564,7 @@ class bool(int): def __rxor__(self, x: bool) -> bool: ... @overload def __rxor__(self, x: int) -> int: ... - def __getnewargs__(self) -> Tuple[int]: ... + def __getnewargs__(self) -> tuple[int]: ... class slice(object): start: Any @@ -592,27 +575,27 @@ class slice(object): @overload def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... __hash__: None # type: ignore - def indices(self, len: int) -> Tuple[int, int, int]: ... + def indices(self, len: int) -> 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[Self], iterable: Iterable[_T_co] = ...) -> Self: ... def __len__(self) -> int: ... def __contains__(self, x: object) -> bool: ... @overload 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[Any, ...]) -> Tuple[Any, ...]: ... - def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... - def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... + def __add__(self, x: tuple[Any, ...]) -> tuple[Any, ...]: ... + def __mul__(self, n: int) -> tuple[_T_co, ...]: ... + def __rmul__(self, n: int) -> tuple[_T_co, ...]: ... def count(self, __value: Any) -> int: ... def index(self, __value: Any) -> int: ... @@ -638,30 +621,29 @@ class list(MutableSequence[_T], Generic[_T]): def sort(self, cmp: Callable[[_T, _T], Any] = ..., key: Callable[[_T], Any] = ..., reverse: bool = ...) -> None: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... __hash__: None # type: ignore @overload def __getitem__(self, i: int) -> _T: ... @overload - def __getitem__(self, s: slice) -> List[_T]: ... + def __getitem__(self, s: slice) -> list[_T]: ... @overload def __setitem__(self, i: int, o: _T) -> None: ... @overload def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... def __delitem__(self, i: int | slice) -> None: ... - def __getslice__(self, start: int, stop: int) -> List[_T]: ... + def __getslice__(self, start: int, stop: int) -> list[_T]: ... def __setslice__(self, start: int, stop: int, o: Sequence[_T]) -> None: ... def __delslice__(self, start: int, stop: int) -> None: ... - def __add__(self, x: List[_T]) -> List[_T]: ... - def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... - def __mul__(self, n: int) -> List[_T]: ... - def __rmul__(self, n: int) -> List[_T]: ... + def __add__(self, x: list[_T]) -> list[_T]: ... + def __iadd__(self: Self, x: Iterable[_T]) -> Self: ... + def __mul__(self, n: int) -> list[_T]: ... + def __rmul__(self, n: int) -> list[_T]: ... 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: ... class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): # NOTE: Keyword arguments are special. If they are used, _KT must include @@ -671,76 +653,74 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @overload def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... @overload - def __init__(self, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... + def __init__(self, iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... def has_key(self, k: _KT) -> bool: ... def clear(self) -> None: ... - def copy(self) -> Dict[_KT, _VT]: ... - def popitem(self) -> Tuple[_KT, _VT]: ... + def copy(self) -> dict[_KT, _VT]: ... + def popitem(self) -> tuple[_KT, _VT]: ... def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ... @overload def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... @overload - def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def update(self, __m: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... @overload def update(self, **kwargs: _VT) -> None: ... def iterkeys(self) -> Iterator[_KT]: ... def itervalues(self) -> Iterator[_VT]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def iteritems(self) -> Iterator[tuple[_KT, _VT]]: ... def viewkeys(self) -> KeysView[_KT]: ... def viewvalues(self) -> ValuesView[_VT]: ... def viewitems(self) -> ItemsView[_KT, _VT]: ... @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T]) -> Dict[_T, Any]: ... + def fromkeys(cls, __iterable: Iterable[_T]) -> dict[_T, Any]: ... @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> Dict[_T, _S]: ... + 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 __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... __hash__: None # type: ignore class set(MutableSet[_T], Generic[_T]): def __init__(self, iterable: Iterable[_T] = ...) -> None: ... def add(self, element: _T) -> None: ... def clear(self) -> None: ... - def copy(self) -> Set[_T]: ... - def difference(self, *s: Iterable[Any]) -> Set[_T]: ... + def copy(self) -> set[_T]: ... + def difference(self, *s: Iterable[Any]) -> set[_T]: ... def difference_update(self, *s: Iterable[Any]) -> None: ... def discard(self, element: _T) -> None: ... - def intersection(self, *s: Iterable[Any]) -> Set[_T]: ... + def 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 pop(self) -> _T: ... def remove(self, element: _T) -> None: ... - def symmetric_difference(self, s: Iterable[_T]) -> Set[_T]: ... + 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 union(self, *s: Iterable[_T]) -> set[_T]: ... def update(self, *s: Iterable[_T]) -> None: ... def __len__(self) -> int: ... 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 __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]: ... @overload - def __sub__(self: Set[str], s: AbstractSet[Text | None]) -> Set[_T]: ... + def __sub__(self: set[str], s: AbstractSet[Text | None]) -> set[_T]: ... @overload - def __sub__(self, s: AbstractSet[_T | None]) -> Set[_T]: ... + def __sub__(self, s: AbstractSet[_T | None]) -> set[_T]: ... @overload # type: ignore - def __isub__(self: Set[str], s: AbstractSet[Text | None]) -> Set[_T]: ... + def __isub__(self: set[str], s: AbstractSet[Text | None]) -> set[_T]: ... @overload - 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 __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: ... @@ -749,31 +729,30 @@ class set(MutableSet[_T], Generic[_T]): class frozenset(AbstractSet[_T_co], Generic[_T_co]): def __init__(self, iterable: Iterable[_T_co] = ...) -> None: ... - def copy(self) -> FrozenSet[_T_co]: ... - def difference(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... - def intersection(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... + def 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 symmetric_difference(self, s: Iterable[_T_co]) -> frozenset[_T_co]: ... + def union(self, *s: Iterable[_T_co]) -> frozenset[_T_co]: ... def __len__(self) -> int: ... 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 __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: ... -class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): +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]: ... + def __iter__(self) -> Iterator[tuple[int, _T]]: ... + def next(self) -> tuple[int, _T]: ... class xrange(Sized, Iterable[int], Reversible[int]): @overload @@ -823,29 +802,29 @@ def cmp(__x: Any, __y: Any) -> int: ... _N1 = TypeVar("_N1", bool, int, float, complex) -def coerce(__x: _N1, __y: _N1) -> Tuple[_N1, _N1]: ... +def coerce(__x: _N1, __y: _N1) -> tuple[_N1, _N1]: ... def compile(source: Text | mod, filename: Text, mode: Text, flags: int = ..., dont_inherit: int = ...) -> Any: ... def delattr(__obj: Any, __name: Text) -> None: ... -def dir(__o: object = ...) -> List[str]: ... +def dir(__o: object = ...) -> list[str]: ... _N2 = TypeVar("_N2", int, float) -def divmod(__x: _N2, __y: _N2) -> Tuple[_N2, _N2]: ... +def divmod(__x: _N2, __y: _N2) -> tuple[_N2, _N2]: ... def eval( - __source: Text | bytes | CodeType, __globals: Dict[str, Any] | None = ..., __locals: Mapping[str, Any] | None = ... + __source: Text | bytes | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, Any] | None = ... ) -> Any: ... -def execfile(__filename: str, __globals: Dict[str, Any] | None = ..., __locals: Dict[str, Any] | None = ...) -> None: ... +def execfile(__filename: str, __globals: dict[str, Any] | None = ..., __locals: dict[str, Any] | None = ...) -> None: ... def exit(code: object = ...) -> NoReturn: ... @overload def filter(__function: Callable[[AnyStr], Any], __iterable: AnyStr) -> AnyStr: ... # type: ignore @overload -def filter(__function: None, __iterable: Tuple[_T | None, ...]) -> Tuple[_T, ...]: ... # type: ignore +def filter(__function: None, __iterable: tuple[_T | None, ...]) -> tuple[_T, ...]: ... # type: ignore @overload -def filter(__function: Callable[[_T], Any], __iterable: Tuple[_T, ...]) -> Tuple[_T, ...]: ... # type: ignore +def filter(__function: Callable[[_T], Any], __iterable: tuple[_T, ...]) -> tuple[_T, ...]: ... # type: ignore @overload -def filter(__function: None, __iterable: Iterable[_T | None]) -> List[_T]: ... +def filter(__function: None, __iterable: Iterable[_T | None]) -> list[_T]: ... @overload -def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> List[_T]: ... +def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> list[_T]: ... def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode @overload def getattr(__o: Any, name: Text) -> Any: ... @@ -863,7 +842,7 @@ def getattr(__o: object, name: str, __default: list[Any]) -> Any | list[Any]: .. def getattr(__o: object, name: str, __default: dict[Any, Any]) -> Any | dict[Any, Any]: ... @overload def getattr(__o: Any, name: Text, __default: _T) -> Any | _T: ... -def globals() -> Dict[str, Any]: ... +def globals() -> dict[str, Any]: ... def hasattr(__obj: Any, __name: Text) -> bool: ... def hash(__obj: object) -> int: ... def hex(__number: int | _SupportsIndex) -> str: ... @@ -876,20 +855,20 @@ def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... def iter(__function: Callable[[], _T | None], __sentinel: None) -> Iterator[_T]: ... @overload def iter(__function: Callable[[], _T], __sentinel: Any) -> Iterator[_T]: ... -def isinstance(__obj: object, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... -def issubclass(__cls: type, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... +def isinstance(__obj: object, __class_or_tuple: type | tuple[type | tuple[Any, ...], ...]) -> bool: ... +def issubclass(__cls: type, __class_or_tuple: type | tuple[type | tuple[Any, ...], ...]) -> bool: ... def len(__obj: Sized) -> int: ... -def locals() -> Dict[str, Any]: ... +def locals() -> dict[str, Any]: ... @overload -def map(__func: None, __iter1: Iterable[_T1]) -> List[_T1]: ... +def map(__func: None, __iter1: Iterable[_T1]) -> list[_T1]: ... @overload -def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... +def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> list[tuple[_T1, _T2]]: ... @overload -def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... +def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> list[tuple[_T1, _T2, _T3]]: ... @overload def map( __func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] -) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... +) -> list[tuple[_T1, _T2, _T3, _T4]]: ... @overload def map( __func: None, @@ -898,7 +877,7 @@ def map( __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5], -) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +) -> list[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def map( __func: None, @@ -909,15 +888,15 @@ def map( __iter5: Iterable[Any], __iter6: Iterable[Any], *iterables: Iterable[Any], -) -> List[Tuple[Any, ...]]: ... +) -> list[tuple[Any, ...]]: ... @overload -def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> List[_S]: ... +def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> list[_S]: ... @overload -def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[_S]: ... +def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> list[_S]: ... @overload def map( __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] -) -> List[_S]: ... +) -> list[_S]: ... @overload def map( __func: Callable[[_T1, _T2, _T3, _T4], _S], @@ -925,7 +904,7 @@ def map( __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], -) -> List[_S]: ... +) -> list[_S]: ... @overload def map( __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], @@ -934,7 +913,7 @@ def map( __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5], -) -> List[_S]: ... +) -> list[_S]: ... @overload def map( __func: Callable[..., _S], @@ -945,7 +924,7 @@ def map( __iter5: Iterable[Any], __iter6: Iterable[Any], *iterables: Iterable[Any], -) -> List[_S]: ... +) -> list[_S]: ... @overload def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... @overload @@ -985,7 +964,7 @@ def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E) -> _T_co: ... @overload def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M) -> _T_co: ... def quit(code: object = ...) -> NoReturn: ... -def range(__x: int, __y: int = ..., __step: int = ...) -> List[int]: ... # noqa: F811 +def range(__x: int, __y: int = ..., __step: int = ...) -> list[int]: ... # noqa: F811 def raw_input(__prompt: Any = ...) -> str: ... @overload def reduce(__function: Callable[[_T, _S], _T], __iterable: Iterable[_S], __initializer: _T) -> _T: ... @@ -1008,27 +987,27 @@ def round(number: SupportsFloat, ndigits: int) -> float: ... def setattr(__obj: Any, __name: Text, __value: Any) -> None: ... def sorted( __iterable: Iterable[_T], *, cmp: Callable[[_T, _T], int] = ..., key: Callable[[_T], Any] | None = ..., reverse: bool = ... -) -> List[_T]: ... +) -> list[_T]: ... @overload def sum(__iterable: Iterable[_T]) -> _T | int: ... @overload def sum(__iterable: Iterable[_T], __start: _S) -> _T | _S: ... def unichr(__i: int) -> unicode: ... -def vars(__object: Any = ...) -> Dict[str, Any]: ... +def vars(__object: Any = ...) -> dict[str, Any]: ... @overload -def zip(__iter1: Iterable[_T1]) -> List[Tuple[_T1]]: ... +def zip(__iter1: Iterable[_T1]) -> list[tuple[_T1]]: ... @overload -def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... +def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> list[tuple[_T1, _T2]]: ... @overload -def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... +def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> list[tuple[_T1, _T2, _T3]]: ... @overload def zip( __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] -) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... +) -> list[tuple[_T1, _T2, _T3, _T4]]: ... @overload def zip( __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5] -) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +) -> list[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def zip( __iter1: Iterable[Any], @@ -1038,7 +1017,7 @@ def zip( __iter5: Iterable[Any], __iter6: Iterable[Any], *iterables: Iterable[Any], -) -> List[Tuple[Any, ...]]: ... +) -> list[tuple[Any, ...]]: ... def __import__( name: Text, globals: Mapping[str, Any] | None = ..., @@ -1066,13 +1045,11 @@ class buffer(Sized): def __mul__(self, x: int) -> str: ... class BaseException(object): - args: Tuple[Any, ...] + args: tuple[Any, ...] message: Any def __init__(self, *args: object) -> None: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... def __getitem__(self, i: int) -> Any: ... - def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ... + def __getslice__(self, start: int, stop: int) -> tuple[Any, ...]: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ... @@ -1181,7 +1158,7 @@ class file(BinaryIO): def seek(self, offset: int, whence: int = ...) -> int: ... def tell(self) -> int: ... def readline(self, limit: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... + def readlines(self, hint: int = ...) -> list[str]: ... def write(self, data: str) -> int: ... def writelines(self, data: Iterable[str]) -> None: ... def truncate(self, pos: int | None = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/__future__.pyi b/mypy/typeshed/stdlib/@python2/__future__.pyi index 8f5ff06ac080..df05b0d7c2de 100644 --- a/mypy/typeshed/stdlib/@python2/__future__.pyi +++ b/mypy/typeshed/stdlib/@python2/__future__.pyi @@ -1,5 +1,4 @@ import sys -from typing import List class _Feature: def __init__(self, optionalRelease: sys._version_info, mandatoryRelease: sys._version_info, compiler_flag: int) -> None: ... @@ -14,4 +13,4 @@ nested_scopes: _Feature print_function: _Feature unicode_literals: _Feature with_statement: _Feature -all_feature_names: List[str] # undocumented +all_feature_names: list[str] # undocumented diff --git a/mypy/typeshed/stdlib/@python2/_ast.pyi b/mypy/typeshed/stdlib/@python2/_ast.pyi index 05cbc70c41d2..c81dc09abb57 100644 --- a/mypy/typeshed/stdlib/@python2/_ast.pyi +++ b/mypy/typeshed/stdlib/@python2/_ast.pyi @@ -1,27 +1,25 @@ -import typing - __version__: str PyCF_ONLY_AST: int _identifier = str class AST: - _attributes: typing.Tuple[str, ...] - _fields: typing.Tuple[str, ...] + _attributes: tuple[str, ...] + _fields: tuple[str, ...] def __init__(self, *args, **kwargs) -> None: ... class mod(AST): ... class Module(mod): - body: typing.List[stmt] + body: list[stmt] class Interactive(mod): - body: typing.List[stmt] + body: list[stmt] class Expression(mod): body: expr class Suite(mod): - body: typing.List[stmt] + body: list[stmt] class stmt(AST): lineno: int @@ -30,23 +28,23 @@ class stmt(AST): class FunctionDef(stmt): name: _identifier args: arguments - body: typing.List[stmt] - decorator_list: typing.List[expr] + body: list[stmt] + decorator_list: list[expr] class ClassDef(stmt): name: _identifier - bases: typing.List[expr] - body: typing.List[stmt] - decorator_list: typing.List[expr] + bases: list[expr] + body: list[stmt] + decorator_list: list[expr] class Return(stmt): value: expr | None class Delete(stmt): - targets: typing.List[expr] + targets: list[expr] class Assign(stmt): - targets: typing.List[expr] + targets: list[expr] value: expr class AugAssign(stmt): @@ -56,29 +54,29 @@ class AugAssign(stmt): class Print(stmt): dest: expr | None - values: typing.List[expr] + values: list[expr] nl: bool class For(stmt): target: expr iter: expr - body: typing.List[stmt] - orelse: typing.List[stmt] + body: list[stmt] + orelse: list[stmt] class While(stmt): test: expr - body: typing.List[stmt] - orelse: typing.List[stmt] + body: list[stmt] + orelse: list[stmt] class If(stmt): test: expr - body: typing.List[stmt] - orelse: typing.List[stmt] + body: list[stmt] + orelse: list[stmt] class With(stmt): context_expr: expr optional_vars: expr | None - body: typing.List[stmt] + body: list[stmt] class Raise(stmt): type: expr | None @@ -86,24 +84,24 @@ class Raise(stmt): tback: expr | None class TryExcept(stmt): - body: typing.List[stmt] - handlers: typing.List[ExceptHandler] - orelse: typing.List[stmt] + body: list[stmt] + handlers: list[ExceptHandler] + orelse: list[stmt] class TryFinally(stmt): - body: typing.List[stmt] - finalbody: typing.List[stmt] + body: list[stmt] + finalbody: list[stmt] class Assert(stmt): test: expr msg: expr | None class Import(stmt): - names: typing.List[alias] + names: list[alias] class ImportFrom(stmt): module: _identifier | None - names: typing.List[alias] + names: list[alias] level: int | None class Exec(stmt): @@ -112,7 +110,7 @@ class Exec(stmt): locals: expr | None class Global(stmt): - names: typing.List[_identifier] + names: list[_identifier] class Expr(stmt): value: expr @@ -130,7 +128,7 @@ class Slice(slice): step: expr | None class ExtSlice(slice): - dims: typing.List[slice] + dims: list[slice] class Index(slice): value: expr @@ -143,7 +141,7 @@ class expr(AST): class BoolOp(expr): op: boolop - values: typing.List[expr] + values: list[expr] class BinOp(expr): left: expr @@ -164,41 +162,41 @@ class IfExp(expr): orelse: expr class Dict(expr): - keys: typing.List[expr] - values: typing.List[expr] + keys: list[expr] + values: list[expr] class Set(expr): - elts: typing.List[expr] + elts: list[expr] class ListComp(expr): elt: expr - generators: typing.List[comprehension] + generators: list[comprehension] class SetComp(expr): elt: expr - generators: typing.List[comprehension] + generators: list[comprehension] class DictComp(expr): key: expr value: expr - generators: typing.List[comprehension] + generators: list[comprehension] class GeneratorExp(expr): elt: expr - generators: typing.List[comprehension] + generators: list[comprehension] class Yield(expr): value: expr | None class Compare(expr): left: expr - ops: typing.List[cmpop] - comparators: typing.List[expr] + ops: list[cmpop] + comparators: list[expr] class Call(expr): func: expr - args: typing.List[expr] - keywords: typing.List[keyword] + args: list[expr] + keywords: list[keyword] starargs: expr | None kwargs: expr | None @@ -226,11 +224,11 @@ class Name(expr): ctx: expr_context class List(expr): - elts: typing.List[expr] + elts: list[expr] ctx: expr_context class Tuple(expr): - elts: typing.List[expr] + elts: list[expr] ctx: expr_context class expr_context(AST): ... @@ -276,22 +274,22 @@ class NotIn(cmpop): ... class comprehension(AST): target: expr iter: expr - ifs: typing.List[expr] + ifs: list[expr] class excepthandler(AST): ... class ExceptHandler(excepthandler): type: expr | None name: expr | None - body: typing.List[stmt] + body: list[stmt] lineno: int col_offset: int class arguments(AST): - args: typing.List[expr] + args: list[expr] vararg: _identifier | None kwarg: _identifier | None - defaults: typing.List[expr] + defaults: list[expr] class keyword(AST): arg: _identifier diff --git a/mypy/typeshed/stdlib/@python2/_codecs.pyi b/mypy/typeshed/stdlib/@python2/_codecs.pyi index 83601f6621bb..fa6922207c25 100644 --- a/mypy/typeshed/stdlib/@python2/_codecs.pyi +++ b/mypy/typeshed/stdlib/@python2/_codecs.pyi @@ -1,9 +1,9 @@ import codecs import sys -from typing import Any, Callable, Dict, Text, Tuple, Union +from typing import Any, Callable, Text, Union # For convenience: -_Handler = Callable[[Exception], Tuple[Text, int]] +_Handler = Callable[[Exception], tuple[Text, int]] _String = Union[bytes, str] _Errors = Union[str, Text, None] _Decodable = Union[bytes, Text] @@ -13,7 +13,7 @@ _Encodable = Union[bytes, Text] class _EncodingMap(object): def size(self) -> int: ... -_MapT = Union[Dict[int, int], _EncodingMap] +_MapT = Union[dict[int, int], _EncodingMap] def register(__search_function: Callable[[str], Any]) -> None: ... def register_error(__errors: str | Text, __handler: _Handler) -> None: ... @@ -22,45 +22,45 @@ def lookup_error(__name: str | Text) -> _Handler: ... def decode(obj: Any, encoding: str | Text = ..., errors: _Errors = ...) -> Any: ... def encode(obj: Any, encoding: str | Text = ..., errors: _Errors = ...) -> Any: ... def charmap_build(__map: Text) -> _MapT: ... -def ascii_decode(__data: _Decodable, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def ascii_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def charbuffer_encode(__data: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def charmap_decode(__data: _Decodable, __errors: _Errors = ..., __mapping: _MapT | None = ...) -> Tuple[Text, int]: ... -def charmap_encode(__str: _Encodable, __errors: _Errors = ..., __mapping: _MapT | None = ...) -> Tuple[bytes, int]: ... -def escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[str, int]: ... -def escape_encode(__data: bytes, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def latin_1_decode(__data: _Decodable, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def latin_1_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def raw_unicode_escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def raw_unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def readbuffer_encode(__data: _String, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def unicode_escape_decode(__data: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def unicode_internal_decode(__obj: _String, __errors: _Errors = ...) -> Tuple[Text, int]: ... -def unicode_internal_encode(__obj: _String, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_16_be_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_16_be_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_16_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_16_encode(__str: _Encodable, __errors: _Errors = ..., __byteorder: int = ...) -> Tuple[bytes, int]: ... +def ascii_decode(__data: _Decodable, __errors: _Errors = ...) -> tuple[Text, int]: ... +def ascii_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def charbuffer_encode(__data: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def charmap_decode(__data: _Decodable, __errors: _Errors = ..., __mapping: _MapT | None = ...) -> tuple[Text, int]: ... +def charmap_encode(__str: _Encodable, __errors: _Errors = ..., __mapping: _MapT | None = ...) -> tuple[bytes, int]: ... +def escape_decode(__data: _String, __errors: _Errors = ...) -> tuple[str, int]: ... +def escape_encode(__data: bytes, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def latin_1_decode(__data: _Decodable, __errors: _Errors = ...) -> tuple[Text, int]: ... +def latin_1_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def raw_unicode_escape_decode(__data: _String, __errors: _Errors = ...) -> tuple[Text, int]: ... +def raw_unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def readbuffer_encode(__data: _String, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def unicode_escape_decode(__data: _String, __errors: _Errors = ...) -> tuple[Text, int]: ... +def unicode_escape_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def unicode_internal_decode(__obj: _String, __errors: _Errors = ...) -> tuple[Text, int]: ... +def unicode_internal_encode(__obj: _String, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def utf_16_be_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> tuple[Text, int]: ... +def utf_16_be_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def utf_16_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> tuple[Text, int]: ... +def utf_16_encode(__str: _Encodable, __errors: _Errors = ..., __byteorder: int = ...) -> tuple[bytes, int]: ... def utf_16_ex_decode( __data: _Decodable, __errors: _Errors = ..., __byteorder: int = ..., __final: int = ... -) -> Tuple[Text, int, int]: ... -def utf_16_le_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_16_le_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_32_be_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_32_be_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_32_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_32_encode(__str: _Encodable, __errors: _Errors = ..., __byteorder: int = ...) -> Tuple[bytes, int]: ... +) -> tuple[Text, int, int]: ... +def utf_16_le_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> tuple[Text, int]: ... +def utf_16_le_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def utf_32_be_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> tuple[Text, int]: ... +def utf_32_be_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def utf_32_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> tuple[Text, int]: ... +def utf_32_encode(__str: _Encodable, __errors: _Errors = ..., __byteorder: int = ...) -> tuple[bytes, int]: ... def utf_32_ex_decode( __data: _Decodable, __errors: _Errors = ..., __byteorder: int = ..., __final: int = ... -) -> Tuple[Text, int, int]: ... -def utf_32_le_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_32_le_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_7_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_7_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... -def utf_8_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... -def utf_8_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... +) -> tuple[Text, int, int]: ... +def utf_32_le_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> tuple[Text, int]: ... +def utf_32_le_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def utf_7_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> tuple[Text, int]: ... +def utf_7_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... +def utf_8_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> tuple[Text, int]: ... +def utf_8_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... if sys.platform == "win32": - def mbcs_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> Tuple[Text, int]: ... - def mbcs_encode(__str: _Encodable, __errors: _Errors = ...) -> Tuple[bytes, int]: ... + def mbcs_decode(__data: _Decodable, __errors: _Errors = ..., __final: int = ...) -> tuple[Text, int]: ... + def mbcs_encode(__str: _Encodable, __errors: _Errors = ...) -> tuple[bytes, int]: ... diff --git a/mypy/typeshed/stdlib/@python2/_collections.pyi b/mypy/typeshed/stdlib/@python2/_collections.pyi index 22ada07d0f24..98509176d4e6 100644 --- a/mypy/typeshed/stdlib/@python2/_collections.pyi +++ b/mypy/typeshed/stdlib/@python2/_collections.pyi @@ -1,16 +1,17 @@ -from typing import Any, Callable, Dict, Generic, Iterator, TypeVar +from _typeshed import Self +from typing import Any, Callable, Generic, Iterator, TypeVar _K = TypeVar("_K") _V = TypeVar("_V") _T = TypeVar("_T") _T2 = TypeVar("_T2") -class defaultdict(Dict[_K, _V]): +class defaultdict(dict[_K, _V]): default_factory: None def __init__(self, __default_factory: Callable[[], _V] = ..., init: Any = ...) -> None: ... def __missing__(self, key: _K) -> _V: ... - def __copy__(self: _T) -> _T: ... - def copy(self: _T) -> _T: ... + def __copy__(self: Self) -> Self: ... + def copy(self: Self) -> Self: ... class deque(Generic[_T]): maxlen: int | None diff --git a/mypy/typeshed/stdlib/@python2/_csv.pyi b/mypy/typeshed/stdlib/@python2/_csv.pyi index ebe44bab67d9..e01ccc19cb19 100644 --- a/mypy/typeshed/stdlib/@python2/_csv.pyi +++ b/mypy/typeshed/stdlib/@python2/_csv.pyi @@ -1,4 +1,4 @@ -from typing import Any, Iterable, Iterator, List, Protocol, Sequence, Text, Type, Union +from typing import Any, Iterable, Iterator, Protocol, Sequence, Text, Union QUOTE_ALL: int QUOTE_MINIMAL: int @@ -18,12 +18,12 @@ class Dialect: strict: int def __init__(self) -> None: ... -_DialectLike = Union[str, Dialect, Type[Dialect]] +_DialectLike = Union[str, Dialect, type[Dialect]] -class _reader(Iterator[List[str]]): +class _reader(Iterator[list[str]]): dialect: Dialect line_num: int - def next(self) -> List[str]: ... + def next(self) -> list[str]: ... class _writer: dialect: Dialect @@ -38,5 +38,5 @@ def reader(csvfile: Iterable[Text], dialect: _DialectLike = ..., **fmtparams: An def register_dialect(name: str, dialect: Any = ..., **fmtparams: Any) -> None: ... def unregister_dialect(name: str) -> None: ... def get_dialect(name: str) -> Dialect: ... -def list_dialects() -> List[str]: ... +def list_dialects() -> list[str]: ... def field_size_limit(new_limit: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/_curses.pyi b/mypy/typeshed/stdlib/@python2/_curses.pyi index 32c1f761ac9e..4b2941e74753 100644 --- a/mypy/typeshed/stdlib/@python2/_curses.pyi +++ b/mypy/typeshed/stdlib/@python2/_curses.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, BinaryIO, Tuple, Union, overload +from typing import IO, Any, BinaryIO, Union, overload _chtype = Union[str, bytes, int] @@ -263,7 +263,7 @@ def baudrate() -> int: ... def beep() -> None: ... def can_change_color() -> bool: ... def cbreak(__flag: bool = ...) -> None: ... -def color_content(__color_number: int) -> Tuple[int, int, int]: ... +def color_content(__color_number: int) -> tuple[int, int, int]: ... # Changed in Python 3.8.8 and 3.9.2 def color_pair(__color_number: int) -> int: ... @@ -278,8 +278,8 @@ def erasechar() -> bytes: ... def filter() -> None: ... def flash() -> None: ... def flushinp() -> None: ... -def getmouse() -> Tuple[int, int, int, int, int]: ... -def getsyx() -> Tuple[int, int]: ... +def getmouse() -> tuple[int, int, int, int, int]: ... +def getsyx() -> tuple[int, int]: ... def getwin(__file: BinaryIO) -> _CursesWindow: ... def halfdelay(__tenths: int) -> None: ... def has_colors() -> bool: ... @@ -297,7 +297,7 @@ def killchar() -> bytes: ... def longname() -> bytes: ... def meta(__yes: bool) -> None: ... def mouseinterval(__interval: int) -> None: ... -def mousemask(__newmask: int) -> Tuple[int, int]: ... +def mousemask(__newmask: int) -> tuple[int, int]: ... def napms(__ms: int) -> int: ... def newpad(__nlines: int, __ncols: int) -> _CursesWindow: ... def newwin(__nlines: int, __ncols: int, __begin_y: int = ..., __begin_x: int = ...) -> _CursesWindow: ... @@ -307,7 +307,7 @@ def noecho() -> None: ... def nonl() -> None: ... def noqiflush() -> None: ... def noraw() -> None: ... -def pair_content(__pair_number: int) -> Tuple[int, int]: ... +def pair_content(__pair_number: int) -> tuple[int, int]: ... def pair_number(__attr: int) -> int: ... def putp(__string: bytes) -> None: ... def qiflush(__flag: bool = ...) -> None: ... @@ -405,8 +405,8 @@ class _CursesWindow: def echochar(self, __ch: _chtype, __attr: int = ...) -> None: ... def enclose(self, __y: int, __x: int) -> bool: ... def erase(self) -> None: ... - def getbegyx(self) -> Tuple[int, int]: ... - def getbkgd(self) -> Tuple[int, int]: ... + def getbegyx(self) -> tuple[int, int]: ... + def getbkgd(self) -> tuple[int, int]: ... @overload def getch(self) -> int: ... @overload @@ -415,8 +415,8 @@ class _CursesWindow: def getkey(self) -> str: ... @overload def getkey(self, y: int, x: int) -> str: ... - def getmaxyx(self) -> Tuple[int, int]: ... - def getparyx(self) -> Tuple[int, int]: ... + def getmaxyx(self) -> tuple[int, int]: ... + def getparyx(self) -> tuple[int, int]: ... @overload def getstr(self) -> _chtype: ... @overload @@ -425,7 +425,7 @@ class _CursesWindow: def getstr(self, y: int, x: int) -> _chtype: ... @overload def getstr(self, y: int, x: int, n: int) -> _chtype: ... - def getyx(self) -> Tuple[int, int]: ... + def getyx(self) -> tuple[int, int]: ... @overload def hline(self, ch: _chtype, n: int) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi b/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi index e45a1b5c4a89..10fbc938f86d 100644 --- a/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi +++ b/mypy/typeshed/stdlib/@python2/_dummy_threading.pyi @@ -1,19 +1,18 @@ from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, List, Mapping, Optional, Text, Type, TypeVar +from typing import Any, Callable, Iterable, Mapping, Optional, Text # TODO recursive type _TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] _PF = Callable[[FrameType, str, Any], None] -_T = TypeVar("_T") -__all__: List[str] +__all__: list[str] def active_count() -> int: ... def activeCount() -> int: ... def current_thread() -> Thread: ... def currentThread() -> Thread: ... -def enumerate() -> List[Thread]: ... +def enumerate() -> list[Thread]: ... def settrace(func: _TF) -> None: ... def setprofile(func: _PF | None) -> None: ... def stack_size(size: int = ...) -> int: ... @@ -53,7 +52,7 @@ class Lock: def __init__(self) -> None: ... def __enter__(self) -> bool: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def release(self) -> None: ... @@ -63,7 +62,7 @@ class _RLock: def __init__(self) -> None: ... def __enter__(self) -> bool: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def release(self) -> None: ... @@ -74,7 +73,7 @@ class Condition: def __init__(self, lock: Lock | _RLock | None = ...) -> None: ... def __enter__(self) -> bool: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def release(self) -> None: ... @@ -86,7 +85,7 @@ class Condition: class Semaphore: def __init__(self, value: int = ...) -> None: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def __enter__(self, blocking: bool = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/_functools.pyi b/mypy/typeshed/stdlib/@python2/_functools.pyi index e68398238f9b..d695e76994c9 100644 --- a/mypy/typeshed/stdlib/@python2/_functools.pyi +++ b/mypy/typeshed/stdlib/@python2/_functools.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Dict, Iterable, Tuple, TypeVar, overload +from typing import Any, Callable, Iterable, TypeVar, overload _T = TypeVar("_T") _S = TypeVar("_S") @@ -10,7 +10,7 @@ def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T class partial(object): func: Callable[..., Any] - args: Tuple[Any, ...] - keywords: Dict[str, Any] + args: tuple[Any, ...] + keywords: dict[str, Any] def __init__(self, func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... diff --git a/mypy/typeshed/stdlib/@python2/_heapq.pyi b/mypy/typeshed/stdlib/@python2/_heapq.pyi index 08a8add08e9a..a2a38dc9c3ed 100644 --- a/mypy/typeshed/stdlib/@python2/_heapq.pyi +++ b/mypy/typeshed/stdlib/@python2/_heapq.pyi @@ -1,11 +1,11 @@ -from typing import Any, Callable, Iterable, List, TypeVar +from typing import Any, Callable, Iterable, TypeVar _T = TypeVar("_T") -def heapify(__heap: List[Any]) -> None: ... -def heappop(__heap: List[_T]) -> _T: ... -def heappush(__heap: List[_T], __item: _T) -> None: ... -def heappushpop(__heap: List[_T], __item: _T) -> _T: ... -def heapreplace(__heap: List[_T], __item: _T) -> _T: ... -def nlargest(__n: int, __iterable: Iterable[_T], __key: Callable[[_T], Any] | None = ...) -> List[_T]: ... -def nsmallest(__n: int, __iterable: Iterable[_T], __key: Callable[[_T], Any] | None = ...) -> List[_T]: ... +def heapify(__heap: list[Any]) -> None: ... +def heappop(__heap: list[_T]) -> _T: ... +def heappush(__heap: list[_T], __item: _T) -> None: ... +def heappushpop(__heap: list[_T], __item: _T) -> _T: ... +def heapreplace(__heap: list[_T], __item: _T) -> _T: ... +def nlargest(__n: int, __iterable: Iterable[_T], __key: Callable[[_T], Any] | None = ...) -> list[_T]: ... +def nsmallest(__n: int, __iterable: Iterable[_T], __key: Callable[[_T], Any] | None = ...) -> list[_T]: ... diff --git a/mypy/typeshed/stdlib/@python2/_hotshot.pyi b/mypy/typeshed/stdlib/@python2/_hotshot.pyi index b048f6fb83d5..aa188a2b4fae 100644 --- a/mypy/typeshed/stdlib/@python2/_hotshot.pyi +++ b/mypy/typeshed/stdlib/@python2/_hotshot.pyi @@ -1,9 +1,9 @@ -from typing import Any, Tuple +from typing import Any def coverage(a: str) -> Any: ... def logreader(a: str) -> LogReaderType: ... def profiler(a: str, *args, **kwargs) -> Any: ... -def resolution() -> Tuple[Any, ...]: ... +def resolution() -> tuple[Any, ...]: ... class LogReaderType(object): def close(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_io.pyi b/mypy/typeshed/stdlib/@python2/_io.pyi index fedbbe137940..3c1eab23b854 100644 --- a/mypy/typeshed/stdlib/@python2/_io.pyi +++ b/mypy/typeshed/stdlib/@python2/_io.pyi @@ -1,6 +1,6 @@ from _typeshed import Self from mmap import mmap -from typing import IO, Any, BinaryIO, Iterable, List, Text, TextIO, Tuple, Type, TypeVar, Union +from typing import IO, Any, BinaryIO, Iterable, Text, TextIO, Union _bytearray_like = Union[bytearray, mmap] @@ -11,8 +11,6 @@ class BlockingIOError(IOError): class UnsupportedOperation(ValueError, IOError): ... -_T = TypeVar("_T") - class _IOBase(BinaryIO): @property def closed(self) -> bool: ... @@ -32,13 +30,13 @@ class _IOBase(BinaryIO): def truncate(self, size: int | None = ...) -> int: ... def writable(self) -> bool: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, t: Type[BaseException] | None, value: BaseException | None, traceback: Any | None) -> bool | None: ... - def __iter__(self: _T) -> _T: ... + def __exit__(self, t: type[BaseException] | None, value: BaseException | None, traceback: Any | None) -> bool | None: ... + def __iter__(self: Self) -> Self: ... # The parameter type of writelines[s]() is determined by that of write(): def writelines(self, lines: Iterable[bytes]) -> None: ... # The return type of readline[s]() and next() is determined by that of read(): def readline(self, limit: int = ...) -> bytes: ... - def readlines(self, hint: int = ...) -> List[bytes]: ... + def readlines(self, hint: int = ...) -> list[bytes]: ... def next(self) -> bytes: ... # These don't actually exist but we need to pretend that it does # so that this class is concrete. @@ -79,8 +77,8 @@ class BufferedWriter(_BufferedIOBase): class BytesIO(_BufferedIOBase): def __init__(self, initial_bytes: bytes = ...) -> None: ... - def __setstate__(self, state: Tuple[Any, ...]) -> None: ... - def __getstate__(self) -> Tuple[Any, ...]: ... + def __setstate__(self, state: tuple[Any, ...]) -> None: ... + def __getstate__(self) -> tuple[Any, ...]: ... # BytesIO does not contain a "name" field. This workaround is necessary # to allow BytesIO sub-classes to add this field, as it is defined # as a read-only property on IO[]. @@ -106,8 +104,8 @@ class IncrementalNewlineDecoder(object): newlines: str | unicode def __init__(self, decoder, translate, z=...) -> None: ... def decode(self, input, final) -> Any: ... - def getstate(self) -> Tuple[Any, int]: ... - def setstate(self, state: Tuple[Any, int]) -> None: ... + def getstate(self) -> tuple[Any, int]: ... + def setstate(self, state: tuple[Any, int]) -> None: ... def reset(self) -> None: ... # Note: In the actual _io.py, _TextIOBase inherits from _IOBase. @@ -140,14 +138,14 @@ class _TextIOBase(TextIO): def write(self, pbuf: unicode) -> int: ... def writelines(self, lines: Iterable[unicode]) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, t: Type[BaseException] | None, value: BaseException | None, traceback: Any | None) -> bool | None: ... - def __iter__(self: _T) -> _T: ... + def __exit__(self, t: type[BaseException] | None, value: BaseException | None, traceback: Any | None) -> bool | None: ... + def __iter__(self: Self) -> Self: ... class StringIO(_TextIOBase): line_buffering: bool def __init__(self, initial_value: unicode | None = ..., newline: unicode | None = ...) -> None: ... - def __setstate__(self, state: Tuple[Any, ...]) -> None: ... - def __getstate__(self) -> Tuple[Any, ...]: ... + def __setstate__(self, state: tuple[Any, ...]) -> None: ... + def __getstate__(self) -> tuple[Any, ...]: ... # StringIO does not contain a "name" field. This workaround is necessary # to allow StringIO sub-classes to add this field, as it is defined # as a read-only property on IO[]. diff --git a/mypy/typeshed/stdlib/@python2/_json.pyi b/mypy/typeshed/stdlib/@python2/_json.pyi index a9868b3e60fd..57c70e80564e 100644 --- a/mypy/typeshed/stdlib/@python2/_json.pyi +++ b/mypy/typeshed/stdlib/@python2/_json.pyi @@ -1,7 +1,7 @@ -from typing import Any, Tuple +from typing import Any def encode_basestring_ascii(*args, **kwargs) -> str: ... -def scanstring(a, b, *args, **kwargs) -> Tuple[Any, ...]: ... +def scanstring(a, b, *args, **kwargs) -> tuple[Any, ...]: ... class Encoder(object): ... class Scanner(object): ... diff --git a/mypy/typeshed/stdlib/@python2/_markupbase.pyi b/mypy/typeshed/stdlib/@python2/_markupbase.pyi index d8bc79f34e8c..368d32bd5b4c 100644 --- a/mypy/typeshed/stdlib/@python2/_markupbase.pyi +++ b/mypy/typeshed/stdlib/@python2/_markupbase.pyi @@ -1,8 +1,6 @@ -from typing import Tuple - class ParserBase: def __init__(self) -> None: ... def error(self, message: str) -> None: ... def reset(self) -> None: ... - def getpos(self) -> Tuple[int, int]: ... + def getpos(self) -> tuple[int, int]: ... def unknown_decl(self, data: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_msi.pyi b/mypy/typeshed/stdlib/@python2/_msi.pyi index a1030a66160f..754febe68da9 100644 --- a/mypy/typeshed/stdlib/@python2/_msi.pyi +++ b/mypy/typeshed/stdlib/@python2/_msi.pyi @@ -1,5 +1,4 @@ import sys -from typing import List if sys.platform == "win32": @@ -44,6 +43,6 @@ if sys.platform == "win32": __new__: None # type: ignore __init__: None # type: ignore def UuidCreate() -> str: ... - def FCICreate(cabname: str, files: List[str]) -> None: ... + def FCICreate(cabname: str, files: list[str]) -> None: ... def OpenDatabase(name: str, flags: int) -> _Database: ... def CreateRecord(count: int) -> _Record: ... diff --git a/mypy/typeshed/stdlib/@python2/_osx_support.pyi b/mypy/typeshed/stdlib/@python2/_osx_support.pyi index 1b890d8d8a0a..72645167c1af 100644 --- a/mypy/typeshed/stdlib/@python2/_osx_support.pyi +++ b/mypy/typeshed/stdlib/@python2/_osx_support.pyi @@ -1,13 +1,13 @@ -from typing import Dict, Iterable, List, Sequence, Tuple, TypeVar +from typing import Iterable, Sequence, TypeVar _T = TypeVar("_T") _K = TypeVar("_K") _V = TypeVar("_V") -__all__: List[str] +__all__: list[str] -_UNIVERSAL_CONFIG_VARS: Tuple[str, ...] # undocumented -_COMPILER_CONFIG_VARS: Tuple[str, ...] # undocumented +_UNIVERSAL_CONFIG_VARS: tuple[str, ...] # undocumented +_COMPILER_CONFIG_VARS: tuple[str, ...] # undocumented _INITPRE: str # undocumented def _find_executable(executable: str, path: str | None = ...) -> str | None: ... # undocumented @@ -17,17 +17,17 @@ def _find_build_tool(toolname: str) -> str: ... # undocumented _SYSTEM_VERSION: str | None # undocumented def _get_system_version() -> str: ... # undocumented -def _remove_original_values(_config_vars: Dict[str, str]) -> None: ... # undocumented -def _save_modified_value(_config_vars: Dict[str, str], cv: str, newvalue: str) -> None: ... # undocumented +def _remove_original_values(_config_vars: dict[str, str]) -> None: ... # undocumented +def _save_modified_value(_config_vars: dict[str, str], cv: str, newvalue: str) -> None: ... # undocumented def _supports_universal_builds() -> bool: ... # undocumented -def _find_appropriate_compiler(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented -def _remove_universal_flags(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented -def _remove_unsupported_archs(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented -def _override_all_archs(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented -def _check_for_unavailable_sdk(_config_vars: Dict[str, str]) -> Dict[str, str]: ... # undocumented -def compiler_fixup(compiler_so: Iterable[str], cc_args: Sequence[str]) -> List[str]: ... -def customize_config_vars(_config_vars: Dict[str, str]) -> Dict[str, str]: ... -def customize_compiler(_config_vars: Dict[str, str]) -> Dict[str, str]: ... +def _find_appropriate_compiler(_config_vars: dict[str, str]) -> dict[str, str]: ... # undocumented +def _remove_universal_flags(_config_vars: dict[str, str]) -> dict[str, str]: ... # undocumented +def _remove_unsupported_archs(_config_vars: dict[str, str]) -> dict[str, str]: ... # undocumented +def _override_all_archs(_config_vars: dict[str, str]) -> dict[str, str]: ... # undocumented +def _check_for_unavailable_sdk(_config_vars: dict[str, str]) -> dict[str, str]: ... # undocumented +def compiler_fixup(compiler_so: Iterable[str], cc_args: Sequence[str]) -> list[str]: ... +def customize_config_vars(_config_vars: dict[str, str]) -> dict[str, str]: ... +def customize_compiler(_config_vars: dict[str, str]) -> dict[str, str]: ... def get_platform_osx( - _config_vars: Dict[str, str], osname: _T, release: _K, machine: _V -) -> Tuple[str | _T, str | _K, str | _V]: ... + _config_vars: dict[str, str], osname: _T, release: _K, machine: _V +) -> tuple[str | _T, str | _K, str | _V]: ... diff --git a/mypy/typeshed/stdlib/@python2/_random.pyi b/mypy/typeshed/stdlib/@python2/_random.pyi index 7c2dd61af49f..8bd1afad48cb 100644 --- a/mypy/typeshed/stdlib/@python2/_random.pyi +++ b/mypy/typeshed/stdlib/@python2/_random.pyi @@ -1,7 +1,5 @@ -from typing import Tuple - # Actually Tuple[(int,) * 625] -_State = Tuple[int, ...] +_State = tuple[int, ...] class Random(object): def __init__(self, seed: object = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_socket.pyi b/mypy/typeshed/stdlib/@python2/_socket.pyi index c505384c5226..d081494be68f 100644 --- a/mypy/typeshed/stdlib/@python2/_socket.pyi +++ b/mypy/typeshed/stdlib/@python2/_socket.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Tuple, overload +from typing import IO, Any, overload AF_APPLETALK: int AF_ASH: int @@ -252,29 +252,29 @@ class SocketType(object): proto: int timeout: float def __init__(self, family: int = ..., type: int = ..., proto: int = ...) -> None: ... - def accept(self) -> Tuple[SocketType, Tuple[Any, ...]]: ... - def bind(self, address: Tuple[Any, ...]) -> None: ... + def accept(self) -> tuple[SocketType, tuple[Any, ...]]: ... + def bind(self, address: tuple[Any, ...]) -> None: ... def close(self) -> None: ... - def connect(self, address: Tuple[Any, ...]) -> None: ... - def connect_ex(self, address: Tuple[Any, ...]) -> int: ... + def connect(self, address: tuple[Any, ...]) -> None: ... + def connect_ex(self, address: tuple[Any, ...]) -> int: ... def dup(self) -> SocketType: ... def fileno(self) -> int: ... - def getpeername(self) -> Tuple[Any, ...]: ... - def getsockname(self) -> Tuple[Any, ...]: ... + def getpeername(self) -> tuple[Any, ...]: ... + def getsockname(self) -> tuple[Any, ...]: ... def getsockopt(self, level: int, option: int, buffersize: int = ...) -> str: ... def gettimeout(self) -> float: ... def listen(self, backlog: int) -> None: ... def makefile(self, mode: str = ..., buffersize: int = ...) -> IO[Any]: ... def recv(self, buffersize: int, flags: int = ...) -> str: ... def recv_into(self, buffer: bytearray, nbytes: int = ..., flags: int = ...) -> int: ... - def recvfrom(self, buffersize: int, flags: int = ...) -> Tuple[Any, ...]: ... + def recvfrom(self, buffersize: int, flags: int = ...) -> tuple[Any, ...]: ... def recvfrom_into(self, buffer: bytearray, nbytes: int = ..., flags: int = ...) -> int: ... def send(self, data: str, flags: int = ...) -> int: ... def sendall(self, data: str, flags: int = ...) -> None: ... @overload - def sendto(self, data: str, address: Tuple[Any, ...]) -> int: ... + def sendto(self, data: str, address: tuple[Any, ...]) -> int: ... @overload - def sendto(self, data: str, flags: int, address: Tuple[Any, ...]) -> int: ... + def sendto(self, data: str, flags: int, address: tuple[Any, ...]) -> int: ... def setblocking(self, flag: bool) -> None: ... def setsockopt(self, level: int, option: int, value: int | str) -> None: ... def settimeout(self, value: float | None) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_sre.pyi b/mypy/typeshed/stdlib/@python2/_sre.pyi index 3bacc097451e..ba61c56344ac 100644 --- a/mypy/typeshed/stdlib/@python2/_sre.pyi +++ b/mypy/typeshed/stdlib/@python2/_sre.pyi @@ -1,4 +1,4 @@ -from typing import Any, Dict, Iterable, List, Mapping, Sequence, Tuple, overload +from typing import Any, Iterable, Mapping, Sequence, overload CODESIZE: int MAGIC: int @@ -13,11 +13,11 @@ class SRE_Match(object): def group(self) -> str: ... @overload def group(self, group: int = ...) -> str | None: ... - def groupdict(self) -> Dict[int, str | None]: ... - def groups(self) -> Tuple[str | None, ...]: ... - def span(self) -> Tuple[int, int]: ... + def groupdict(self) -> dict[int, str | None]: ... + def groups(self) -> tuple[str | None, ...]: ... + def span(self) -> tuple[int, int]: ... @property - def regs(self) -> Tuple[Tuple[int, int], ...]: ... # undocumented + def regs(self) -> tuple[tuple[int, int], ...]: ... # undocumented class SRE_Scanner(object): pattern: str @@ -30,19 +30,19 @@ class SRE_Pattern(object): groups: int groupindex: Mapping[str, int] indexgroup: Sequence[int] - def findall(self, source: str, pos: int = ..., endpos: int = ...) -> List[Tuple[Any, ...] | str]: ... - def finditer(self, source: str, pos: int = ..., endpos: int = ...) -> Iterable[Tuple[Any, ...] | str]: ... + def findall(self, source: str, pos: int = ..., endpos: int = ...) -> list[tuple[Any, ...] | str]: ... + def finditer(self, source: str, pos: int = ..., endpos: int = ...) -> Iterable[tuple[Any, ...] | str]: ... def match(self, pattern, pos: int = ..., endpos: int = ...) -> SRE_Match: ... def scanner(self, s: str, start: int = ..., end: int = ...) -> SRE_Scanner: ... def search(self, pattern, pos: int = ..., endpos: int = ...) -> SRE_Match: ... - def split(self, source: str, maxsplit: int = ...) -> List[str | None]: ... - def sub(self, repl: str, string: str, count: int = ...) -> Tuple[Any, ...]: ... - def subn(self, repl: str, string: str, count: int = ...) -> Tuple[Any, ...]: ... + def split(self, source: str, maxsplit: int = ...) -> list[str | None]: ... + def sub(self, repl: str, string: str, count: int = ...) -> tuple[Any, ...]: ... + def subn(self, repl: str, string: str, count: int = ...) -> tuple[Any, ...]: ... def compile( pattern: str, flags: int, - code: List[int], + code: list[int], groups: int = ..., groupindex: Mapping[str, int] = ..., indexgroup: Sequence[int] = ..., diff --git a/mypy/typeshed/stdlib/@python2/_struct.pyi b/mypy/typeshed/stdlib/@python2/_struct.pyi index 316307eaabca..89357ab0bbc8 100644 --- a/mypy/typeshed/stdlib/@python2/_struct.pyi +++ b/mypy/typeshed/stdlib/@python2/_struct.pyi @@ -1,4 +1,4 @@ -from typing import Any, AnyStr, Tuple +from typing import Any, AnyStr class error(Exception): ... @@ -8,12 +8,12 @@ class Struct(object): def __init__(self, fmt: str) -> None: ... def pack_into(self, buffer: bytearray, offset: int, obj: Any) -> None: ... def pack(self, *args) -> str: ... - def unpack(self, s: str) -> Tuple[Any, ...]: ... - def unpack_from(self, buffer: bytearray, offset: int = ...) -> Tuple[Any, ...]: ... + def unpack(self, s: str) -> tuple[Any, ...]: ... + def unpack_from(self, buffer: bytearray, offset: int = ...) -> tuple[Any, ...]: ... def _clearcache() -> None: ... def calcsize(fmt: str) -> int: ... def pack(fmt: AnyStr, obj: Any) -> str: ... def pack_into(fmt: AnyStr, buffer: bytearray, offset: int, obj: Any) -> None: ... -def unpack(fmt: AnyStr, data: str) -> Tuple[Any, ...]: ... -def unpack_from(fmt: AnyStr, buffer: bytearray, offset: int = ...) -> Tuple[Any, ...]: ... +def unpack(fmt: AnyStr, data: str) -> tuple[Any, ...]: ... +def unpack_from(fmt: AnyStr, buffer: bytearray, offset: int = ...) -> tuple[Any, ...]: ... diff --git a/mypy/typeshed/stdlib/@python2/_symtable.pyi b/mypy/typeshed/stdlib/@python2/_symtable.pyi index 5b2370449c31..ca21f8d5e521 100644 --- a/mypy/typeshed/stdlib/@python2/_symtable.pyi +++ b/mypy/typeshed/stdlib/@python2/_symtable.pyi @@ -1,5 +1,3 @@ -from typing import Dict, List - CELL: int DEF_BOUND: int DEF_FREE: int @@ -25,13 +23,13 @@ USE: int class _symtable_entry(object): ... class symtable(object): - children: List[_symtable_entry] + children: list[_symtable_entry] id: int lineno: int name: str nested: int optimized: int - symbols: Dict[str, int] + symbols: dict[str, int] type: int - varnames: List[str] + varnames: list[str] def __init__(self, src: str, filename: str, startstr: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_thread.pyi b/mypy/typeshed/stdlib/@python2/_thread.pyi index 562ece61e042..0470ebd4830f 100644 --- a/mypy/typeshed/stdlib/@python2/_thread.pyi +++ b/mypy/typeshed/stdlib/@python2/_thread.pyi @@ -1,5 +1,5 @@ from types import TracebackType -from typing import Any, Callable, Dict, NoReturn, Tuple, Type +from typing import Any, Callable, NoReturn error = RuntimeError @@ -13,10 +13,10 @@ class LockType: def locked(self) -> bool: ... def __enter__(self) -> bool: ... def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... -def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> int: ... +def start_new_thread(function: Callable[..., Any], args: tuple[Any, ...], kwargs: dict[str, Any] = ...) -> int: ... def interrupt_main() -> None: ... def exit() -> NoReturn: ... def allocate_lock() -> LockType: ... diff --git a/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi index ca698e29ae8a..0d1dc3866b56 100644 --- a/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/_typeshed/__init__.pyi @@ -14,7 +14,7 @@ import array import mmap -from typing import Any, Container, Iterable, Protocol, Text, Tuple, TypeVar, Union +from typing import Any, Container, Iterable, Protocol, Text, TypeVar, Union from typing_extensions import Literal, final _KT = TypeVar("_KT") @@ -48,7 +48,7 @@ class SupportsRDivMod(Protocol[_T_contra, _T_co]): class SupportsItems(Protocol[_KT_co, _VT_co]): # We want dictionaries to support this on Python 2. - def items(self) -> Iterable[Tuple[_KT_co, _VT_co]]: ... + def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ... class SupportsKeysAndGetItem(Protocol[_KT, _VT_co]): def keys(self) -> Iterable[_KT]: ... diff --git a/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi b/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi index a1f10443a6f0..6dc2b5cc021d 100644 --- a/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi +++ b/mypy/typeshed/stdlib/@python2/_typeshed/wsgi.pyi @@ -4,28 +4,28 @@ # file. They are provided for type checking purposes. from sys import _OptExcInfo -from typing import Any, Callable, Dict, Iterable, List, Optional, Protocol, Text, Tuple +from typing import Any, Callable, Iterable, Optional, Protocol, Text class StartResponse(Protocol): def __call__( - self, status: str, headers: List[Tuple[str, str]], exc_info: _OptExcInfo | None = ... + self, status: str, headers: list[tuple[str, str]], exc_info: _OptExcInfo | None = ... ) -> Callable[[bytes], Any]: ... -WSGIEnvironment = Dict[Text, Any] +WSGIEnvironment = dict[Text, Any] WSGIApplication = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] # WSGI input streams per PEP 3333 class InputStream(Protocol): def read(self, size: int = ...) -> bytes: ... def readline(self, size: int = ...) -> bytes: ... - def readlines(self, hint: int = ...) -> List[bytes]: ... + def readlines(self, hint: int = ...) -> list[bytes]: ... def __iter__(self) -> Iterable[bytes]: ... # WSGI error streams per PEP 3333 class ErrorStream(Protocol): def flush(self) -> None: ... def write(self, s: str) -> None: ... - def writelines(self, seq: List[str]) -> None: ... + def writelines(self, seq: list[str]) -> None: ... class _Readable(Protocol): def read(self, size: int = ...) -> bytes: ... diff --git a/mypy/typeshed/stdlib/@python2/_typeshed/xml.pyi b/mypy/typeshed/stdlib/@python2/_typeshed/xml.pyi index 6a5d2531ca72..eaff9a641db4 100644 --- a/mypy/typeshed/stdlib/@python2/_typeshed/xml.pyi +++ b/mypy/typeshed/stdlib/@python2/_typeshed/xml.pyi @@ -1,7 +1,6 @@ # Stub-only types. This module does not exist at runtime. -from typing import Any -from typing_extensions import Protocol +from typing import Any, Protocol # As defined https://docs.python.org/3/library/xml.dom.html#domimplementation-objects class DOMImplementation(Protocol): diff --git a/mypy/typeshed/stdlib/@python2/_warnings.pyi b/mypy/typeshed/stdlib/@python2/_warnings.pyi index ccc51fecb8da..8f531c47af55 100644 --- a/mypy/typeshed/stdlib/@python2/_warnings.pyi +++ b/mypy/typeshed/stdlib/@python2/_warnings.pyi @@ -1,23 +1,23 @@ -from typing import Any, Dict, List, Tuple, Type, overload +from typing import Any, overload default_action: str -once_registry: Dict[Any, Any] +once_registry: dict[Any, Any] -filters: List[Tuple[Any, ...]] +filters: list[tuple[Any, ...]] @overload -def warn(message: str, category: Type[Warning] | None = ..., stacklevel: int = ...) -> None: ... +def warn(message: str, category: type[Warning] | None = ..., stacklevel: int = ...) -> None: ... @overload def warn(message: Warning, category: Any = ..., stacklevel: int = ...) -> None: ... @overload def warn_explicit( message: str, - category: Type[Warning], + category: type[Warning], filename: str, lineno: int, module: str | None = ..., - registry: Dict[str | Tuple[str, Type[Warning], int], int] | None = ..., - module_globals: Dict[str, Any] | None = ..., + registry: dict[str | tuple[str, type[Warning], int], int] | None = ..., + module_globals: dict[str, Any] | None = ..., ) -> None: ... @overload def warn_explicit( @@ -26,6 +26,6 @@ def warn_explicit( filename: str, lineno: int, module: str | None = ..., - registry: Dict[str | Tuple[str, Type[Warning], int], int] | None = ..., - module_globals: Dict[str, Any] | None = ..., + registry: dict[str | tuple[str, type[Warning], int], int] | None = ..., + module_globals: dict[str, Any] | None = ..., ) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/_weakref.pyi b/mypy/typeshed/stdlib/@python2/_weakref.pyi index a283d4cb60d3..9a37de3174b6 100644 --- a/mypy/typeshed/stdlib/@python2/_weakref.pyi +++ b/mypy/typeshed/stdlib/@python2/_weakref.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Generic, List, TypeVar, overload +from typing import Any, Callable, Generic, TypeVar, overload _C = TypeVar("_C", bound=Callable[..., Any]) _T = TypeVar("_T") @@ -17,7 +17,7 @@ class ReferenceType(Generic[_T]): ref = ReferenceType def getweakrefcount(__object: Any) -> int: ... -def getweakrefs(object: Any) -> List[Any]: ... +def getweakrefs(object: Any) -> list[Any]: ... @overload def proxy(object: _C, callback: Callable[[_C], Any] | None = ...) -> CallableProxyType[_C]: ... diff --git a/mypy/typeshed/stdlib/@python2/_weakrefset.pyi b/mypy/typeshed/stdlib/@python2/_weakrefset.pyi index f2cde7d67e52..a6ca20d572fc 100644 --- a/mypy/typeshed/stdlib/@python2/_weakrefset.pyi +++ b/mypy/typeshed/stdlib/@python2/_weakrefset.pyi @@ -1,15 +1,15 @@ +from _typeshed import Self from typing import Any, Generic, Iterable, Iterator, MutableSet, TypeVar _S = TypeVar("_S") _T = TypeVar("_T") -_SelfT = TypeVar("_SelfT", bound=WeakSet[Any]) class WeakSet(MutableSet[_T], Generic[_T]): def __init__(self, data: Iterable[_T] | None = ...) -> None: ... def add(self, item: _T) -> None: ... def clear(self) -> None: ... def discard(self, item: _T) -> None: ... - def copy(self: _SelfT) -> _SelfT: ... + def copy(self: Self) -> Self: ... def pop(self) -> _T: ... def remove(self, item: _T) -> None: ... def update(self, other: Iterable[_T]) -> None: ... @@ -17,14 +17,14 @@ class WeakSet(MutableSet[_T], Generic[_T]): def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... def __ior__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... - def difference(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def __sub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def difference(self: Self, other: Iterable[_T]) -> Self: ... + def __sub__(self: Self, other: Iterable[_T]) -> Self: ... def difference_update(self, other: Iterable[_T]) -> None: ... - def __isub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def intersection(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def __and__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def __isub__(self: Self, other: Iterable[_T]) -> Self: ... + def intersection(self: Self, other: Iterable[_T]) -> Self: ... + def __and__(self: Self, other: Iterable[_T]) -> Self: ... def intersection_update(self, other: Iterable[_T]) -> None: ... - def __iand__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def __iand__(self: Self, other: Iterable[_T]) -> Self: ... def issubset(self, other: Iterable[_T]) -> bool: ... def __le__(self, other: Iterable[_T]) -> bool: ... def __lt__(self, other: Iterable[_T]) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/_winreg.pyi b/mypy/typeshed/stdlib/@python2/_winreg.pyi index 7297626ac8b3..0381dc03ba01 100644 --- a/mypy/typeshed/stdlib/@python2/_winreg.pyi +++ b/mypy/typeshed/stdlib/@python2/_winreg.pyi @@ -1,96 +1,96 @@ +import sys from types import TracebackType -from typing import Any, Tuple, Type, Union +from typing import Any, Union -_KeyType = Union[HKEYType, int] +if sys.platform == "win32": + _KeyType = Union[HKEYType, int] + def CloseKey(__hkey: _KeyType) -> None: ... + def ConnectRegistry(__computer_name: str | None, __key: _KeyType) -> HKEYType: ... + def CreateKey(__key: _KeyType, __sub_key: str | None) -> HKEYType: ... + def CreateKeyEx(key: _KeyType, sub_key: str | None, reserved: int = ..., access: int = ...) -> HKEYType: ... + def DeleteKey(__key: _KeyType, __sub_key: str) -> None: ... + def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = ..., reserved: int = ...) -> None: ... + def DeleteValue(__key: _KeyType, __value: str) -> None: ... + def EnumKey(__key: _KeyType, __index: int) -> str: ... + def EnumValue(__key: _KeyType, __index: int) -> tuple[str, Any, int]: ... + def ExpandEnvironmentStrings(__str: str) -> str: ... + def FlushKey(__key: _KeyType) -> None: ... + def LoadKey(__key: _KeyType, __sub_key: str, __file_name: str) -> None: ... + def OpenKey(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... + def OpenKeyEx(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... + def QueryInfoKey(__key: _KeyType) -> tuple[int, int, int]: ... + def QueryValue(__key: _KeyType, __sub_key: str | None) -> str: ... + def QueryValueEx(__key: _KeyType, __name: str) -> tuple[Any, int]: ... + def SaveKey(__key: _KeyType, __file_name: str) -> None: ... + def SetValue(__key: _KeyType, __sub_key: str, __type: int, __value: str) -> None: ... + def SetValueEx( + __key: _KeyType, __value_name: str | None, __reserved: Any, __type: int, __value: str | int + ) -> None: ... # reserved is ignored + def DisableReflectionKey(__key: _KeyType) -> None: ... + def EnableReflectionKey(__key: _KeyType) -> None: ... + def QueryReflectionKey(__key: _KeyType) -> bool: ... + HKEY_CLASSES_ROOT: int + HKEY_CURRENT_USER: int + HKEY_LOCAL_MACHINE: int + HKEY_USERS: int + HKEY_PERFORMANCE_DATA: int + HKEY_CURRENT_CONFIG: int + HKEY_DYN_DATA: int -def CloseKey(__hkey: _KeyType) -> None: ... -def ConnectRegistry(__computer_name: str | None, __key: _KeyType) -> HKEYType: ... -def CreateKey(__key: _KeyType, __sub_key: str | None) -> HKEYType: ... -def CreateKeyEx(key: _KeyType, sub_key: str | None, reserved: int = ..., access: int = ...) -> HKEYType: ... -def DeleteKey(__key: _KeyType, __sub_key: str) -> None: ... -def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = ..., reserved: int = ...) -> None: ... -def DeleteValue(__key: _KeyType, __value: str) -> None: ... -def EnumKey(__key: _KeyType, __index: int) -> str: ... -def EnumValue(__key: _KeyType, __index: int) -> Tuple[str, Any, int]: ... -def ExpandEnvironmentStrings(__str: str) -> str: ... -def FlushKey(__key: _KeyType) -> None: ... -def LoadKey(__key: _KeyType, __sub_key: str, __file_name: str) -> None: ... -def OpenKey(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... -def OpenKeyEx(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... -def QueryInfoKey(__key: _KeyType) -> Tuple[int, int, int]: ... -def QueryValue(__key: _KeyType, __sub_key: str | None) -> str: ... -def QueryValueEx(__key: _KeyType, __name: str) -> Tuple[Any, int]: ... -def SaveKey(__key: _KeyType, __file_name: str) -> None: ... -def SetValue(__key: _KeyType, __sub_key: str, __type: int, __value: str) -> None: ... -def SetValueEx( - __key: _KeyType, __value_name: str | None, __reserved: Any, __type: int, __value: str | int -) -> None: ... # reserved is ignored -def DisableReflectionKey(__key: _KeyType) -> None: ... -def EnableReflectionKey(__key: _KeyType) -> None: ... -def QueryReflectionKey(__key: _KeyType) -> bool: ... + KEY_ALL_ACCESS: int + KEY_WRITE: int + KEY_READ: int + KEY_EXECUTE: int + KEY_QUERY_VALUE: int + KEY_SET_VALUE: int + KEY_CREATE_SUB_KEY: int + KEY_ENUMERATE_SUB_KEYS: int + KEY_NOTIFY: int + KEY_CREATE_LINK: int -HKEY_CLASSES_ROOT: int -HKEY_CURRENT_USER: int -HKEY_LOCAL_MACHINE: int -HKEY_USERS: int -HKEY_PERFORMANCE_DATA: int -HKEY_CURRENT_CONFIG: int -HKEY_DYN_DATA: int + KEY_WOW64_64KEY: int + KEY_WOW64_32KEY: int -KEY_ALL_ACCESS: int -KEY_WRITE: int -KEY_READ: int -KEY_EXECUTE: int -KEY_QUERY_VALUE: int -KEY_SET_VALUE: int -KEY_CREATE_SUB_KEY: int -KEY_ENUMERATE_SUB_KEYS: int -KEY_NOTIFY: int -KEY_CREATE_LINK: int + REG_BINARY: int + REG_DWORD: int + REG_DWORD_LITTLE_ENDIAN: int + REG_DWORD_BIG_ENDIAN: int + REG_EXPAND_SZ: int + REG_LINK: int + REG_MULTI_SZ: int + REG_NONE: int + REG_RESOURCE_LIST: int + REG_FULL_RESOURCE_DESCRIPTOR: int + REG_RESOURCE_REQUIREMENTS_LIST: int + REG_SZ: int -KEY_WOW64_64KEY: int -KEY_WOW64_32KEY: int + REG_CREATED_NEW_KEY: int # undocumented + REG_LEGAL_CHANGE_FILTER: int # undocumented + REG_LEGAL_OPTION: int # undocumented + REG_NOTIFY_CHANGE_ATTRIBUTES: int # undocumented + REG_NOTIFY_CHANGE_LAST_SET: int # undocumented + REG_NOTIFY_CHANGE_NAME: int # undocumented + REG_NOTIFY_CHANGE_SECURITY: int # undocumented + REG_NO_LAZY_FLUSH: int # undocumented + REG_OPENED_EXISTING_KEY: int # undocumented + REG_OPTION_BACKUP_RESTORE: int # undocumented + REG_OPTION_CREATE_LINK: int # undocumented + REG_OPTION_NON_VOLATILE: int # undocumented + REG_OPTION_OPEN_LINK: int # undocumented + REG_OPTION_RESERVED: int # undocumented + REG_OPTION_VOLATILE: int # undocumented + REG_REFRESH_HIVE: int # undocumented + REG_WHOLE_HIVE_VOLATILE: int # undocumented -REG_BINARY: int -REG_DWORD: int -REG_DWORD_LITTLE_ENDIAN: int -REG_DWORD_BIG_ENDIAN: int -REG_EXPAND_SZ: int -REG_LINK: int -REG_MULTI_SZ: int -REG_NONE: int -REG_RESOURCE_LIST: int -REG_FULL_RESOURCE_DESCRIPTOR: int -REG_RESOURCE_REQUIREMENTS_LIST: int -REG_SZ: int + error = OSError -REG_CREATED_NEW_KEY: int # undocumented -REG_LEGAL_CHANGE_FILTER: int # undocumented -REG_LEGAL_OPTION: int # undocumented -REG_NOTIFY_CHANGE_ATTRIBUTES: int # undocumented -REG_NOTIFY_CHANGE_LAST_SET: int # undocumented -REG_NOTIFY_CHANGE_NAME: int # undocumented -REG_NOTIFY_CHANGE_SECURITY: int # undocumented -REG_NO_LAZY_FLUSH: int # undocumented -REG_OPENED_EXISTING_KEY: int # undocumented -REG_OPTION_BACKUP_RESTORE: int # undocumented -REG_OPTION_CREATE_LINK: int # undocumented -REG_OPTION_NON_VOLATILE: int # undocumented -REG_OPTION_OPEN_LINK: int # undocumented -REG_OPTION_RESERVED: int # undocumented -REG_OPTION_VOLATILE: int # undocumented -REG_REFRESH_HIVE: int # undocumented -REG_WHOLE_HIVE_VOLATILE: int # undocumented - -error = OSError - -# Though this class has a __name__ of PyHKEY, it's exposed as HKEYType for some reason -class HKEYType: - def __bool__(self) -> bool: ... - def __int__(self) -> int: ... - def __enter__(self) -> HKEYType: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def Close(self) -> None: ... - def Detach(self) -> int: ... + # Though this class has a __name__ of PyHKEY, it's exposed as HKEYType for some reason + class HKEYType: + def __bool__(self) -> bool: ... + def __int__(self) -> int: ... + def __enter__(self) -> HKEYType: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> bool | None: ... + def Close(self) -> None: ... + def Detach(self) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/abc.pyi b/mypy/typeshed/stdlib/@python2/abc.pyi index ac14246d44a5..49ec775f91e8 100644 --- a/mypy/typeshed/stdlib/@python2/abc.pyi +++ b/mypy/typeshed/stdlib/@python2/abc.pyi @@ -1,6 +1,6 @@ import _weakrefset from _typeshed import SupportsWrite -from typing import Any, Callable, Dict, Set, Tuple, Type, TypeVar +from typing import Any, Callable, TypeVar _FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) @@ -15,11 +15,11 @@ class ABCMeta(type): _abc_negative_cache: _weakrefset.WeakSet[Any] _abc_negative_cache_version: int _abc_registry: _weakrefset.WeakSet[Any] - def __init__(self, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> None: ... + def __init__(self, name: str, bases: tuple[type, ...], namespace: dict[str, Any]) -> None: ... def __instancecheck__(cls: ABCMeta, instance: Any) -> Any: ... def __subclasscheck__(cls: ABCMeta, subclass: Any) -> Any: ... def _dump_registry(cls: ABCMeta, file: SupportsWrite[Any] | None = ...) -> None: ... - def register(cls: ABCMeta, subclass: Type[Any]) -> None: ... + def register(cls: ABCMeta, subclass: type[Any]) -> None: ... # TODO: The real abc.abstractproperty inherits from "property". class abstractproperty(object): diff --git a/mypy/typeshed/stdlib/@python2/aifc.pyi b/mypy/typeshed/stdlib/@python2/aifc.pyi index 42f20b7466a1..b8049e857304 100644 --- a/mypy/typeshed/stdlib/@python2/aifc.pyi +++ b/mypy/typeshed/stdlib/@python2/aifc.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, List, NamedTuple, Text, Tuple, Union, overload +from typing import IO, Any, NamedTuple, Text, Union, overload from typing_extensions import Literal class Error(Exception): ... @@ -12,7 +12,7 @@ class _aifc_params(NamedTuple): compname: bytes _File = Union[Text, IO[bytes]] -_Marker = Tuple[int, int, bytes] +_Marker = tuple[int, int, bytes] class Aifc_read: def __init__(self, f: _File) -> None: ... @@ -28,7 +28,7 @@ class Aifc_read: def getcomptype(self) -> bytes: ... def getcompname(self) -> bytes: ... def getparams(self) -> _aifc_params: ... - def getmarkers(self) -> List[_Marker] | None: ... + def getmarkers(self) -> list[_Marker] | None: ... def getmark(self, id: int) -> _Marker: ... def setpos(self, pos: int) -> None: ... def readframes(self, nframes: int) -> bytes: ... @@ -50,11 +50,11 @@ class Aifc_write: def setcomptype(self, comptype: bytes, compname: bytes) -> None: ... def getcomptype(self) -> bytes: ... def getcompname(self) -> bytes: ... - def setparams(self, params: Tuple[int, int, int, int, bytes, bytes]) -> None: ... + def setparams(self, params: tuple[int, int, int, int, bytes, bytes]) -> None: ... def getparams(self) -> _aifc_params: ... def setmark(self, id: int, pos: int, name: bytes) -> None: ... def getmark(self, id: int) -> _Marker: ... - def getmarkers(self) -> List[_Marker] | None: ... + def getmarkers(self) -> list[_Marker] | None: ... def tell(self) -> int: ... def writeframesraw(self, data: Any) -> None: ... # Actual type for data is Buffer Protocol def writeframes(self, data: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/argparse.pyi b/mypy/typeshed/stdlib/@python2/argparse.pyi index 4d77f6582c5f..e82a8c621e40 100644 --- a/mypy/typeshed/stdlib/@python2/argparse.pyi +++ b/mypy/typeshed/stdlib/@python2/argparse.pyi @@ -1,22 +1,4 @@ -from typing import ( - IO, - Any, - Callable, - Dict, - Generator, - Iterable, - List, - NoReturn, - Pattern, - Protocol, - Sequence, - Text, - Tuple, - Type, - TypeVar, - Union, - overload, -) +from typing import IO, Any, Callable, Generator, Iterable, NoReturn, Pattern, Protocol, Sequence, Text, TypeVar, Union, overload _T = TypeVar("_T") _ActionT = TypeVar("_ActionT", bound=Action) @@ -39,8 +21,8 @@ class ArgumentError(Exception): # undocumented class _AttributeHolder: - def _get_kwargs(self) -> List[Tuple[str, Any]]: ... - def _get_args(self) -> List[Any]: ... + def _get_kwargs(self) -> list[tuple[str, Any]]: ... + def _get_args(self) -> list[Any]: ... # undocumented class _ActionsContainer: @@ -49,14 +31,14 @@ class _ActionsContainer: argument_default: Any conflict_handler: _Text - _registries: Dict[_Text, Dict[Any, Any]] - _actions: List[Action] - _option_string_actions: Dict[_Text, Action] - _action_groups: List[_ArgumentGroup] - _mutually_exclusive_groups: List[_MutuallyExclusiveGroup] - _defaults: Dict[str, Any] + _registries: dict[_Text, dict[Any, Any]] + _actions: list[Action] + _option_string_actions: dict[_Text, Action] + _action_groups: list[_ArgumentGroup] + _mutually_exclusive_groups: list[_MutuallyExclusiveGroup] + _defaults: dict[str, Any] _negative_number_matcher: Pattern[str] - _has_negative_number_optionals: List[bool] + _has_negative_number_optionals: list[bool] def __init__(self, description: Text | None, prefix_chars: Text, argument_default: Any, conflict_handler: Text) -> None: ... def register(self, registry_name: Text, value: Any, object: Any) -> None: ... def _registry_get(self, registry_name: Text, value: Any, default: Any = ...) -> Any: ... @@ -65,7 +47,7 @@ class _ActionsContainer: def add_argument( self, *name_or_flags: Text, - action: Text | Type[Action] = ..., + action: Text | type[Action] = ..., nargs: int | Text = ..., const: Any = ..., default: Any = ..., @@ -73,7 +55,7 @@ class _ActionsContainer: choices: Iterable[_T] = ..., required: bool = ..., help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., + metavar: Text | tuple[Text, ...] | None = ..., dest: Text | None = ..., version: Text = ..., **kwargs: Any, @@ -83,13 +65,13 @@ class _ActionsContainer: def _add_action(self, action: _ActionT) -> _ActionT: ... def _remove_action(self, action: Action) -> None: ... def _add_container_actions(self, container: _ActionsContainer) -> None: ... - def _get_positional_kwargs(self, dest: Text, **kwargs: Any) -> Dict[str, Any]: ... - def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> Dict[str, Any]: ... - def _pop_action_class(self, kwargs: Any, default: Type[Action] | None = ...) -> Type[Action]: ... - def _get_handler(self) -> Callable[[Action, Iterable[Tuple[Text, Action]]], Any]: ... + def _get_positional_kwargs(self, dest: Text, **kwargs: Any) -> dict[str, Any]: ... + def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> dict[str, Any]: ... + def _pop_action_class(self, kwargs: Any, default: type[Action] | None = ...) -> type[Action]: ... + def _get_handler(self) -> Callable[[Action, Iterable[tuple[Text, Action]]], Any]: ... def _check_conflict(self, action: Action) -> None: ... - def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[Tuple[Text, Action]]) -> NoReturn: ... - def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[Tuple[Text, Action]]) -> None: ... + def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[tuple[Text, Action]]) -> NoReturn: ... + def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[tuple[Text, Action]]) -> None: ... class _FormatterClass(Protocol): def __call__(self, prog: str) -> HelpFormatter: ... @@ -138,8 +120,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): title: Text = ..., description: Text | None = ..., prog: Text = ..., - parser_class: Type[ArgumentParser] = ..., - action: Type[Action] = ..., + parser_class: type[ArgumentParser] = ..., + action: type[Action] = ..., option_string: Text = ..., dest: Text | None = ..., help: Text | None = ..., @@ -151,21 +133,21 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): def format_help(self) -> str: ... def parse_known_args( self, args: Sequence[Text] | None = ..., namespace: Namespace | None = ... - ) -> Tuple[Namespace, List[str]]: ... - def convert_arg_line_to_args(self, arg_line: Text) -> List[str]: ... + ) -> tuple[Namespace, list[str]]: ... + def convert_arg_line_to_args(self, arg_line: Text) -> list[str]: ... def exit(self, status: int = ..., message: Text | None = ...) -> NoReturn: ... def error(self, message: Text) -> NoReturn: ... # undocumented - def _get_optional_actions(self) -> List[Action]: ... - def _get_positional_actions(self) -> List[Action]: ... - def _parse_known_args(self, arg_strings: List[Text], namespace: Namespace) -> Tuple[Namespace, List[str]]: ... - def _read_args_from_files(self, arg_strings: List[Text]) -> List[Text]: ... + def _get_optional_actions(self) -> list[Action]: ... + def _get_positional_actions(self) -> list[Action]: ... + def _parse_known_args(self, arg_strings: list[Text], namespace: Namespace) -> tuple[Namespace, list[str]]: ... + def _read_args_from_files(self, arg_strings: list[Text]) -> list[Text]: ... def _match_argument(self, action: Action, arg_strings_pattern: Text) -> int: ... - def _match_arguments_partial(self, actions: Sequence[Action], arg_strings_pattern: Text) -> List[int]: ... - def _parse_optional(self, arg_string: Text) -> Tuple[Action | None, Text, Text | None] | None: ... - def _get_option_tuples(self, option_string: Text) -> List[Tuple[Action, Text, Text | None]]: ... + def _match_arguments_partial(self, actions: Sequence[Action], arg_strings_pattern: Text) -> list[int]: ... + def _parse_optional(self, arg_string: Text) -> tuple[Action | None, Text, Text | None] | None: ... + def _get_option_tuples(self, option_string: Text) -> list[tuple[Action, Text, Text | None]]: ... def _get_nargs_pattern(self, action: Action) -> _Text: ... - def _get_values(self, action: Action, arg_strings: List[Text]) -> Any: ... + def _get_values(self, action: Action, arg_strings: list[Text]) -> Any: ... def _get_value(self, action: Action, arg_string: Text) -> Any: ... def _check_value(self, action: Action, value: Any) -> None: ... def _get_formatter(self) -> HelpFormatter: ... @@ -184,7 +166,7 @@ class HelpFormatter: _current_section: Any _whitespace_matcher: Pattern[str] _long_break_matcher: Pattern[str] - _Section: Type[Any] # Nested class + _Section: type[Any] # Nested class def __init__( self, prog: Text, indent_increment: int = ..., max_help_position: int = ..., width: int | None = ... ) -> None: ... @@ -208,11 +190,11 @@ class HelpFormatter: def _format_text(self, text: Text) -> _Text: ... def _format_action(self, action: Action) -> _Text: ... def _format_action_invocation(self, action: Action) -> _Text: ... - def _metavar_formatter(self, action: Action, default_metavar: Text) -> Callable[[int], Tuple[_Text, ...]]: ... + def _metavar_formatter(self, action: Action, default_metavar: Text) -> Callable[[int], tuple[_Text, ...]]: ... def _format_args(self, action: Action, default_metavar: Text) -> _Text: ... def _expand_help(self, action: Action) -> _Text: ... def _iter_indented_subactions(self, action: Action) -> Generator[Action, None, None]: ... - def _split_lines(self, text: Text, width: int) -> List[_Text]: ... + def _split_lines(self, text: Text, width: int) -> list[_Text]: ... def _fill_text(self, text: Text, width: int, indent: Text) -> _Text: ... def _get_help_string(self, action: Action) -> _Text | None: ... def _get_default_metavar_for_optional(self, action: Action) -> _Text: ... @@ -232,7 +214,7 @@ class Action(_AttributeHolder): choices: Iterable[Any] | None required: bool help: _Text | None - metavar: _Text | Tuple[_Text, ...] | None + metavar: _Text | tuple[_Text, ...] | None def __init__( self, option_strings: Sequence[Text], @@ -244,7 +226,7 @@ class Action(_AttributeHolder): choices: Iterable[_T] | None = ..., required: bool = ..., help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., + metavar: Text | tuple[Text, ...] | None = ..., ) -> None: ... def __call__( self, parser: ArgumentParser, namespace: Namespace, values: Text | Sequence[Any] | None, option_string: Text | None = ... @@ -266,7 +248,7 @@ class FileType: # undocumented class _ArgumentGroup(_ActionsContainer): title: _Text | None - _group_actions: List[Action] + _group_actions: list[Action] def __init__( self, container: _ActionsContainer, title: Text | None = ..., description: Text | None = ..., **kwargs: Any ) -> None: ... @@ -290,7 +272,7 @@ class _StoreConstAction(Action): default: Any = ..., required: bool = ..., help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., + metavar: Text | tuple[Text, ...] | None = ..., ) -> None: ... # undocumented @@ -318,7 +300,7 @@ class _AppendConstAction(Action): default: Any = ..., required: bool = ..., help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., + metavar: Text | tuple[Text, ...] | None = ..., ) -> None: ... # undocumented @@ -342,24 +324,24 @@ class _VersionAction(Action): # undocumented class _SubParsersAction(Action): - _ChoicesPseudoAction: Type[Any] # nested class + _ChoicesPseudoAction: type[Any] # nested class _prog_prefix: _Text - _parser_class: Type[ArgumentParser] - _name_parser_map: Dict[_Text, ArgumentParser] - choices: Dict[_Text, ArgumentParser] - _choices_actions: List[Action] + _parser_class: type[ArgumentParser] + _name_parser_map: dict[_Text, ArgumentParser] + choices: dict[_Text, ArgumentParser] + _choices_actions: list[Action] def __init__( self, option_strings: Sequence[Text], prog: Text, - parser_class: Type[ArgumentParser], + parser_class: type[ArgumentParser], dest: Text = ..., help: Text | None = ..., - metavar: Text | Tuple[Text, ...] | None = ..., + metavar: Text | tuple[Text, ...] | None = ..., ) -> None: ... # TODO: Type keyword args properly. def add_parser(self, name: Text, **kwargs: Any) -> ArgumentParser: ... - def _get_subactions(self) -> List[Action]: ... + def _get_subactions(self) -> list[Action]: ... # undocumented class ArgumentTypeError(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/array.pyi b/mypy/typeshed/stdlib/@python2/array.pyi index 39670fe734fc..ea9b21a8eccb 100644 --- a/mypy/typeshed/stdlib/@python2/array.pyi +++ b/mypy/typeshed/stdlib/@python2/array.pyi @@ -1,4 +1,4 @@ -from typing import Any, BinaryIO, Generic, Iterable, List, MutableSequence, Text, Tuple, TypeVar, Union, overload +from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, Text, TypeVar, Union, overload from typing_extensions import Literal _IntTypeCode = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] @@ -20,12 +20,12 @@ class array(MutableSequence[_T], Generic[_T]): @overload def __init__(self, typecode: str, __initializer: bytes | Iterable[_T] = ...) -> None: ... def append(self, __v: _T) -> None: ... - def buffer_info(self) -> Tuple[int, int]: ... + def buffer_info(self) -> tuple[int, int]: ... def byteswap(self) -> None: ... def count(self, __v: Any) -> int: ... def extend(self, __bb: Iterable[_T]) -> None: ... def fromfile(self, __f: BinaryIO, __n: int) -> None: ... - def fromlist(self, __list: List[_T]) -> None: ... + def fromlist(self, __list: list[_T]) -> None: ... def fromunicode(self, __ustr: str) -> None: ... def index(self, __v: _T) -> int: ... # type: ignore # Overrides Sequence def insert(self, __i: int, __v: _T) -> None: ... @@ -34,7 +34,7 @@ class array(MutableSequence[_T], Generic[_T]): def remove(self, __v: Any) -> None: ... def reverse(self) -> None: ... def tofile(self, __f: BinaryIO) -> None: ... - def tolist(self) -> List[_T]: ... + def tolist(self) -> list[_T]: ... def tounicode(self) -> str: ... def write(self, f: BinaryIO) -> None: ... def fromstring(self, __buffer: bytes) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/asynchat.pyi b/mypy/typeshed/stdlib/@python2/asynchat.pyi index 0f5526d71b1d..e55dbf258a14 100644 --- a/mypy/typeshed/stdlib/@python2/asynchat.pyi +++ b/mypy/typeshed/stdlib/@python2/asynchat.pyi @@ -1,7 +1,7 @@ import asyncore import socket from abc import abstractmethod -from typing import Sequence, Tuple +from typing import Sequence class simple_producer: def __init__(self, data: bytes, buffer_size: int = ...) -> None: ... @@ -34,4 +34,4 @@ class fifo: def is_empty(self) -> bool: ... def first(self) -> bytes: ... def push(self, data: bytes | simple_producer) -> None: ... - def pop(self) -> Tuple[int, bytes]: ... + def pop(self) -> tuple[int, bytes]: ... diff --git a/mypy/typeshed/stdlib/@python2/asyncore.pyi b/mypy/typeshed/stdlib/@python2/asyncore.pyi index 95acf9b706d3..a7ef4df1f0a9 100644 --- a/mypy/typeshed/stdlib/@python2/asyncore.pyi +++ b/mypy/typeshed/stdlib/@python2/asyncore.pyi @@ -1,12 +1,12 @@ import sys from _typeshed import FileDescriptorLike from socket import SocketType -from typing import Any, Dict, Optional, Tuple, overload +from typing import Any, Optional, overload # cyclic dependence with asynchat -_maptype = Dict[int, Any] +_maptype = dict[int, Any] -socket_map: _maptype = ... # undocumented +socket_map: _maptype # undocumented class ExitNow(Exception): ... @@ -40,9 +40,9 @@ class dispatcher: def readable(self) -> bool: ... def writable(self) -> bool: ... def listen(self, num: int) -> None: ... - def bind(self, addr: Tuple[Any, ...] | str) -> None: ... - def connect(self, address: Tuple[Any, ...] | str) -> None: ... - def accept(self) -> Tuple[SocketType, Any] | None: ... + def bind(self, addr: tuple[Any, ...] | str) -> None: ... + def connect(self, address: tuple[Any, ...] | str) -> None: ... + def accept(self) -> tuple[SocketType, Any] | None: ... def send(self, data: bytes) -> int: ... def recv(self, buffer_size: int) -> bytes: ... def close(self) -> None: ... @@ -73,7 +73,7 @@ class dispatcher: @overload def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... def gettimeout(self) -> float: ... - def ioctl(self, control: object, option: Tuple[int, int, int]) -> None: ... + def ioctl(self, control: object, option: tuple[int, int, int]) -> None: ... # TODO the return value may be BinaryIO or TextIO, depending on mode def makefile( self, mode: str = ..., buffering: int = ..., encoding: str = ..., errors: str = ..., newline: str = ... @@ -83,7 +83,7 @@ class dispatcher: def recvfrom_into(self, buffer: bytes, nbytes: int, flags: int = ...) -> Any: ... def recv_into(self, buffer: bytes, nbytes: int, flags: int = ...) -> Any: ... def sendall(self, data: bytes, flags: int = ...) -> None: ... - def sendto(self, data: bytes, address: Tuple[str, int] | str, flags: int = ...) -> int: ... + def sendto(self, data: bytes, address: tuple[str, int] | str, flags: int = ...) -> int: ... def setblocking(self, flag: bool) -> None: ... def settimeout(self, value: float | None) -> None: ... def setsockopt(self, level: int, optname: int, value: int | bytes) -> None: ... @@ -96,7 +96,7 @@ class dispatcher_with_send(dispatcher): # incompatible signature: # def send(self, data: bytes) -> Optional[int]: ... -def compact_traceback() -> Tuple[Tuple[str, str, str], type, type, str]: ... +def compact_traceback() -> tuple[tuple[str, str, str], type, type, str]: ... def close_all(map: _maptype | None = ..., ignore_all: bool = ...) -> None: ... if sys.platform != "win32": diff --git a/mypy/typeshed/stdlib/@python2/audioop.pyi b/mypy/typeshed/stdlib/@python2/audioop.pyi index 71671afe487e..b08731b85b0b 100644 --- a/mypy/typeshed/stdlib/@python2/audioop.pyi +++ b/mypy/typeshed/stdlib/@python2/audioop.pyi @@ -1,12 +1,10 @@ -from typing import Tuple - -AdpcmState = Tuple[int, int] -RatecvState = Tuple[int, Tuple[Tuple[int, int], ...]] +AdpcmState = tuple[int, int] +RatecvState = tuple[int, tuple[tuple[int, int], ...]] class error(Exception): ... def add(__fragment1: bytes, __fragment2: bytes, __width: int) -> bytes: ... -def adpcm2lin(__fragment: bytes, __width: int, __state: AdpcmState | None) -> Tuple[bytes, AdpcmState]: ... +def adpcm2lin(__fragment: bytes, __width: int, __state: AdpcmState | None) -> tuple[bytes, AdpcmState]: ... def alaw2lin(__fragment: bytes, __width: int) -> bytes: ... def avg(__fragment: bytes, __width: int) -> int: ... def avgpp(__fragment: bytes, __width: int) -> int: ... @@ -14,16 +12,16 @@ def bias(__fragment: bytes, __width: int, __bias: int) -> bytes: ... def byteswap(__fragment: bytes, __width: int) -> bytes: ... def cross(__fragment: bytes, __width: int) -> int: ... def findfactor(__fragment: bytes, __reference: bytes) -> float: ... -def findfit(__fragment: bytes, __reference: bytes) -> Tuple[int, float]: ... +def findfit(__fragment: bytes, __reference: bytes) -> tuple[int, float]: ... def findmax(__fragment: bytes, __length: int) -> int: ... def getsample(__fragment: bytes, __width: int, __index: int) -> int: ... -def lin2adpcm(__fragment: bytes, __width: int, __state: AdpcmState | None) -> Tuple[bytes, AdpcmState]: ... +def lin2adpcm(__fragment: bytes, __width: int, __state: AdpcmState | None) -> tuple[bytes, AdpcmState]: ... def lin2alaw(__fragment: bytes, __width: int) -> bytes: ... def lin2lin(__fragment: bytes, __width: int, __newwidth: int) -> bytes: ... def lin2ulaw(__fragment: bytes, __width: int) -> bytes: ... def max(__fragment: bytes, __width: int) -> int: ... def maxpp(__fragment: bytes, __width: int) -> int: ... -def minmax(__fragment: bytes, __width: int) -> Tuple[int, int]: ... +def minmax(__fragment: bytes, __width: int) -> tuple[int, int]: ... def mul(__fragment: bytes, __width: int, __factor: float) -> bytes: ... def ratecv( __fragment: bytes, @@ -34,7 +32,7 @@ def ratecv( __state: RatecvState | None, __weightA: int = ..., __weightB: int = ..., -) -> Tuple[bytes, RatecvState]: ... +) -> tuple[bytes, RatecvState]: ... def reverse(__fragment: bytes, __width: int) -> bytes: ... def rms(__fragment: bytes, __width: int) -> int: ... def tomono(__fragment: bytes, __width: int, __lfactor: float, __rfactor: float) -> bytes: ... diff --git a/mypy/typeshed/stdlib/@python2/bdb.pyi b/mypy/typeshed/stdlib/@python2/bdb.pyi index 5bee9dadb928..3610bed14109 100644 --- a/mypy/typeshed/stdlib/@python2/bdb.pyi +++ b/mypy/typeshed/stdlib/@python2/bdb.pyi @@ -1,19 +1,19 @@ from types import CodeType, FrameType, TracebackType -from typing import IO, Any, Callable, Dict, Iterable, List, Mapping, Set, SupportsInt, Tuple, Type, TypeVar +from typing import IO, Any, Callable, Iterable, Mapping, SupportsInt, TypeVar _T = TypeVar("_T") _TraceDispatch = Callable[[FrameType, str, Any], Any] # TODO: Recursive type -_ExcInfo = Tuple[Type[BaseException], BaseException, FrameType] +_ExcInfo = tuple[type[BaseException], BaseException, FrameType] -GENERATOR_AND_COROUTINE_FLAGS: int = ... +GENERATOR_AND_COROUTINE_FLAGS: int class BdbQuit(Exception): ... class Bdb: - skip: Set[str] | None - breaks: Dict[str, List[int]] - fncache: Dict[str, str] + skip: set[str] | None + breaks: dict[str, list[int]] + fncache: dict[str, str] frame_returning: FrameType | None botframe: FrameType | None quitting: bool @@ -53,21 +53,21 @@ class Bdb: def clear_all_breaks(self) -> None: ... def get_bpbynumber(self, arg: SupportsInt) -> Breakpoint: ... def get_break(self, filename: str, lineno: int) -> bool: ... - def get_breaks(self, filename: str, lineno: int) -> List[Breakpoint]: ... - def get_file_breaks(self, filename: str) -> List[Breakpoint]: ... - def get_all_breaks(self) -> List[Breakpoint]: ... - def get_stack(self, f: FrameType | None, t: TracebackType | None) -> Tuple[List[Tuple[FrameType, int]], int]: ... + def get_breaks(self, filename: str, lineno: int) -> list[Breakpoint]: ... + def get_file_breaks(self, filename: str) -> list[Breakpoint]: ... + def get_all_breaks(self) -> list[Breakpoint]: ... + def get_stack(self, f: FrameType | None, t: TracebackType | None) -> tuple[list[tuple[FrameType, int]], int]: ... def format_stack_entry(self, frame_lineno: int, lprefix: str = ...) -> str: ... - def run(self, cmd: str | CodeType, globals: Dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... - def runeval(self, expr: str, globals: Dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... - def runctx(self, cmd: str | CodeType, globals: Dict[str, Any] | None, locals: Mapping[str, Any] | None) -> None: ... + def run(self, cmd: str | CodeType, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... + def runeval(self, expr: str, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... + def runctx(self, cmd: str | CodeType, globals: dict[str, Any] | None, locals: Mapping[str, Any] | None) -> None: ... def runcall(self, __func: Callable[..., _T], *args: Any, **kwds: Any) -> _T | None: ... class Breakpoint: next: int = ... - bplist: Dict[Tuple[str, int], List[Breakpoint]] = ... - bpbynumber: List[Breakpoint | None] = ... + bplist: dict[tuple[str, int], list[Breakpoint]] = ... + bpbynumber: list[Breakpoint | None] = ... funcname: str | None func_first_executable_line: int | None @@ -87,8 +87,7 @@ class Breakpoint: def disable(self) -> None: ... def bpprint(self, out: IO[str] | None = ...) -> None: ... def bpformat(self) -> str: ... - def __str__(self) -> str: ... def checkfuncname(b: Breakpoint, frame: FrameType) -> bool: ... -def effective(file: str, line: int, frame: FrameType) -> Tuple[Breakpoint, bool] | Tuple[None, None]: ... +def effective(file: str, line: int, frame: FrameType) -> tuple[Breakpoint, bool] | tuple[None, None]: ... def set_trace() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/binhex.pyi b/mypy/typeshed/stdlib/@python2/binhex.pyi index 02d094faf923..4e295b8ed903 100644 --- a/mypy/typeshed/stdlib/@python2/binhex.pyi +++ b/mypy/typeshed/stdlib/@python2/binhex.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Tuple, Union +from typing import IO, Any, Union class Error(Exception): ... @@ -12,7 +12,7 @@ class FInfo: Creator: str Flags: int -_FileInfoTuple = Tuple[str, FInfo, int, int] +_FileInfoTuple = tuple[str, FInfo, int, int] _FileHandleUnion = Union[str, IO[bytes]] def getfileinfo(name: str) -> _FileInfoTuple: ... diff --git a/mypy/typeshed/stdlib/@python2/builtins.pyi b/mypy/typeshed/stdlib/@python2/builtins.pyi index fad8b2b4e7d8..d5e1c2e5e53b 100644 --- a/mypy/typeshed/stdlib/@python2/builtins.pyi +++ b/mypy/typeshed/stdlib/@python2/builtins.pyi @@ -1,7 +1,7 @@ # True and False are deliberately omitted because they are keywords in # Python 3, and stub files conform to Python 3 syntax. -from _typeshed import ReadableBuffer, SupportsKeysAndGetItem, SupportsWrite +from _typeshed import ReadableBuffer, Self, SupportsKeysAndGetItem, SupportsWrite from abc import ABCMeta from ast import mod from types import CodeType @@ -13,14 +13,11 @@ from typing import ( ByteString, Callable, Container, - Dict, - FrozenSet, Generic, ItemsView, Iterable, Iterator, KeysView, - List, Mapping, MutableMapping, MutableSequence, @@ -29,15 +26,12 @@ from typing import ( Protocol, Reversible, Sequence, - Set, Sized, SupportsAbs, SupportsComplex, SupportsFloat, SupportsInt, Text, - Tuple, - Type, TypeVar, ValuesView, overload, @@ -60,70 +54,68 @@ _T2 = TypeVar("_T2") _T3 = TypeVar("_T3") _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") -_TT = TypeVar("_TT", bound="type") -_TBE = TypeVar("_TBE", bound="BaseException") +_TT = TypeVar("_TT", bound=type) class object: __doc__: str | None - __dict__: Dict[str, Any] - __slots__: Text | Iterable[Text] + __dict__: dict[str, Any] __module__: str @property - def __class__(self: _T) -> Type[_T]: ... + def __class__(self: _T) -> type[_T]: ... @__class__.setter - def __class__(self, __type: Type[object]) -> None: ... # noqa: F811 + def __class__(self, __type: type[object]) -> None: ... # noqa: F811 def __init__(self) -> None: ... def __new__(cls) -> Any: ... 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 __str__(self) -> str: ... # noqa Y029 + def __repr__(self) -> str: ... # noqa Y029 def __hash__(self) -> int: ... 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_ex__(self, protocol: int) -> str | Tuple[Any, ...]: ... + def __reduce__(self) -> str | tuple[Any, ...]: ... + def __reduce_ex__(self, protocol: int) -> str | tuple[Any, ...]: ... class staticmethod(object): # Special, only valid as a decorator. __func__: Callable[..., Any] def __init__(self, f: Callable[..., Any]) -> None: ... - def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, obj: _T, type: Type[_T] | None = ...) -> Callable[..., Any]: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... + def __get__(self, obj: _T, type: type[_T] | None = ...) -> Callable[..., Any]: ... class classmethod(object): # Special, only valid as a decorator. __func__: Callable[..., Any] def __init__(self, f: Callable[..., Any]) -> None: ... - def __new__(cls: Type[_T], *args: Any, **kwargs: Any) -> _T: ... - def __get__(self, obj: _T, type: Type[_T] | None = ...) -> Callable[..., Any]: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... + def __get__(self, obj: _T, type: type[_T] | None = ...) -> Callable[..., Any]: ... class type(object): __base__: type - __bases__: Tuple[type, ...] + __bases__: tuple[type, ...] __basicsize__: int - __dict__: Dict[str, Any] + __dict__: dict[str, Any] __dictoffset__: int __flags__: int __itemsize__: int __module__: str - __mro__: Tuple[type, ...] + __mro__: tuple[type, ...] __name__: str __weakrefoffset__: int @overload def __init__(self, o: object) -> None: ... @overload - def __init__(self, name: str, bases: Tuple[type, ...], dict: Dict[str, Any]) -> None: ... + def __init__(self, name: str, bases: tuple[type, ...], dict: dict[str, Any]) -> None: ... @overload def __new__(cls, o: object) -> type: ... @overload - def __new__(cls, name: str, bases: Tuple[type, ...], namespace: Dict[str, Any]) -> type: ... + 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]: ... + def __subclasses__(self: _TT) -> list[_TT]: ... # 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 mro(self) -> list[type]: ... def __instancecheck__(self, instance: Any) -> bool: ... def __subclasscheck__(self, subclass: type) -> bool: ... @@ -135,9 +127,9 @@ class super(object): class int: @overload - def __new__(cls: Type[_T], x: Text | bytes | SupportsInt | _SupportsIndex | _SupportsTrunc = ...) -> _T: ... + def __new__(cls: type[Self], x: Text | bytes | SupportsInt | _SupportsIndex | _SupportsTrunc = ...) -> Self: ... @overload - def __new__(cls: Type[_T], x: Text | bytes | bytearray, base: int) -> _T: ... + def __new__(cls: type[Self], x: Text | bytes | bytearray, base: int) -> Self: ... @property def real(self) -> int: ... @property @@ -155,7 +147,7 @@ class int: def __div__(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 __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: ... @@ -163,7 +155,7 @@ class int: def __rdiv__(self, x: int) -> int: ... def __rtruediv__(self, x: int) -> float: ... def __rmod__(self, x: int) -> int: ... - def __rdivmod__(self, x: int) -> Tuple[int, int]: ... + def __rdivmod__(self, x: int) -> tuple[int, int]: ... @overload def __pow__(self, __x: Literal[2], __modulo: int | None = ...) -> int: ... @overload @@ -183,14 +175,13 @@ class int: def __pos__(self) -> int: ... def __invert__(self) -> int: ... def __trunc__(self) -> int: ... - def __getnewargs__(self) -> Tuple[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 __str__(self) -> str: ... def __float__(self) -> float: ... def __int__(self) -> int: ... def __abs__(self) -> int: ... @@ -199,8 +190,8 @@ class int: def __index__(self) -> int: ... class float: - def __new__(cls: Type[_T], x: SupportsFloat | _SupportsIndex | Text | bytes | bytearray = ...) -> _T: ... - def as_integer_ratio(self) -> Tuple[int, int]: ... + def __new__(cls: type[Self], x: SupportsFloat | _SupportsIndex | Text | bytes | bytearray = ...) -> Self: ... + def as_integer_ratio(self) -> tuple[int, int]: ... def hex(self) -> str: ... def is_integer(self) -> bool: ... @classmethod @@ -217,7 +208,7 @@ class float: def __div__(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 __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 @@ -228,9 +219,9 @@ class float: def __rdiv__(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 __rdivmod__(self, x: float) -> tuple[float, float]: ... def __rpow__(self, x: float, mod: None = ...) -> float: ... - def __getnewargs__(self) -> Tuple[float]: ... + def __getnewargs__(self) -> tuple[float]: ... def __trunc__(self) -> int: ... def __eq__(self, x: object) -> bool: ... def __ne__(self, x: object) -> bool: ... @@ -240,7 +231,6 @@ class float: def __ge__(self, x: float) -> bool: ... def __neg__(self) -> float: ... def __pos__(self) -> float: ... - def __str__(self) -> str: ... def __int__(self) -> int: ... def __float__(self) -> float: ... def __abs__(self) -> float: ... @@ -249,9 +239,9 @@ class float: class complex: @overload - def __new__(cls: Type[_T], real: float = ..., imag: float = ...) -> _T: ... + def __new__(cls: type[Self], real: float = ..., imag: float = ...) -> Self: ... @overload - def __new__(cls: Type[_T], real: str | SupportsComplex | _SupportsIndex) -> _T: ... + def __new__(cls: type[Self], real: str | SupportsComplex | _SupportsIndex) -> Self: ... @property def real(self) -> float: ... @property @@ -273,7 +263,6 @@ class complex: def __ne__(self, x: object) -> bool: ... def __neg__(self) -> complex: ... def __pos__(self) -> complex: ... - def __str__(self) -> str: ... def __complex__(self) -> complex: ... def __abs__(self) -> float: ... def __hash__(self) -> int: ... @@ -293,7 +282,7 @@ class unicode(basestring, Sequence[unicode]): def count(self, x: unicode) -> int: ... def decode(self, encoding: unicode = ..., errors: unicode = ...) -> unicode: ... def encode(self, encoding: unicode = ..., errors: unicode = ...) -> str: ... - def endswith(self, __suffix: unicode | Tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def endswith(self, __suffix: unicode | tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def expandtabs(self, tabsize: int = ...) -> unicode: ... def find(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... def format(self, *args: object, **kwargs: object) -> unicode: ... @@ -313,21 +302,21 @@ class unicode(basestring, Sequence[unicode]): def ljust(self, width: int, fillchar: unicode = ...) -> unicode: ... def lower(self) -> unicode: ... def lstrip(self, chars: unicode = ...) -> unicode: ... - def partition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def partition(self, sep: unicode) -> tuple[unicode, unicode, unicode]: ... def replace(self, old: unicode, new: unicode, count: int = ...) -> unicode: ... def rfind(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... def rindex(self, sub: unicode, start: int = ..., end: int = ...) -> int: ... def rjust(self, width: int, fillchar: unicode = ...) -> unicode: ... - def rpartition(self, sep: unicode) -> Tuple[unicode, unicode, unicode]: ... - def rsplit(self, sep: unicode | None = ..., maxsplit: int = ...) -> List[unicode]: ... + def rpartition(self, sep: unicode) -> tuple[unicode, unicode, unicode]: ... + def rsplit(self, sep: unicode | None = ..., maxsplit: int = ...) -> list[unicode]: ... def rstrip(self, chars: unicode = ...) -> unicode: ... - def split(self, sep: unicode | None = ..., maxsplit: int = ...) -> List[unicode]: ... - def splitlines(self, keepends: bool = ...) -> List[unicode]: ... - def startswith(self, __prefix: unicode | Tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def split(self, sep: unicode | None = ..., maxsplit: int = ...) -> list[unicode]: ... + def splitlines(self, keepends: bool = ...) -> list[unicode]: ... + def startswith(self, __prefix: unicode | tuple[unicode, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def strip(self, chars: unicode = ...) -> unicode: ... def swapcase(self) -> unicode: ... def title(self) -> unicode: ... - def translate(self, table: Dict[int, Any] | unicode) -> unicode: ... + def translate(self, table: dict[int, Any] | unicode) -> unicode: ... def upper(self) -> unicode: ... def zfill(self, width: int) -> unicode: ... @overload @@ -349,12 +338,10 @@ class unicode(basestring, Sequence[unicode]): # The argument type is incompatible with Sequence def __contains__(self, s: unicode | bytes) -> bool: ... # type: ignore def __iter__(self) -> Iterator[unicode]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... def __int__(self) -> int: ... def __float__(self) -> float: ... def __hash__(self) -> int: ... - def __getnewargs__(self) -> Tuple[unicode]: ... + def __getnewargs__(self) -> tuple[unicode]: ... class _FormatMapMapping(Protocol): def __getitem__(self, __key: str) -> Any: ... @@ -366,7 +353,7 @@ class str(Sequence[str], basestring): def count(self, x: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... - def endswith(self, __suffix: Text | Tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def endswith(self, __suffix: Text | tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def expandtabs(self, tabsize: int = ...) -> str: ... def find(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... def format(self, *args: object, **kwargs: object) -> str: ... @@ -387,35 +374,35 @@ class str(Sequence[str], basestring): @overload def lstrip(self, __chars: unicode) -> unicode: ... @overload - def partition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + def partition(self, __sep: bytearray) -> tuple[str, bytearray, str]: ... @overload - def partition(self, __sep: str) -> Tuple[str, str, str]: ... + def partition(self, __sep: str) -> tuple[str, str, str]: ... @overload - def partition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def partition(self, __sep: unicode) -> tuple[unicode, unicode, unicode]: ... def replace(self, __old: AnyStr, __new: AnyStr, __count: int = ...) -> AnyStr: ... def rfind(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... def rindex(self, sub: Text, __start: int | None = ..., __end: int | None = ...) -> int: ... def rjust(self, __width: int, __fillchar: str = ...) -> str: ... @overload - def rpartition(self, __sep: bytearray) -> Tuple[str, bytearray, str]: ... + def rpartition(self, __sep: bytearray) -> tuple[str, bytearray, str]: ... @overload - def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... + def rpartition(self, __sep: str) -> tuple[str, str, str]: ... @overload - def rpartition(self, __sep: unicode) -> Tuple[unicode, unicode, unicode]: ... + def rpartition(self, __sep: unicode) -> tuple[unicode, unicode, unicode]: ... @overload - def rsplit(self, sep: str | None = ..., maxsplit: int = ...) -> List[str]: ... + def rsplit(self, sep: str | None = ..., maxsplit: int = ...) -> list[str]: ... @overload - def rsplit(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... + def rsplit(self, sep: unicode, maxsplit: int = ...) -> list[unicode]: ... @overload def rstrip(self, __chars: str = ...) -> str: ... @overload def rstrip(self, __chars: unicode) -> unicode: ... @overload - def split(self, sep: str | None = ..., maxsplit: int = ...) -> List[str]: ... + def split(self, sep: str | None = ..., maxsplit: int = ...) -> list[str]: ... @overload - def split(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... - def splitlines(self, keepends: bool = ...) -> List[str]: ... - def startswith(self, __prefix: Text | Tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def split(self, sep: unicode, maxsplit: int = ...) -> list[unicode]: ... + def splitlines(self, keepends: bool = ...) -> list[str]: ... + def startswith(self, __prefix: Text | tuple[Text, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... @overload def strip(self, __chars: str = ...) -> str: ... @overload @@ -440,10 +427,8 @@ class str(Sequence[str], basestring): def __mod__(self, x: Any) -> str: ... def __mul__(self, n: int) -> str: ... def __ne__(self, x: object) -> bool: ... - def __repr__(self) -> str: ... def __rmul__(self, n: int) -> str: ... - def __str__(self) -> str: ... - def __getnewargs__(self) -> Tuple[str]: ... + def __getnewargs__(self) -> tuple[str]: ... def __getslice__(self, start: int, stop: int) -> str: ... def __float__(self) -> float: ... def __int__(self) -> int: ... @@ -465,7 +450,7 @@ class bytearray(MutableSequence[int], ByteString): def center(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... def count(self, __sub: str) -> int: ... def decode(self, encoding: Text = ..., errors: Text = ...) -> str: ... - def endswith(self, __suffix: bytes | Tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def endswith(self, __suffix: bytes | tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def expandtabs(self, tabsize: int = ...) -> bytearray: ... def extend(self, iterable: str | Iterable[int]) -> None: ... def find(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... @@ -482,17 +467,17 @@ class bytearray(MutableSequence[int], ByteString): def ljust(self, __width: int, __fillchar: str = ...) -> bytearray: ... def lower(self) -> bytearray: ... def lstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def partition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... + def partition(self, __sep: bytes) -> tuple[bytearray, bytearray, bytearray]: ... def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytearray: ... def rfind(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... def rindex(self, __sub: bytes, __start: int = ..., __end: int = ...) -> int: ... def rjust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... - def rpartition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... - def rsplit(self, sep: bytes | None = ..., maxsplit: int = ...) -> List[bytearray]: ... + def rpartition(self, __sep: bytes) -> tuple[bytearray, bytearray, bytearray]: ... + def rsplit(self, sep: bytes | None = ..., maxsplit: int = ...) -> list[bytearray]: ... def rstrip(self, __bytes: bytes | None = ...) -> bytearray: ... - def split(self, sep: bytes | None = ..., maxsplit: int = ...) -> List[bytearray]: ... - def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... - def startswith(self, __prefix: bytes | Tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... + def split(self, sep: bytes | None = ..., maxsplit: int = ...) -> list[bytearray]: ... + def splitlines(self, keepends: bool = ...) -> list[bytearray]: ... + def startswith(self, __prefix: bytes | tuple[bytes, ...], __start: int | None = ..., __end: int | None = ...) -> bool: ... def strip(self, __bytes: bytes | None = ...) -> bytearray: ... def swapcase(self) -> bytearray: ... def title(self) -> bytearray: ... @@ -503,8 +488,6 @@ class bytearray(MutableSequence[int], ByteString): def fromhex(cls, __string: str) -> bytearray: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... def __int__(self) -> int: ... def __float__(self) -> float: ... __hash__: None # type: ignore @@ -534,9 +517,9 @@ class bytearray(MutableSequence[int], ByteString): class memoryview(Sized, Container[str]): format: str itemsize: int - shape: Tuple[int, ...] | None - strides: Tuple[int, ...] | None - suboffsets: Tuple[int, ...] | None + shape: tuple[int, ...] | None + strides: tuple[int, ...] | None + suboffsets: tuple[int, ...] | None readonly: bool ndim: int def __init__(self, obj: ReadableBuffer) -> None: ... @@ -552,11 +535,11 @@ class memoryview(Sized, Container[str]): @overload def __setitem__(self, i: int, o: int) -> None: ... def tobytes(self) -> bytes: ... - def tolist(self) -> List[int]: ... + def tolist(self) -> list[int]: ... @final class bool(int): - def __new__(cls: Type[_T], __o: object = ...) -> _T: ... + def __new__(cls: type[Self], __o: object = ...) -> Self: ... @overload def __and__(self, x: bool) -> bool: ... @overload @@ -581,7 +564,7 @@ class bool(int): def __rxor__(self, x: bool) -> bool: ... @overload def __rxor__(self, x: int) -> int: ... - def __getnewargs__(self) -> Tuple[int]: ... + def __getnewargs__(self) -> tuple[int]: ... class slice(object): start: Any @@ -592,27 +575,27 @@ class slice(object): @overload def __init__(self, start: Any, stop: Any, step: Any = ...) -> None: ... __hash__: None # type: ignore - def indices(self, len: int) -> Tuple[int, int, int]: ... + def indices(self, len: int) -> 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[Self], iterable: Iterable[_T_co] = ...) -> Self: ... def __len__(self) -> int: ... def __contains__(self, x: object) -> bool: ... @overload 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[Any, ...]) -> Tuple[Any, ...]: ... - def __mul__(self, n: int) -> Tuple[_T_co, ...]: ... - def __rmul__(self, n: int) -> Tuple[_T_co, ...]: ... + def __add__(self, x: tuple[Any, ...]) -> tuple[Any, ...]: ... + def __mul__(self, n: int) -> tuple[_T_co, ...]: ... + def __rmul__(self, n: int) -> tuple[_T_co, ...]: ... def count(self, __value: Any) -> int: ... def index(self, __value: Any) -> int: ... @@ -638,30 +621,29 @@ class list(MutableSequence[_T], Generic[_T]): def sort(self, cmp: Callable[[_T, _T], Any] = ..., key: Callable[[_T], Any] = ..., reverse: bool = ...) -> None: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... __hash__: None # type: ignore @overload def __getitem__(self, i: int) -> _T: ... @overload - def __getitem__(self, s: slice) -> List[_T]: ... + def __getitem__(self, s: slice) -> list[_T]: ... @overload def __setitem__(self, i: int, o: _T) -> None: ... @overload def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... def __delitem__(self, i: int | slice) -> None: ... - def __getslice__(self, start: int, stop: int) -> List[_T]: ... + def __getslice__(self, start: int, stop: int) -> list[_T]: ... def __setslice__(self, start: int, stop: int, o: Sequence[_T]) -> None: ... def __delslice__(self, start: int, stop: int) -> None: ... - def __add__(self, x: List[_T]) -> List[_T]: ... - def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... - def __mul__(self, n: int) -> List[_T]: ... - def __rmul__(self, n: int) -> List[_T]: ... + def __add__(self, x: list[_T]) -> list[_T]: ... + def __iadd__(self: Self, x: Iterable[_T]) -> Self: ... + def __mul__(self, n: int) -> list[_T]: ... + def __rmul__(self, n: int) -> list[_T]: ... 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: ... class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): # NOTE: Keyword arguments are special. If they are used, _KT must include @@ -671,76 +653,74 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @overload def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... @overload - def __init__(self, iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... - def __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... + def __init__(self, iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... def has_key(self, k: _KT) -> bool: ... def clear(self) -> None: ... - def copy(self) -> Dict[_KT, _VT]: ... - def popitem(self) -> Tuple[_KT, _VT]: ... + def copy(self) -> dict[_KT, _VT]: ... + def popitem(self) -> tuple[_KT, _VT]: ... def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ... @overload def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... @overload - def update(self, __m: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def update(self, __m: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... @overload def update(self, **kwargs: _VT) -> None: ... def iterkeys(self) -> Iterator[_KT]: ... def itervalues(self) -> Iterator[_VT]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def iteritems(self) -> Iterator[tuple[_KT, _VT]]: ... def viewkeys(self) -> KeysView[_KT]: ... def viewvalues(self) -> ValuesView[_VT]: ... def viewitems(self) -> ItemsView[_KT, _VT]: ... @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T]) -> Dict[_T, Any]: ... + def fromkeys(cls, __iterable: Iterable[_T]) -> dict[_T, Any]: ... @classmethod @overload - def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> Dict[_T, _S]: ... + 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 __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... __hash__: None # type: ignore class set(MutableSet[_T], Generic[_T]): def __init__(self, iterable: Iterable[_T] = ...) -> None: ... def add(self, element: _T) -> None: ... def clear(self) -> None: ... - def copy(self) -> Set[_T]: ... - def difference(self, *s: Iterable[Any]) -> Set[_T]: ... + def copy(self) -> set[_T]: ... + def difference(self, *s: Iterable[Any]) -> set[_T]: ... def difference_update(self, *s: Iterable[Any]) -> None: ... def discard(self, element: _T) -> None: ... - def intersection(self, *s: Iterable[Any]) -> Set[_T]: ... + def 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 pop(self) -> _T: ... def remove(self, element: _T) -> None: ... - def symmetric_difference(self, s: Iterable[_T]) -> Set[_T]: ... + 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 union(self, *s: Iterable[_T]) -> set[_T]: ... def update(self, *s: Iterable[_T]) -> None: ... def __len__(self) -> int: ... 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 __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]: ... @overload - def __sub__(self: Set[str], s: AbstractSet[Text | None]) -> Set[_T]: ... + def __sub__(self: set[str], s: AbstractSet[Text | None]) -> set[_T]: ... @overload - def __sub__(self, s: AbstractSet[_T | None]) -> Set[_T]: ... + def __sub__(self, s: AbstractSet[_T | None]) -> set[_T]: ... @overload # type: ignore - def __isub__(self: Set[str], s: AbstractSet[Text | None]) -> Set[_T]: ... + def __isub__(self: set[str], s: AbstractSet[Text | None]) -> set[_T]: ... @overload - 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 __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: ... @@ -749,31 +729,30 @@ class set(MutableSet[_T], Generic[_T]): class frozenset(AbstractSet[_T_co], Generic[_T_co]): def __init__(self, iterable: Iterable[_T_co] = ...) -> None: ... - def copy(self) -> FrozenSet[_T_co]: ... - def difference(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... - def intersection(self, *s: Iterable[object]) -> FrozenSet[_T_co]: ... + def 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 symmetric_difference(self, s: Iterable[_T_co]) -> frozenset[_T_co]: ... + def union(self, *s: Iterable[_T_co]) -> frozenset[_T_co]: ... def __len__(self) -> int: ... 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 __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: ... -class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): +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]: ... + def __iter__(self) -> Iterator[tuple[int, _T]]: ... + def next(self) -> tuple[int, _T]: ... class xrange(Sized, Iterable[int], Reversible[int]): @overload @@ -823,29 +802,29 @@ def cmp(__x: Any, __y: Any) -> int: ... _N1 = TypeVar("_N1", bool, int, float, complex) -def coerce(__x: _N1, __y: _N1) -> Tuple[_N1, _N1]: ... +def coerce(__x: _N1, __y: _N1) -> tuple[_N1, _N1]: ... def compile(source: Text | mod, filename: Text, mode: Text, flags: int = ..., dont_inherit: int = ...) -> Any: ... def delattr(__obj: Any, __name: Text) -> None: ... -def dir(__o: object = ...) -> List[str]: ... +def dir(__o: object = ...) -> list[str]: ... _N2 = TypeVar("_N2", int, float) -def divmod(__x: _N2, __y: _N2) -> Tuple[_N2, _N2]: ... +def divmod(__x: _N2, __y: _N2) -> tuple[_N2, _N2]: ... def eval( - __source: Text | bytes | CodeType, __globals: Dict[str, Any] | None = ..., __locals: Mapping[str, Any] | None = ... + __source: Text | bytes | CodeType, __globals: dict[str, Any] | None = ..., __locals: Mapping[str, Any] | None = ... ) -> Any: ... -def execfile(__filename: str, __globals: Dict[str, Any] | None = ..., __locals: Dict[str, Any] | None = ...) -> None: ... +def execfile(__filename: str, __globals: dict[str, Any] | None = ..., __locals: dict[str, Any] | None = ...) -> None: ... def exit(code: object = ...) -> NoReturn: ... @overload def filter(__function: Callable[[AnyStr], Any], __iterable: AnyStr) -> AnyStr: ... # type: ignore @overload -def filter(__function: None, __iterable: Tuple[_T | None, ...]) -> Tuple[_T, ...]: ... # type: ignore +def filter(__function: None, __iterable: tuple[_T | None, ...]) -> tuple[_T, ...]: ... # type: ignore @overload -def filter(__function: Callable[[_T], Any], __iterable: Tuple[_T, ...]) -> Tuple[_T, ...]: ... # type: ignore +def filter(__function: Callable[[_T], Any], __iterable: tuple[_T, ...]) -> tuple[_T, ...]: ... # type: ignore @overload -def filter(__function: None, __iterable: Iterable[_T | None]) -> List[_T]: ... +def filter(__function: None, __iterable: Iterable[_T | None]) -> list[_T]: ... @overload -def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> List[_T]: ... +def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> list[_T]: ... def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode @overload def getattr(__o: Any, name: Text) -> Any: ... @@ -863,7 +842,7 @@ def getattr(__o: object, name: str, __default: list[Any]) -> Any | list[Any]: .. def getattr(__o: object, name: str, __default: dict[Any, Any]) -> Any | dict[Any, Any]: ... @overload def getattr(__o: Any, name: Text, __default: _T) -> Any | _T: ... -def globals() -> Dict[str, Any]: ... +def globals() -> dict[str, Any]: ... def hasattr(__obj: Any, __name: Text) -> bool: ... def hash(__obj: object) -> int: ... def hex(__number: int | _SupportsIndex) -> str: ... @@ -876,20 +855,20 @@ def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... def iter(__function: Callable[[], _T | None], __sentinel: None) -> Iterator[_T]: ... @overload def iter(__function: Callable[[], _T], __sentinel: Any) -> Iterator[_T]: ... -def isinstance(__obj: object, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... -def issubclass(__cls: type, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... +def isinstance(__obj: object, __class_or_tuple: type | tuple[type | tuple[Any, ...], ...]) -> bool: ... +def issubclass(__cls: type, __class_or_tuple: type | tuple[type | tuple[Any, ...], ...]) -> bool: ... def len(__obj: Sized) -> int: ... -def locals() -> Dict[str, Any]: ... +def locals() -> dict[str, Any]: ... @overload -def map(__func: None, __iter1: Iterable[_T1]) -> List[_T1]: ... +def map(__func: None, __iter1: Iterable[_T1]) -> list[_T1]: ... @overload -def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... +def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> list[tuple[_T1, _T2]]: ... @overload -def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... +def map(__func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> list[tuple[_T1, _T2, _T3]]: ... @overload def map( __func: None, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] -) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... +) -> list[tuple[_T1, _T2, _T3, _T4]]: ... @overload def map( __func: None, @@ -898,7 +877,7 @@ def map( __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5], -) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +) -> list[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def map( __func: None, @@ -909,15 +888,15 @@ def map( __iter5: Iterable[Any], __iter6: Iterable[Any], *iterables: Iterable[Any], -) -> List[Tuple[Any, ...]]: ... +) -> list[tuple[Any, ...]]: ... @overload -def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> List[_S]: ... +def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> list[_S]: ... @overload -def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[_S]: ... +def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> list[_S]: ... @overload def map( __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] -) -> List[_S]: ... +) -> list[_S]: ... @overload def map( __func: Callable[[_T1, _T2, _T3, _T4], _S], @@ -925,7 +904,7 @@ def map( __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], -) -> List[_S]: ... +) -> list[_S]: ... @overload def map( __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], @@ -934,7 +913,7 @@ def map( __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5], -) -> List[_S]: ... +) -> list[_S]: ... @overload def map( __func: Callable[..., _S], @@ -945,7 +924,7 @@ def map( __iter5: Iterable[Any], __iter6: Iterable[Any], *iterables: Iterable[Any], -) -> List[_S]: ... +) -> list[_S]: ... @overload def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], Any] = ...) -> _T: ... @overload @@ -985,7 +964,7 @@ def pow(__base: _SupportsPow2[_E, _T_co], __exp: _E) -> _T_co: ... @overload def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M) -> _T_co: ... def quit(code: object = ...) -> NoReturn: ... -def range(__x: int, __y: int = ..., __step: int = ...) -> List[int]: ... # noqa: F811 +def range(__x: int, __y: int = ..., __step: int = ...) -> list[int]: ... # noqa: F811 def raw_input(__prompt: Any = ...) -> str: ... @overload def reduce(__function: Callable[[_T, _S], _T], __iterable: Iterable[_S], __initializer: _T) -> _T: ... @@ -1008,27 +987,27 @@ def round(number: SupportsFloat, ndigits: int) -> float: ... def setattr(__obj: Any, __name: Text, __value: Any) -> None: ... def sorted( __iterable: Iterable[_T], *, cmp: Callable[[_T, _T], int] = ..., key: Callable[[_T], Any] | None = ..., reverse: bool = ... -) -> List[_T]: ... +) -> list[_T]: ... @overload def sum(__iterable: Iterable[_T]) -> _T | int: ... @overload def sum(__iterable: Iterable[_T], __start: _S) -> _T | _S: ... def unichr(__i: int) -> unicode: ... -def vars(__object: Any = ...) -> Dict[str, Any]: ... +def vars(__object: Any = ...) -> dict[str, Any]: ... @overload -def zip(__iter1: Iterable[_T1]) -> List[Tuple[_T1]]: ... +def zip(__iter1: Iterable[_T1]) -> list[tuple[_T1]]: ... @overload -def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> List[Tuple[_T1, _T2]]: ... +def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> list[tuple[_T1, _T2]]: ... @overload -def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> List[Tuple[_T1, _T2, _T3]]: ... +def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> list[tuple[_T1, _T2, _T3]]: ... @overload def zip( __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] -) -> List[Tuple[_T1, _T2, _T3, _T4]]: ... +) -> list[tuple[_T1, _T2, _T3, _T4]]: ... @overload def zip( __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5] -) -> List[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +) -> list[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def zip( __iter1: Iterable[Any], @@ -1038,7 +1017,7 @@ def zip( __iter5: Iterable[Any], __iter6: Iterable[Any], *iterables: Iterable[Any], -) -> List[Tuple[Any, ...]]: ... +) -> list[tuple[Any, ...]]: ... def __import__( name: Text, globals: Mapping[str, Any] | None = ..., @@ -1066,13 +1045,11 @@ class buffer(Sized): def __mul__(self, x: int) -> str: ... class BaseException(object): - args: Tuple[Any, ...] + args: tuple[Any, ...] message: Any def __init__(self, *args: object) -> None: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... def __getitem__(self, i: int) -> Any: ... - def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ... + def __getslice__(self, start: int, stop: int) -> tuple[Any, ...]: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ... @@ -1181,7 +1158,7 @@ class file(BinaryIO): def seek(self, offset: int, whence: int = ...) -> int: ... def tell(self) -> int: ... def readline(self, limit: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... + def readlines(self, hint: int = ...) -> list[str]: ... def write(self, data: str) -> int: ... def writelines(self, data: Iterable[str]) -> None: ... def truncate(self, pos: int | None = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/bz2.pyi b/mypy/typeshed/stdlib/@python2/bz2.pyi index 81ee6f6ce26a..bec8994dbe29 100644 --- a/mypy/typeshed/stdlib/@python2/bz2.pyi +++ b/mypy/typeshed/stdlib/@python2/bz2.pyi @@ -1,22 +1,21 @@ import io -from _typeshed import ReadableBuffer, WriteableBuffer -from typing import IO, Any, Iterable, List, Text, TypeVar, Union +from _typeshed import ReadableBuffer, Self, WriteableBuffer +from typing import IO, Any, Iterable, Text, Union from typing_extensions import SupportsIndex _PathOrFile = Union[Text, IO[bytes]] -_T = TypeVar("_T") def compress(data: bytes, compresslevel: int = ...) -> bytes: ... def decompress(data: bytes) -> bytes: ... class BZ2File(io.BufferedIOBase, IO[bytes]): - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __init__(self, filename: _PathOrFile, mode: str = ..., buffering: Any | None = ..., compresslevel: int = ...) -> None: ... def read(self, size: int | None = ...) -> bytes: ... def read1(self, size: int = ...) -> bytes: ... def readline(self, size: SupportsIndex = ...) -> bytes: ... # type: ignore def readinto(self, b: WriteableBuffer) -> int: ... - def readlines(self, size: SupportsIndex = ...) -> List[bytes]: ... + def readlines(self, size: SupportsIndex = ...) -> list[bytes]: ... def seek(self, offset: int, whence: int = ...) -> int: ... def write(self, data: ReadableBuffer) -> int: ... def writelines(self, seq: Iterable[ReadableBuffer]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/cPickle.pyi b/mypy/typeshed/stdlib/@python2/cPickle.pyi index d8db140cdda1..9169a8df02b0 100644 --- a/mypy/typeshed/stdlib/@python2/cPickle.pyi +++ b/mypy/typeshed/stdlib/@python2/cPickle.pyi @@ -1,7 +1,7 @@ -from typing import IO, Any, List +from typing import IO, Any HIGHEST_PROTOCOL: int -compatible_formats: List[str] +compatible_formats: list[str] format_version: str class Pickler: diff --git a/mypy/typeshed/stdlib/@python2/cProfile.pyi b/mypy/typeshed/stdlib/@python2/cProfile.pyi index 1257b0cc92eb..2bb063c032a8 100644 --- a/mypy/typeshed/stdlib/@python2/cProfile.pyi +++ b/mypy/typeshed/stdlib/@python2/cProfile.pyi @@ -1,14 +1,14 @@ +from _typeshed import Self from types import CodeType -from typing import Any, Callable, Dict, Text, Tuple, TypeVar +from typing import Any, Callable, Text, TypeVar def run(statement: str, filename: str | None = ..., sort: str | int = ...) -> None: ... def runctx( - statement: str, globals: Dict[str, Any], locals: Dict[str, Any], filename: str | None = ..., sort: str | int = ... + statement: str, globals: dict[str, Any], locals: dict[str, Any], filename: str | None = ..., sort: str | int = ... ) -> None: ... -_SelfT = TypeVar("_SelfT", bound=Profile) _T = TypeVar("_T") -_Label = Tuple[str, int, str] +_Label = tuple[str, int, str] class Profile: stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]] # undocumented @@ -21,8 +21,8 @@ class Profile: def dump_stats(self, file: Text) -> None: ... def create_stats(self) -> None: ... def snapshot_stats(self) -> None: ... - def run(self: _SelfT, cmd: str) -> _SelfT: ... - def runctx(self: _SelfT, cmd: str, globals: Dict[str, Any], locals: Dict[str, Any]) -> _SelfT: ... + def run(self: Self, cmd: str) -> Self: ... + def runctx(self: Self, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> Self: ... def runcall(self, __func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... def label(code: str | CodeType) -> _Label: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/cStringIO.pyi b/mypy/typeshed/stdlib/@python2/cStringIO.pyi index 7703e030c332..33a20dd4a739 100644 --- a/mypy/typeshed/stdlib/@python2/cStringIO.pyi +++ b/mypy/typeshed/stdlib/@python2/cStringIO.pyi @@ -1,5 +1,5 @@ from abc import ABCMeta -from typing import IO, Iterable, Iterator, List, overload +from typing import IO, Iterable, Iterator, overload # This class isn't actually abstract, but you can't instantiate it # directly, so we might as well treat it as abstract in the stub. @@ -12,7 +12,7 @@ class InputType(IO[str], Iterator[str], metaclass=ABCMeta): def isatty(self) -> bool: ... def read(self, size: int = ...) -> str: ... def readline(self, size: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... + def readlines(self, hint: int = ...) -> list[str]: ... def seek(self, offset: int, whence: int = ...) -> int: ... def tell(self) -> int: ... def truncate(self, size: int | None = ...) -> int: ... @@ -31,7 +31,7 @@ class OutputType(IO[str], Iterator[str], metaclass=ABCMeta): def isatty(self) -> bool: ... def read(self, size: int = ...) -> str: ... def readline(self, size: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... + def readlines(self, hint: int = ...) -> list[str]: ... def seek(self, offset: int, whence: int = ...) -> int: ... def tell(self) -> int: ... def truncate(self, size: int | None = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/calendar.pyi b/mypy/typeshed/stdlib/@python2/calendar.pyi index ce765210dc1e..f21e6406a5c5 100644 --- a/mypy/typeshed/stdlib/@python2/calendar.pyi +++ b/mypy/typeshed/stdlib/@python2/calendar.pyi @@ -1,21 +1,19 @@ import datetime from time import struct_time -from typing import Any, Iterable, List, Optional, Sequence, Tuple +from typing import Any, Iterable, Optional, Sequence -_LocaleType = Tuple[Optional[str], Optional[str]] +_LocaleType = tuple[Optional[str], Optional[str]] class IllegalMonthError(ValueError): def __init__(self, month: int) -> None: ... - def __str__(self) -> str: ... class IllegalWeekdayError(ValueError): def __init__(self, weekday: int) -> None: ... - def __str__(self) -> str: ... def isleap(year: int) -> bool: ... def leapdays(y1: int, y2: int) -> int: ... def weekday(year: int, month: int, day: int) -> int: ... -def monthrange(year: int, month: int) -> Tuple[int, int]: ... +def monthrange(year: int, month: int) -> tuple[int, int]: ... class Calendar: firstweekday: int @@ -24,14 +22,14 @@ class Calendar: def setfirstweekday(self, firstweekday: int) -> None: ... def iterweekdays(self) -> Iterable[int]: ... def itermonthdates(self, year: int, month: int) -> Iterable[datetime.date]: ... - def itermonthdays2(self, year: int, month: int) -> Iterable[Tuple[int, int]]: ... + def itermonthdays2(self, year: int, month: int) -> Iterable[tuple[int, int]]: ... def itermonthdays(self, year: int, month: int) -> Iterable[int]: ... - def monthdatescalendar(self, year: int, month: int) -> List[List[datetime.date]]: ... - def monthdays2calendar(self, year: int, month: int) -> List[List[Tuple[int, int]]]: ... - def monthdayscalendar(self, year: int, month: int) -> List[List[int]]: ... - def yeardatescalendar(self, year: int, width: int = ...) -> List[List[int]]: ... - def yeardays2calendar(self, year: int, width: int = ...) -> List[List[Tuple[int, int]]]: ... - def yeardayscalendar(self, year: int, width: int = ...) -> List[List[int]]: ... + def monthdatescalendar(self, year: int, month: int) -> list[list[datetime.date]]: ... + def monthdays2calendar(self, year: int, month: int) -> list[list[tuple[int, int]]]: ... + def monthdayscalendar(self, year: int, month: int) -> list[list[int]]: ... + def yeardatescalendar(self, year: int, width: int = ...) -> list[list[int]]: ... + def yeardays2calendar(self, year: int, width: int = ...) -> list[list[tuple[int, int]]]: ... + def yeardayscalendar(self, year: int, width: int = ...) -> list[list[int]]: ... class TextCalendar(Calendar): def prweek(self, theweek: int, width: int) -> None: ... @@ -46,7 +44,7 @@ class TextCalendar(Calendar): def pryear(self, theyear: int, w: int = ..., l: int = ..., c: int = ..., m: int = ...) -> None: ... def firstweekday() -> int: ... -def monthcalendar(year: int, month: int) -> List[List[int]]: ... +def monthcalendar(year: int, month: int) -> list[list[int]]: ... def prweek(theweek: int, width: int) -> None: ... def week(theweek: int, width: int) -> str: ... def weekheader(width: int) -> str: ... @@ -85,7 +83,7 @@ c: TextCalendar def setfirstweekday(firstweekday: int) -> None: ... def format(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ... def formatstring(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ... -def timegm(tuple: Tuple[int, ...] | struct_time) -> int: ... +def timegm(tuple: tuple[int, ...] | struct_time) -> int: ... # Data attributes day_name: Sequence[str] diff --git a/mypy/typeshed/stdlib/@python2/cgi.pyi b/mypy/typeshed/stdlib/@python2/cgi.pyi index 674748242ebb..6c83a9c27e55 100644 --- a/mypy/typeshed/stdlib/@python2/cgi.pyi +++ b/mypy/typeshed/stdlib/@python2/cgi.pyi @@ -1,19 +1,17 @@ from _typeshed import SupportsGetItem, SupportsItemAccess -from builtins import type as _type -from typing import IO, Any, AnyStr, Iterable, Iterator, List, Mapping, Protocol, TypeVar +from builtins import list as List, type as _type # aliases to avoid name clashes with `FieldStorage` attributes +from typing import IO, Any, AnyStr, Iterable, Iterator, Mapping, Protocol from UserDict import UserDict -_T = TypeVar("_T", bound=FieldStorage) - def parse( fp: IO[Any] | None = ..., environ: SupportsItemAccess[str, str] = ..., keep_blank_values: bool = ..., strict_parsing: bool = ..., -) -> dict[str, List[str]]: ... -def parse_qs(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> dict[str, List[str]]: ... -def parse_qsl(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> List[tuple[str, str]]: ... -def parse_multipart(fp: IO[Any], pdict: SupportsGetItem[str, bytes]) -> dict[str, List[bytes]]: ... +) -> dict[str, list[str]]: ... +def parse_qs(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> dict[str, list[str]]: ... +def parse_qsl(qs: str, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> list[tuple[str, str]]: ... +def parse_multipart(fp: IO[Any], pdict: SupportsGetItem[str, bytes]) -> dict[str, list[bytes]]: ... class _Environ(Protocol): def __getitem__(self, __k: str) -> str: ... @@ -40,7 +38,6 @@ class MiniFieldStorage: name: Any value: Any def __init__(self, name: Any, value: Any) -> None: ... - def __repr__(self) -> str: ... class FieldStorage(object): FieldStorageClass: _type | None @@ -74,7 +71,6 @@ class FieldStorage(object): keep_blank_values: int = ..., strict_parsing: int = ..., ) -> None: ... - def __repr__(self) -> str: ... def __iter__(self) -> Iterator[str]: ... def __getitem__(self, key: str) -> Any: ... def getvalue(self, key: str, default: Any = ...) -> Any: ... @@ -88,7 +84,7 @@ class FieldStorage(object): # In Python 2 it always returns bytes and ignores the "binary" flag def make_file(self, binary: Any = ...) -> IO[bytes]: ... -class FormContentDict(UserDict[str, List[str]]): +class FormContentDict(UserDict[str, list[str]]): query_string: str def __init__(self, environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/cgitb.pyi b/mypy/typeshed/stdlib/@python2/cgitb.pyi index daa0233ee69a..aff45db6198c 100644 --- a/mypy/typeshed/stdlib/@python2/cgitb.pyi +++ b/mypy/typeshed/stdlib/@python2/cgitb.pyi @@ -1,16 +1,16 @@ from types import FrameType, TracebackType -from typing import IO, Any, Callable, Dict, List, Optional, Text, Tuple, Type +from typing import IO, Any, Callable, Optional, Text -_ExcInfo = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_ExcInfo = tuple[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]] def reset() -> str: ... # undocumented def small(text: str) -> str: ... # undocumented def strong(text: str) -> str: ... # undocumented def grey(text: str) -> str: ... # undocumented -def lookup(name: str, frame: FrameType, locals: Dict[str, Any]) -> Tuple[str | None, Any]: ... # undocumented +def lookup(name: str, frame: FrameType, locals: dict[str, Any]) -> tuple[str | None, Any]: ... # undocumented def scanvars( - reader: Callable[[], bytes], frame: FrameType, locals: Dict[str, Any] -) -> List[Tuple[str, str | None, Any]]: ... # undocumented + reader: Callable[[], bytes], frame: FrameType, locals: dict[str, Any] +) -> list[tuple[str, str | None, Any]]: ... # undocumented def html(einfo: _ExcInfo, context: int = ...) -> str: ... def text(einfo: _ExcInfo, context: int = ...) -> str: ... @@ -18,7 +18,7 @@ class Hook: # undocumented def __init__( self, display: int = ..., logdir: Text | None = ..., context: int = ..., file: IO[str] | None = ..., format: str = ... ) -> None: ... - def __call__(self, etype: Type[BaseException] | None, evalue: BaseException | None, etb: TracebackType | None) -> None: ... + def __call__(self, etype: type[BaseException] | None, evalue: BaseException | None, etb: TracebackType | None) -> None: ... def handle(self, info: _ExcInfo | None = ...) -> None: ... def handler(info: _ExcInfo | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/cmath.pyi b/mypy/typeshed/stdlib/@python2/cmath.pyi index 1e19687b4885..ef54d7f43854 100644 --- a/mypy/typeshed/stdlib/@python2/cmath.pyi +++ b/mypy/typeshed/stdlib/@python2/cmath.pyi @@ -1,4 +1,4 @@ -from typing import SupportsComplex, SupportsFloat, Tuple, Union +from typing import SupportsComplex, SupportsFloat, Union e: float pi: float @@ -18,7 +18,7 @@ def isnan(__z: _C) -> bool: ... def log(__x: _C, __y_obj: _C = ...) -> complex: ... def log10(__z: _C) -> complex: ... def phase(__z: _C) -> float: ... -def polar(__z: _C) -> Tuple[float, float]: ... +def polar(__z: _C) -> tuple[float, float]: ... def rect(__r: float, __phi: float) -> complex: ... def sin(__z: _C) -> complex: ... def sinh(__z: _C) -> complex: ... diff --git a/mypy/typeshed/stdlib/@python2/cmd.pyi b/mypy/typeshed/stdlib/@python2/cmd.pyi index ffccba84ec16..f6d818591a4e 100644 --- a/mypy/typeshed/stdlib/@python2/cmd.pyi +++ b/mypy/typeshed/stdlib/@python2/cmd.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Callable, List, Tuple +from typing import IO, Any, Callable class Cmd: prompt: str @@ -14,7 +14,7 @@ class Cmd: use_rawinput: bool stdin: IO[str] stdout: IO[str] - cmdqueue: List[str] + cmdqueue: list[str] completekey: str def __init__(self, completekey: str = ..., stdin: IO[str] | None = ..., stdout: IO[str] | None = ...) -> None: ... old_completer: Callable[[str, int], str | None] | None @@ -23,17 +23,17 @@ class Cmd: def postcmd(self, stop: bool, line: str) -> bool: ... def preloop(self) -> None: ... def postloop(self) -> None: ... - def parseline(self, line: str) -> Tuple[str | None, str | None, str]: ... + def parseline(self, line: str) -> tuple[str | None, str | None, str]: ... def onecmd(self, line: str) -> bool: ... def emptyline(self) -> bool: ... def default(self, line: str) -> bool: ... - def completedefault(self, *ignored: Any) -> List[str]: ... - def completenames(self, text: str, *ignored: Any) -> List[str]: ... - completion_matches: List[str] | None - def complete(self, text: str, state: int) -> List[str] | None: ... - def get_names(self) -> List[str]: ... + def completedefault(self, *ignored: Any) -> list[str]: ... + def completenames(self, text: str, *ignored: Any) -> list[str]: ... + completion_matches: list[str] | None + def complete(self, text: str, state: int) -> list[str] | None: ... + def get_names(self) -> list[str]: ... # Only the first element of args matters. - def complete_help(self, *args: Any) -> List[str]: ... + def complete_help(self, *args: Any) -> list[str]: ... def do_help(self, arg: str) -> bool | None: ... - def print_topics(self, header: str, cmds: List[str] | None, cmdlen: Any, maxcol: int) -> None: ... - def columnize(self, list: List[str] | None, displaywidth: int = ...) -> None: ... + def print_topics(self, header: str, cmds: list[str] | None, cmdlen: Any, maxcol: int) -> None: ... + def columnize(self, list: list[str] | None, displaywidth: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/codecs.pyi b/mypy/typeshed/stdlib/@python2/codecs.pyi index a7835106336d..339578ca1ae7 100644 --- a/mypy/typeshed/stdlib/@python2/codecs.pyi +++ b/mypy/typeshed/stdlib/@python2/codecs.pyi @@ -1,23 +1,7 @@ import types +from _typeshed import Self from abc import abstractmethod -from typing import ( - IO, - Any, - BinaryIO, - Callable, - Generator, - Iterable, - Iterator, - List, - Protocol, - Text, - TextIO, - Tuple, - Type, - TypeVar, - Union, - overload, -) +from typing import IO, Any, BinaryIO, Callable, Generator, Iterable, Iterator, Protocol, Text, TextIO, Union, overload from typing_extensions import Literal # TODO: this only satisfies the most common interface, where @@ -30,10 +14,10 @@ _Decoded = Text _Encoded = bytes class _Encoder(Protocol): - def __call__(self, input: _Decoded, errors: str = ...) -> Tuple[_Encoded, int]: ... # signature of Codec().encode + def __call__(self, input: _Decoded, errors: str = ...) -> tuple[_Encoded, int]: ... # signature of Codec().encode class _Decoder(Protocol): - def __call__(self, input: _Encoded, errors: str = ...) -> Tuple[_Decoded, int]: ... # signature of Codec().decode + def __call__(self, input: _Encoded, errors: str = ...) -> tuple[_Decoded, int]: ... # signature of Codec().decode class _StreamReader(Protocol): def __call__(self, stream: IO[_Encoded], errors: str = ...) -> StreamReader: ... @@ -83,10 +67,10 @@ def decode(obj: _Encoded, encoding: str = ..., errors: str = ...) -> _Decoded: . def lookup(__encoding: str) -> CodecInfo: ... def utf_16_be_decode( __data: _Encoded, __errors: str | None = ..., __final: bool = ... -) -> Tuple[_Decoded, int]: ... # undocumented -def utf_16_be_encode(__str: _Decoded, __errors: str | None = ...) -> Tuple[_Encoded, int]: ... # undocumented +) -> tuple[_Decoded, int]: ... # undocumented +def utf_16_be_encode(__str: _Decoded, __errors: str | None = ...) -> tuple[_Encoded, int]: ... # undocumented -class CodecInfo(Tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): +class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): @property def encode(self) -> _Encoder: ... @property @@ -141,19 +125,19 @@ BOM_UTF32_LE: bytes # It is expected that different actions be taken depending on which of the # three subclasses of `UnicodeError` is actually ...ed. However, the Union # is still needed for at least one of the cases. -def register_error(__errors: str, __handler: Callable[[UnicodeError], Tuple[str | bytes, int]]) -> None: ... -def lookup_error(__name: str) -> Callable[[UnicodeError], Tuple[str | bytes, int]]: ... -def strict_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... -def replace_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... -def ignore_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... -def xmlcharrefreplace_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... -def backslashreplace_errors(exception: UnicodeError) -> Tuple[str | bytes, int]: ... +def register_error(__errors: str, __handler: Callable[[UnicodeError], tuple[str | bytes, int]]) -> None: ... +def lookup_error(__name: str) -> Callable[[UnicodeError], tuple[str | bytes, int]]: ... +def strict_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... +def replace_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... +def ignore_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... +def xmlcharrefreplace_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... +def backslashreplace_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... class Codec: # These are sort of @abstractmethod but sort of not. # The StreamReader and StreamWriter subclasses only implement one. - def encode(self, input: _Decoded, errors: str = ...) -> Tuple[_Encoded, int]: ... - def decode(self, input: _Encoded, errors: str = ...) -> Tuple[_Decoded, int]: ... + def encode(self, input: _Decoded, errors: str = ...) -> tuple[_Encoded, int]: ... + def decode(self, input: _Encoded, errors: str = ...) -> tuple[_Decoded, int]: ... class IncrementalEncoder: errors: str @@ -171,8 +155,8 @@ class IncrementalDecoder: @abstractmethod def decode(self, input: _Encoded, final: bool = ...) -> _Decoded: ... def reset(self) -> None: ... - def getstate(self) -> Tuple[_Encoded, int]: ... - def setstate(self, state: Tuple[_Encoded, int]) -> None: ... + def getstate(self) -> tuple[_Encoded, int]: ... + def setstate(self, state: tuple[_Encoded, int]) -> None: ... # These are not documented but used in encodings/*.py implementations. class BufferedIncrementalEncoder(IncrementalEncoder): @@ -186,11 +170,9 @@ class BufferedIncrementalDecoder(IncrementalDecoder): buffer: bytes def __init__(self, errors: str = ...) -> None: ... @abstractmethod - def _buffer_decode(self, input: _Encoded, errors: str, final: bool) -> Tuple[_Decoded, int]: ... + def _buffer_decode(self, input: _Encoded, errors: str, final: bool) -> tuple[_Decoded, int]: ... def decode(self, input: _Encoded, final: bool = ...) -> _Decoded: ... -_SW = TypeVar("_SW", bound=StreamWriter) - # TODO: it is not possible to specify the requirement that all other # attributes and methods are passed-through from the stream. class StreamWriter(Codec): @@ -199,43 +181,39 @@ class StreamWriter(Codec): def write(self, object: _Decoded) -> None: ... def writelines(self, list: Iterable[_Decoded]) -> None: ... def reset(self) -> None: ... - def __enter__(self: _SW) -> _SW: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __enter__(self: Self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... -_SR = TypeVar("_SR", bound=StreamReader) - class StreamReader(Codec): errors: str def __init__(self, stream: IO[_Encoded], errors: str = ...) -> None: ... def read(self, size: int = ..., chars: int = ..., firstline: bool = ...) -> _Decoded: ... def readline(self, size: int | None = ..., keepends: bool = ...) -> _Decoded: ... - def readlines(self, sizehint: int | None = ..., keepends: bool = ...) -> List[_Decoded]: ... + def readlines(self, sizehint: int | None = ..., keepends: bool = ...) -> list[_Decoded]: ... def reset(self) -> None: ... - def __enter__(self: _SR) -> _SR: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __enter__(self: Self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... def __iter__(self) -> Iterator[_Decoded]: ... def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... -_T = TypeVar("_T", bound=StreamReaderWriter) - # Doesn't actually inherit from TextIO, but wraps a BinaryIO to provide text reading and writing # and delegates attributes to the underlying binary stream with __getattr__. class StreamReaderWriter(TextIO): def __init__(self, stream: IO[_Encoded], Reader: _StreamReader, Writer: _StreamWriter, errors: str = ...) -> None: ... def read(self, size: int = ...) -> _Decoded: ... def readline(self, size: int | None = ...) -> _Decoded: ... - def readlines(self, sizehint: int | None = ...) -> List[_Decoded]: ... + def readlines(self, sizehint: int | None = ...) -> list[_Decoded]: ... def next(self) -> Text: ... - def __iter__(self: _T) -> _T: ... + def __iter__(self: Self) -> Self: ... # This actually returns None, but that's incompatible with the supertype def write(self, data: _Decoded) -> int: ... def writelines(self, list: Iterable[_Decoded]) -> None: ... def reset(self) -> None: ... # Same as write() def seek(self, offset: int, whence: int = ...) -> int: ... - def __enter__(self: _T) -> _T: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __enter__(self: Self) -> Self: ... + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... def __getattr__(self, name: str) -> Any: ... # These methods don't actually exist directly, but they are needed to satisfy the TextIO # interface. At runtime, they are delegated through __getattr__. @@ -249,8 +227,6 @@ class StreamReaderWriter(TextIO): def tell(self) -> int: ... def writable(self) -> bool: ... -_SRT = TypeVar("_SRT", bound=StreamRecoder) - class StreamRecoder(BinaryIO): def __init__( self, @@ -263,15 +239,15 @@ class StreamRecoder(BinaryIO): ) -> None: ... def read(self, size: int = ...) -> bytes: ... def readline(self, size: int | None = ...) -> bytes: ... - def readlines(self, sizehint: int | None = ...) -> List[bytes]: ... + def readlines(self, sizehint: int | None = ...) -> list[bytes]: ... def next(self) -> bytes: ... - def __iter__(self: _SRT) -> _SRT: ... + def __iter__(self: Self) -> Self: ... def write(self, data: bytes) -> int: ... def writelines(self, list: Iterable[bytes]) -> int: ... # type: ignore # it's supposed to return None def reset(self) -> None: ... def __getattr__(self, name: str) -> Any: ... - def __enter__(self: _SRT) -> _SRT: ... - def __exit__(self, type: Type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __enter__(self: Self) -> Self: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... # These methods don't actually exist directly, but they are needed to satisfy the BinaryIO # interface. At runtime, they are delegated through __getattr__. def seek(self, offset: int, whence: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/collections.pyi b/mypy/typeshed/stdlib/@python2/collections.pyi index 5a2f73aed7ce..ca2d78be596d 100644 --- a/mypy/typeshed/stdlib/@python2/collections.pyi +++ b/mypy/typeshed/stdlib/@python2/collections.pyi @@ -1,16 +1,15 @@ +from _typeshed import Self from typing import ( AbstractSet, Any, Callable as Callable, Container as Container, - Dict, Generic, Hashable as Hashable, ItemsView as ItemsView, Iterable as Iterable, Iterator as Iterator, KeysView as KeysView, - List, Mapping as Mapping, MappingView as MappingView, MutableMapping as MutableMapping, @@ -19,8 +18,6 @@ from typing import ( Reversible, Sequence as Sequence, Sized as Sized, - Tuple, - Type, TypeVar, ValuesView as ValuesView, overload, @@ -28,7 +25,6 @@ from typing import ( Set = AbstractSet -_S = TypeVar("_S") _T = TypeVar("_T") _KT = TypeVar("_KT") _VT = TypeVar("_VT") @@ -36,7 +32,7 @@ _VT = TypeVar("_VT") # namedtuple is special-cased in the type checker; the initializer is ignored. def namedtuple( typename: str | unicode, field_names: str | unicode | Iterable[str | unicode], verbose: bool = ..., rename: bool = ... -) -> Type[Tuple[Any, ...]]: ... +) -> type[tuple[Any, ...]]: ... class deque(Sized, Iterable[_T], Reversible[_T], Generic[_T]): def __init__(self, iterable: Iterable[_T] = ..., maxlen: int = ...) -> None: ... @@ -55,24 +51,23 @@ class deque(Sized, Iterable[_T], Reversible[_T], Generic[_T]): def rotate(self, n: int = ...) -> None: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... def __hash__(self) -> int: ... def __getitem__(self, i: int) -> _T: ... def __setitem__(self, i: int, x: _T) -> None: ... def __contains__(self, o: _T) -> bool: ... def __reversed__(self) -> Iterator[_T]: ... - def __iadd__(self: _S, iterable: Iterable[_T]) -> _S: ... + def __iadd__(self: Self, iterable: Iterable[_T]) -> Self: ... -class Counter(Dict[_T, int], Generic[_T]): +class Counter(dict[_T, int], Generic[_T]): @overload def __init__(self, **kwargs: int) -> None: ... @overload def __init__(self, mapping: Mapping[_T, int]) -> None: ... @overload def __init__(self, iterable: Iterable[_T]) -> None: ... - def copy(self: _S) -> _S: ... + def copy(self: Self) -> Self: ... def elements(self) -> Iterator[_T]: ... - def most_common(self, n: int | None = ...) -> List[Tuple[_T, int]]: ... + def most_common(self, n: int | None = ...) -> list[tuple[_T, int]]: ... @overload def subtract(self, __mapping: Mapping[_T, int]) -> None: ... @overload @@ -85,7 +80,7 @@ class Counter(Dict[_T, int], Generic[_T]): @overload def update(self, __m: Mapping[_T, int], **kwargs: int) -> None: ... @overload - def update(self, __m: Iterable[_T] | Iterable[Tuple[_T, int]], **kwargs: int) -> None: ... + def update(self, __m: Iterable[_T] | Iterable[tuple[_T, int]], **kwargs: int) -> None: ... @overload def update(self, **kwargs: int) -> None: ... def __add__(self, other: Counter[_T]) -> Counter[_T]: ... @@ -97,12 +92,12 @@ class Counter(Dict[_T, int], Generic[_T]): def __iand__(self, other: Counter[_T]) -> Counter[_T]: ... def __ior__(self, other: Counter[_T]) -> Counter[_T]: ... -class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): - def popitem(self, last: bool = ...) -> Tuple[_KT, _VT]: ... - def copy(self: _S) -> _S: ... +class OrderedDict(dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): + def popitem(self, last: bool = ...) -> tuple[_KT, _VT]: ... + def copy(self: Self) -> Self: ... def __reversed__(self) -> Iterator[_KT]: ... -class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): +class defaultdict(dict[_KT, _VT], Generic[_KT, _VT]): default_factory: Callable[[], _VT] @overload def __init__(self, **kwargs: _VT) -> None: ... @@ -115,8 +110,8 @@ class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): @overload 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 __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: Self) -> Self: ... diff --git a/mypy/typeshed/stdlib/@python2/colorsys.pyi b/mypy/typeshed/stdlib/@python2/colorsys.pyi index 8db2e2c9ab3a..00c5f9d22cb1 100644 --- a/mypy/typeshed/stdlib/@python2/colorsys.pyi +++ b/mypy/typeshed/stdlib/@python2/colorsys.pyi @@ -1,11 +1,9 @@ -from typing import Tuple - -def rgb_to_yiq(r: float, g: float, b: float) -> Tuple[float, float, float]: ... -def yiq_to_rgb(y: float, i: float, q: float) -> Tuple[float, float, float]: ... -def rgb_to_hls(r: float, g: float, b: float) -> Tuple[float, float, float]: ... -def hls_to_rgb(h: float, l: float, s: float) -> Tuple[float, float, float]: ... -def rgb_to_hsv(r: float, g: float, b: float) -> Tuple[float, float, float]: ... -def hsv_to_rgb(h: float, s: float, v: float) -> Tuple[float, float, float]: ... +def rgb_to_yiq(r: float, g: float, b: float) -> tuple[float, float, float]: ... +def yiq_to_rgb(y: float, i: float, q: float) -> tuple[float, float, float]: ... +def rgb_to_hls(r: float, g: float, b: float) -> tuple[float, float, float]: ... +def hls_to_rgb(h: float, l: float, s: float) -> tuple[float, float, float]: ... +def rgb_to_hsv(r: float, g: float, b: float) -> tuple[float, float, float]: ... +def hsv_to_rgb(h: float, s: float, v: float) -> tuple[float, float, float]: ... # TODO undocumented ONE_SIXTH: float diff --git a/mypy/typeshed/stdlib/@python2/commands.pyi b/mypy/typeshed/stdlib/@python2/commands.pyi index 970d6ccf2032..2c36033583ec 100644 --- a/mypy/typeshed/stdlib/@python2/commands.pyi +++ b/mypy/typeshed/stdlib/@python2/commands.pyi @@ -1,8 +1,8 @@ -from typing import AnyStr, Text, Tuple, overload +from typing import AnyStr, Text, overload def getstatus(file: Text) -> str: ... def getoutput(cmd: Text) -> str: ... -def getstatusoutput(cmd: Text) -> Tuple[int, str]: ... +def getstatusoutput(cmd: Text) -> tuple[int, str]: ... @overload def mk2arg(head: bytes, x: bytes) -> bytes: ... @overload diff --git a/mypy/typeshed/stdlib/@python2/contextlib.pyi b/mypy/typeshed/stdlib/@python2/contextlib.pyi index 6aabf5a16e47..6cb18831fc17 100644 --- a/mypy/typeshed/stdlib/@python2/contextlib.pyi +++ b/mypy/typeshed/stdlib/@python2/contextlib.pyi @@ -1,14 +1,11 @@ from types import TracebackType -from typing import IO, Any, Callable, ContextManager, Iterable, Iterator, Optional, Type, TypeVar -from typing_extensions import Protocol +from typing import IO, Any, Callable, ContextManager, Iterable, Iterator, Optional, Protocol, TypeVar _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) -_T_io = TypeVar("_T_io", bound=Optional[IO[str]]) _F = TypeVar("_F", bound=Callable[..., Any]) -_ExitFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], bool] -_CM_EF = TypeVar("_CM_EF", ContextManager[Any], _ExitFunc) +_ExitFunc = Callable[[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]], bool] class GeneratorContextManager(ContextManager[_T_co]): def __call__(self, func: _F) -> _F: ... diff --git a/mypy/typeshed/stdlib/@python2/copy.pyi b/mypy/typeshed/stdlib/@python2/copy.pyi index c88f92846ddf..a5f9420e3811 100644 --- a/mypy/typeshed/stdlib/@python2/copy.pyi +++ b/mypy/typeshed/stdlib/@python2/copy.pyi @@ -1,4 +1,4 @@ -from typing import Any, Dict, TypeVar +from typing import Any, TypeVar _T = TypeVar("_T") @@ -6,7 +6,7 @@ _T = TypeVar("_T") PyStringMap: Any # Note: memo and _nil are internal kwargs. -def deepcopy(x: _T, memo: Dict[int, Any] | None = ..., _nil: Any = ...) -> _T: ... +def deepcopy(x: _T, memo: dict[int, Any] | None = ..., _nil: Any = ...) -> _T: ... def copy(x: _T) -> _T: ... class Error(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/copy_reg.pyi b/mypy/typeshed/stdlib/@python2/copy_reg.pyi index 91b099888bab..f6fe5cd28582 100644 --- a/mypy/typeshed/stdlib/@python2/copy_reg.pyi +++ b/mypy/typeshed/stdlib/@python2/copy_reg.pyi @@ -1,9 +1,9 @@ -from typing import Any, Callable, Hashable, List, Optional, SupportsInt, Tuple, TypeVar, Union +from typing import Any, Callable, Hashable, Optional, SupportsInt, TypeVar, Union _TypeT = TypeVar("_TypeT", bound=type) -_Reduce = Union[Tuple[Callable[..., _TypeT], Tuple[Any, ...]], Tuple[Callable[..., _TypeT], Tuple[Any, ...], Optional[Any]]] +_Reduce = Union[tuple[Callable[..., _TypeT], tuple[Any, ...]], tuple[Callable[..., _TypeT], tuple[Any, ...], Optional[Any]]] -__all__: List[str] +__all__: list[str] def pickle( ob_type: _TypeT, diff --git a/mypy/typeshed/stdlib/@python2/copyreg.pyi b/mypy/typeshed/stdlib/@python2/copyreg.pyi index 91b099888bab..f6fe5cd28582 100644 --- a/mypy/typeshed/stdlib/@python2/copyreg.pyi +++ b/mypy/typeshed/stdlib/@python2/copyreg.pyi @@ -1,9 +1,9 @@ -from typing import Any, Callable, Hashable, List, Optional, SupportsInt, Tuple, TypeVar, Union +from typing import Any, Callable, Hashable, Optional, SupportsInt, TypeVar, Union _TypeT = TypeVar("_TypeT", bound=type) -_Reduce = Union[Tuple[Callable[..., _TypeT], Tuple[Any, ...]], Tuple[Callable[..., _TypeT], Tuple[Any, ...], Optional[Any]]] +_Reduce = Union[tuple[Callable[..., _TypeT], tuple[Any, ...]], tuple[Callable[..., _TypeT], tuple[Any, ...], Optional[Any]]] -__all__: List[str] +__all__: list[str] def pickle( ob_type: _TypeT, diff --git a/mypy/typeshed/stdlib/@python2/crypt.pyi b/mypy/typeshed/stdlib/@python2/crypt.pyi index c4036dbe7a5a..a7c0cb1e8fbc 100644 --- a/mypy/typeshed/stdlib/@python2/crypt.pyi +++ b/mypy/typeshed/stdlib/@python2/crypt.pyi @@ -1 +1,4 @@ -def crypt(word: str, salt: str) -> str: ... +import sys + +if sys.platform != "win32": + def crypt(word: str, salt: str) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/csv.pyi b/mypy/typeshed/stdlib/@python2/csv.pyi index 886de6210ca9..a52db42291af 100644 --- a/mypy/typeshed/stdlib/@python2/csv.pyi +++ b/mypy/typeshed/stdlib/@python2/csv.pyi @@ -16,20 +16,8 @@ from _csv import ( unregister_dialect as unregister_dialect, writer as writer, ) -from typing import ( - Any, - Dict as _DictReadMapping, - Generic, - Iterable, - Iterator, - List, - Mapping, - Sequence, - Text, - Type, - TypeVar, - overload, -) +from builtins import dict as _DictReadMapping +from typing import Any, Generic, Iterable, Iterator, Mapping, Sequence, Text, TypeVar, overload _T = TypeVar("_T") @@ -96,7 +84,7 @@ class DictWriter(Generic[_T]): def writerows(self, rowdicts: Iterable[Mapping[_T, Any]]) -> None: ... class Sniffer(object): - preferred: List[str] + preferred: list[str] def __init__(self) -> None: ... - def sniff(self, sample: str, delimiters: str | None = ...) -> Type[Dialect]: ... + def sniff(self, sample: str, delimiters: str | None = ...) -> type[Dialect]: ... def has_header(self, sample: str) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi b/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi index 33184cc2ff88..9fab35ebd022 100644 --- a/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/ctypes/__init__.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from array import array from typing import ( Any, @@ -7,13 +8,10 @@ from typing import ( Generic, Iterable, Iterator, - List, Mapping, Optional, Sequence, Text, - Tuple, - Type, TypeVar, Union as _UnionT, overload, @@ -23,16 +21,16 @@ _T = TypeVar("_T") _DLLT = TypeVar("_DLLT", bound=CDLL) _CT = TypeVar("_CT", bound=_CData) -RTLD_GLOBAL: int = ... -RTLD_LOCAL: int = ... -DEFAULT_MODE: int = ... +RTLD_GLOBAL: int +RTLD_LOCAL: int +DEFAULT_MODE: int class CDLL(object): _func_flags_: ClassVar[int] = ... _func_restype_: ClassVar[_CData] = ... _name: str = ... _handle: int = ... - _FuncPtr: Type[_FuncPointer] = ... + _FuncPtr: type[_FuncPointer] = ... def __init__( self, name: str | None, mode: int = ..., handle: int | None = ..., use_errno: bool = ..., use_last_error: bool = ... ) -> None: ... @@ -46,17 +44,17 @@ if sys.platform == "win32": class PyDLL(CDLL): ... class LibraryLoader(Generic[_DLLT]): - def __init__(self, dlltype: Type[_DLLT]) -> None: ... + def __init__(self, dlltype: type[_DLLT]) -> None: ... def __getattr__(self, name: str) -> _DLLT: ... def __getitem__(self, name: str) -> _DLLT: ... def LoadLibrary(self, name: str) -> _DLLT: ... -cdll: LibraryLoader[CDLL] = ... +cdll: LibraryLoader[CDLL] if sys.platform == "win32": - windll: LibraryLoader[WinDLL] = ... - oledll: LibraryLoader[OleDLL] = ... -pydll: LibraryLoader[PyDLL] = ... -pythonapi: PyDLL = ... + windll: LibraryLoader[WinDLL] + oledll: LibraryLoader[OleDLL] +pydll: LibraryLoader[PyDLL] +pythonapi: PyDLL # Anything that implements the read-write buffer interface. # The buffer interface is defined purely on the C level, so we cannot define a normal Protocol @@ -69,42 +67,42 @@ class _CDataMeta(type): # By default mypy complains about the following two methods, because strictly speaking cls # might not be a Type[_CT]. However this can never actually happen, because the only class that # uses _CDataMeta as its metaclass is _CData. So it's safe to ignore the errors here. - def __mul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore - def __rmul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore class _CData(metaclass=_CDataMeta): _b_base: int = ... _b_needsfree_: bool = ... _objects: Mapping[Any, int] | None = ... @classmethod - def from_buffer(cls: Type[_CT], source: _WritableBuffer, offset: int = ...) -> _CT: ... + def from_buffer(cls: type[Self], source: _WritableBuffer, offset: int = ...) -> Self: ... @classmethod - def from_buffer_copy(cls: Type[_CT], source: _ReadOnlyBuffer, offset: int = ...) -> _CT: ... + def from_buffer_copy(cls: type[Self], source: _ReadOnlyBuffer, offset: int = ...) -> Self: ... @classmethod - def from_address(cls: Type[_CT], address: int) -> _CT: ... + def from_address(cls: type[Self], address: int) -> Self: ... @classmethod - def from_param(cls: Type[_CT], obj: Any) -> _UnionT[_CT, _CArgObject]: ... + def from_param(cls: type[_CT], obj: Any) -> _UnionT[_CT, _CArgObject]: ... @classmethod - def in_dll(cls: Type[_CT], library: CDLL, name: str) -> _CT: ... + def in_dll(cls: type[Self], library: CDLL, name: str) -> Self: ... class _CanCastTo(_CData): ... class _PointerLike(_CanCastTo): ... -_ECT = Callable[[Optional[Type[_CData]], _FuncPointer, Tuple[_CData, ...]], _CData] -_PF = _UnionT[Tuple[int], Tuple[int, str], Tuple[int, str, Any]] +_ECT = Callable[[Optional[type[_CData]], _FuncPointer, tuple[_CData, ...]], _CData] +_PF = _UnionT[tuple[int], tuple[int, str], tuple[int, str, Any]] class _FuncPointer(_PointerLike, _CData): - restype: _UnionT[Type[_CData], Callable[[int], Any], None] = ... - argtypes: Sequence[Type[_CData]] = ... + restype: _UnionT[type[_CData], Callable[[int], Any], None] = ... + argtypes: Sequence[type[_CData]] = ... errcheck: _ECT = ... @overload def __init__(self, address: int) -> None: ... @overload def __init__(self, callable: Callable[..., Any]) -> None: ... @overload - def __init__(self, func_spec: Tuple[_UnionT[str, int], CDLL], paramflags: Tuple[_PF, ...] = ...) -> None: ... + def __init__(self, func_spec: tuple[_UnionT[str, int], CDLL], paramflags: tuple[_PF, ...] = ...) -> None: ... @overload - def __init__(self, vtlb_index: int, name: str, paramflags: Tuple[_PF, ...] = ..., iid: pointer[c_int] = ...) -> None: ... + def __init__(self, vtlb_index: int, name: str, paramflags: tuple[_PF, ...] = ..., iid: pointer[c_int] = ...) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... class _NamedFuncPointer(_FuncPointer): @@ -113,15 +111,15 @@ class _NamedFuncPointer(_FuncPointer): class ArgumentError(Exception): ... def CFUNCTYPE( - restype: Type[_CData] | None, *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ... -) -> Type[_FuncPointer]: ... + restype: type[_CData] | None, *argtypes: type[_CData], use_errno: bool = ..., use_last_error: bool = ... +) -> type[_FuncPointer]: ... if sys.platform == "win32": def WINFUNCTYPE( - restype: Type[_CData] | None, *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ... - ) -> Type[_FuncPointer]: ... + restype: type[_CData] | None, *argtypes: type[_CData], use_errno: bool = ..., use_last_error: bool = ... + ) -> type[_FuncPointer]: ... -def PYFUNCTYPE(restype: Type[_CData] | None, *argtypes: Type[_CData]) -> Type[_FuncPointer]: ... +def PYFUNCTYPE(restype: type[_CData] | None, *argtypes: type[_CData]) -> type[_FuncPointer]: ... class _CArgObject: ... @@ -135,12 +133,12 @@ _CVoidPLike = _UnionT[_PointerLike, Array[Any], _CArgObject, int] _CVoidConstPLike = _UnionT[_CVoidPLike, bytes] def addressof(obj: _CData) -> int: ... -def alignment(obj_or_type: _UnionT[_CData, Type[_CData]]) -> int: ... +def alignment(obj_or_type: _UnionT[_CData, type[_CData]]) -> int: ... def byref(obj: _CData, offset: int = ...) -> _CArgObject: ... _CastT = TypeVar("_CastT", bound=_CanCastTo) -def cast(obj: _UnionT[_CData, _CArgObject, int], typ: Type[_CastT]) -> _CastT: ... +def cast(obj: _UnionT[_CData, _CArgObject, int], typ: type[_CastT]) -> _CastT: ... def create_string_buffer(init: _UnionT[int, bytes], size: int | None = ...) -> Array[c_char]: ... c_buffer = create_string_buffer @@ -150,7 +148,7 @@ def create_unicode_buffer(init: _UnionT[int, Text], size: int | None = ...) -> A if sys.platform == "win32": def DllCanUnloadNow() -> int: ... def DllGetClassObject(rclsid: Any, riid: Any, ppv: Any) -> int: ... # TODO not documented - def FormatError(code: int) -> str: ... + def FormatError(code: int = ...) -> str: ... def GetLastError() -> int: ... def get_errno() -> int: ... @@ -160,32 +158,32 @@ if sys.platform == "win32": def memmove(dst: _CVoidPLike, src: _CVoidConstPLike, count: int) -> None: ... def memset(dst: _CVoidPLike, c: int, count: int) -> None: ... -def POINTER(type: Type[_CT]) -> Type[pointer[_CT]]: ... +def POINTER(type: type[_CT]) -> type[pointer[_CT]]: ... # The real ctypes.pointer is a function, not a class. The stub version of pointer behaves like # ctypes._Pointer in that it is the base class for all pointer types. Unlike the real _Pointer, # it can be instantiated directly (to mimic the behavior of the real pointer function). class pointer(Generic[_CT], _PointerLike, _CData): - _type_: Type[_CT] = ... + _type_: type[_CT] = ... contents: _CT = ... def __init__(self, arg: _CT = ...) -> None: ... @overload def __getitem__(self, i: int) -> _CT: ... @overload - def __getitem__(self, s: slice) -> List[_CT]: ... + def __getitem__(self, s: slice) -> list[_CT]: ... @overload def __setitem__(self, i: int, o: _CT) -> None: ... @overload def __setitem__(self, s: slice, o: Iterable[_CT]) -> None: ... def resize(obj: _CData, size: int) -> None: ... -def set_conversion_mode(encoding: str, errors: str) -> Tuple[str, str]: ... +def set_conversion_mode(encoding: str, errors: str) -> tuple[str, str]: ... def set_errno(value: int) -> int: ... if sys.platform == "win32": def set_last_error(value: int) -> int: ... -def sizeof(obj_or_type: _UnionT[_CData, Type[_CData]]) -> int: ... +def sizeof(obj_or_type: _UnionT[_CData, type[_CData]]) -> int: ... def string_at(address: _CVoidConstPLike, size: int = ...) -> bytes: ... if sys.platform == "win32": @@ -246,7 +244,7 @@ class _CField: size: int = ... class _StructUnionMeta(_CDataMeta): - _fields_: Sequence[_UnionT[Tuple[str, Type[_CData]], Tuple[str, Type[_CData], int]]] = ... + _fields_: Sequence[_UnionT[tuple[str, type[_CData]], tuple[str, type[_CData], int]]] = ... _pack_: int = ... _anonymous_: Sequence[str] = ... def __getattr__(self, name: str) -> _CField: ... @@ -263,7 +261,7 @@ class LittleEndianStructure(Structure): ... class Array(Generic[_CT], _CData): _length_: int = ... - _type_: Type[_CT] = ... + _type_: type[_CT] = ... raw: bytes = ... # Note: only available if _CT == c_char value: Any = ... # Note: bytes if _CT == c_char, Text if _CT == c_wchar, unavailable otherwise # TODO These methods cannot be annotated correctly at the moment. @@ -282,7 +280,7 @@ class Array(Generic[_CT], _CData): @overload def __getitem__(self, i: int) -> Any: ... @overload - def __getitem__(self, s: slice) -> List[Any]: ... + def __getitem__(self, s: slice) -> list[Any]: ... @overload def __setitem__(self, i: int, o: Any) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/@python2/curses/ascii.pyi b/mypy/typeshed/stdlib/@python2/curses/ascii.pyi index 05efb326687a..66efbe36a7df 100644 --- a/mypy/typeshed/stdlib/@python2/curses/ascii.pyi +++ b/mypy/typeshed/stdlib/@python2/curses/ascii.pyi @@ -1,4 +1,4 @@ -from typing import List, TypeVar +from typing import TypeVar _CharT = TypeVar("_CharT", str, int) @@ -39,7 +39,7 @@ US: int SP: int DEL: int -controlnames: List[int] +controlnames: list[int] def isalnum(c: str | int) -> bool: ... def isalpha(c: str | int) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/datetime.pyi b/mypy/typeshed/stdlib/@python2/datetime.pyi index 8b19a3d316f2..6a259cf4d0e4 100644 --- a/mypy/typeshed/stdlib/@python2/datetime.pyi +++ b/mypy/typeshed/stdlib/@python2/datetime.pyi @@ -1,7 +1,6 @@ +from _typeshed import Self from time import struct_time -from typing import AnyStr, ClassVar, SupportsAbs, Tuple, Type, TypeVar, Union, overload - -_S = TypeVar("_S") +from typing import AnyStr, ClassVar, SupportsAbs, Union, overload _Text = Union[str, unicode] @@ -20,13 +19,13 @@ class date: min: ClassVar[date] max: ClassVar[date] resolution: ClassVar[timedelta] - def __new__(cls: Type[_S], year: int, month: int, day: int) -> _S: ... + def __new__(cls: type[Self], year: int, month: int, day: int) -> Self: ... @classmethod - def fromtimestamp(cls: Type[_S], __timestamp: float) -> _S: ... + def fromtimestamp(cls: type[Self], __timestamp: float) -> Self: ... @classmethod - def today(cls: Type[_S]) -> _S: ... + def today(cls: type[Self]) -> Self: ... @classmethod - def fromordinal(cls: Type[_S], n: int) -> _S: ... + def fromordinal(cls: type[Self], n: int) -> Self: ... @property def year(self) -> int: ... @property @@ -53,15 +52,20 @@ class date: def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... - def isocalendar(self) -> Tuple[int, int, int]: ... + def isocalendar(self) -> tuple[int, int, int]: ... class time: min: ClassVar[time] max: ClassVar[time] resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], hour: int = ..., minute: int = ..., second: int = ..., microsecond: int = ..., tzinfo: _tzinfo | None = ... - ) -> _S: ... + cls: type[Self], + hour: int = ..., + minute: int = ..., + second: int = ..., + microsecond: int = ..., + tzinfo: _tzinfo | None = ..., + ) -> Self: ... @property def hour(self) -> int: ... @property @@ -95,7 +99,7 @@ class timedelta(SupportsAbs[timedelta]): max: ClassVar[timedelta] resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], + cls: type[Self], days: float = ..., seconds: float = ..., microseconds: float = ..., @@ -103,7 +107,7 @@ class timedelta(SupportsAbs[timedelta]): minutes: float = ..., hours: float = ..., weeks: float = ..., - ) -> _S: ... + ) -> Self: ... @property def days(self) -> int: ... @property @@ -139,7 +143,7 @@ class datetime(date): max: ClassVar[datetime] resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], + cls: type[Self], year: int, month: int, day: int, @@ -148,7 +152,7 @@ class datetime(date): second: int = ..., microsecond: int = ..., tzinfo: _tzinfo | None = ..., - ) -> _S: ... + ) -> Self: ... @property def year(self) -> int: ... @property @@ -166,21 +170,21 @@ class datetime(date): @property def tzinfo(self) -> _tzinfo | None: ... @classmethod - def fromtimestamp(cls: Type[_S], t: float, tz: _tzinfo | None = ...) -> _S: ... + def fromtimestamp(cls: type[Self], t: float, tz: _tzinfo | None = ...) -> Self: ... @classmethod - def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ... + def utcfromtimestamp(cls: type[Self], t: float) -> Self: ... @classmethod - def today(cls: Type[_S]) -> _S: ... + def today(cls: type[Self]) -> Self: ... @classmethod - def fromordinal(cls: Type[_S], n: int) -> _S: ... + def fromordinal(cls: type[Self], n: int) -> Self: ... @overload @classmethod - def now(cls: Type[_S], tz: None = ...) -> _S: ... + def now(cls: type[Self], tz: None = ...) -> Self: ... @overload @classmethod def now(cls, tz: _tzinfo) -> datetime: ... @classmethod - def utcnow(cls: Type[_S]) -> _S: ... + def utcnow(cls: type[Self]) -> Self: ... @classmethod def combine(cls, date: _date, time: _time) -> datetime: ... def strftime(self, fmt: _Text) -> str: ... @@ -223,4 +227,4 @@ class datetime(date): def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... - def isocalendar(self) -> Tuple[int, int, int]: ... + def isocalendar(self) -> tuple[int, int, int]: ... diff --git a/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi b/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi index 95f6d9cf0363..738c60792a4e 100644 --- a/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/dbm/__init__.pyi @@ -1,5 +1,5 @@ from types import TracebackType -from typing import Iterator, MutableMapping, Tuple, Type, Union +from typing import Iterator, MutableMapping, Union from typing_extensions import Literal _KeyType = Union[str, bytes] @@ -15,12 +15,12 @@ class _Database(MutableMapping[_KeyType, bytes]): def __del__(self) -> None: ... def __enter__(self) -> _Database: ... 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: ... class _error(Exception): ... -error = Tuple[Type[_error], Type[OSError]] +error = tuple[type[_error], type[OSError]] def whichdb(filename: str) -> str: ... def open(file: str, flag: Literal["r", "w", "c", "n"] = ..., mode: int = ...) -> _Database: ... diff --git a/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi b/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi index fb5e2da5fa2c..163ceb53d685 100644 --- a/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi +++ b/mypy/typeshed/stdlib/@python2/dbm/dumb.pyi @@ -1,5 +1,5 @@ from types import TracebackType -from typing import Iterator, MutableMapping, Type, Union +from typing import Iterator, MutableMapping, Union _KeyType = Union[str, bytes] _ValueType = Union[str, bytes] @@ -19,7 +19,7 @@ class _Database(MutableMapping[_KeyType, bytes]): def __del__(self) -> None: ... def __enter__(self) -> _Database: ... 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 open(file: str, flag: str = ..., mode: int = ...) -> _Database: ... diff --git a/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi b/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi index 0e9339bf81f9..b8b10cb62b3e 100644 --- a/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi +++ b/mypy/typeshed/stdlib/@python2/dbm/gnu.pyi @@ -1,5 +1,5 @@ from types import TracebackType -from typing import List, Type, TypeVar, Union, overload +from typing import TypeVar, Union, overload _T = TypeVar("_T") _KeyType = Union[str, bytes] @@ -20,13 +20,13 @@ class _gdbm: def __len__(self) -> int: ... def __enter__(self) -> _gdbm: ... 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: ... @overload def get(self, k: _KeyType) -> bytes | None: ... @overload def get(self, k: _KeyType, default: bytes | _T) -> bytes | _T: ... - def keys(self) -> List[bytes]: ... + def keys(self) -> list[bytes]: ... def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... # Don't exist at runtime __new__: None # type: ignore diff --git a/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi b/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi index 28f4dd8e4e59..dec50baaaaf4 100644 --- a/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi +++ b/mypy/typeshed/stdlib/@python2/dbm/ndbm.pyi @@ -1,5 +1,5 @@ from types import TracebackType -from typing import List, Type, TypeVar, Union, overload +from typing import TypeVar, Union, overload _T = TypeVar("_T") _KeyType = Union[str, bytes] @@ -7,7 +7,7 @@ _ValueType = Union[str, bytes] class error(OSError): ... -library: str = ... +library: str # Actual typename dbm, not exposed by the implementation class _dbm: @@ -19,13 +19,13 @@ class _dbm: def __del__(self) -> None: ... def __enter__(self) -> _dbm: ... 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: ... @overload def get(self, k: _KeyType) -> bytes | None: ... @overload def get(self, k: _KeyType, default: bytes | _T) -> bytes | _T: ... - def keys(self) -> List[bytes]: ... + def keys(self) -> list[bytes]: ... def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... # Don't exist at runtime __new__: None # type: ignore diff --git a/mypy/typeshed/stdlib/@python2/decimal.pyi b/mypy/typeshed/stdlib/@python2/decimal.pyi index 915bddadb584..f798d8811c87 100644 --- a/mypy/typeshed/stdlib/@python2/decimal.pyi +++ b/mypy/typeshed/stdlib/@python2/decimal.pyi @@ -1,14 +1,14 @@ +from _typeshed import Self from types import TracebackType -from typing import Any, Container, Dict, List, NamedTuple, Sequence, Text, Tuple, Type, TypeVar, Union +from typing import Any, Container, NamedTuple, Sequence, Text, Union _Decimal = Union[Decimal, int] -_DecimalNew = Union[Decimal, float, Text, Tuple[int, Sequence[int], int]] +_DecimalNew = Union[Decimal, float, Text, tuple[int, Sequence[int], int]] _ComparableNum = Union[Decimal, float] -_DecimalT = TypeVar("_DecimalT", bound=Decimal) class DecimalTuple(NamedTuple): sign: int - digits: Tuple[int, ...] + digits: tuple[int, ...] exponent: int ROUND_DOWN: str @@ -41,7 +41,7 @@ def getcontext() -> Context: ... def localcontext(ctx: Context | None = ...) -> _ContextManager: ... class Decimal(object): - def __new__(cls: Type[_DecimalT], value: _DecimalNew = ..., context: Context | None = ...) -> _DecimalT: ... + def __new__(cls: type[Self], value: _DecimalNew = ..., context: Context | None = ...) -> Self: ... @classmethod def from_float(cls, __f: float) -> Decimal: ... def __nonzero__(self) -> bool: ... @@ -54,7 +54,7 @@ class Decimal(object): def to_eng_string(self, context: Context | None = ...) -> str: ... def __abs__(self, round: bool = ..., context: Context | None = ...) -> Decimal: ... def __add__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __divmod__(self, other: _Decimal, context: Context | None = ...) -> Tuple[Decimal, Decimal]: ... + def __divmod__(self, other: _Decimal, context: Context | None = ...) -> tuple[Decimal, Decimal]: ... def __eq__(self, other: object, context: Context | None = ...) -> bool: ... def __floordiv__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def __ge__(self, other: _ComparableNum, context: Context | None = ...) -> bool: ... @@ -67,7 +67,7 @@ class Decimal(object): def __pos__(self, context: Context | None = ...) -> Decimal: ... def __pow__(self, other: _Decimal, modulo: _Decimal | None = ..., context: Context | None = ...) -> Decimal: ... def __radd__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __rdivmod__(self, other: _Decimal, context: Context | None = ...) -> Tuple[Decimal, Decimal]: ... + def __rdivmod__(self, other: _Decimal, context: Context | None = ...) -> tuple[Decimal, Decimal]: ... def __rfloordiv__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def __rmod__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def __rmul__(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... @@ -136,7 +136,7 @@ class Decimal(object): def rotate(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def scaleb(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def shift(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __reduce__(self) -> Tuple[Type[Decimal], Tuple[str]]: ... + 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: ... @@ -146,9 +146,9 @@ class _ContextManager(object): saved_context: Context def __init__(self, new_context: Context) -> None: ... def __enter__(self) -> Context: ... - def __exit__(self, t: Type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... -_TrapType = Type[DecimalException] +_TrapType = type[DecimalException] class Context(object): prec: int @@ -157,19 +157,19 @@ class Context(object): Emax: int capitals: int _clamp: int - traps: Dict[_TrapType, bool] - flags: Dict[_TrapType, bool] + traps: dict[_TrapType, bool] + flags: dict[_TrapType, bool] def __init__( self, prec: int | None = ..., rounding: str | None = ..., - traps: None | Dict[_TrapType, bool] | Container[_TrapType] = ..., - flags: None | Dict[_TrapType, bool] | Container[_TrapType] = ..., + traps: None | dict[_TrapType, bool] | Container[_TrapType] = ..., + flags: None | dict[_TrapType, bool] | Container[_TrapType] = ..., Emin: int | None = ..., Emax: int | None = ..., capitals: int | None = ..., _clamp: int | None = ..., - _ignored_flags: List[_TrapType] | None = ..., + _ignored_flags: list[_TrapType] | None = ..., ) -> None: ... def clear_flags(self) -> None: ... def copy(self) -> Context: ... @@ -192,7 +192,7 @@ class Context(object): def copy_sign(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... def divide(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... def divide_int(self, __x: _Decimal, __y: _Decimal) -> Decimal: ... - def divmod(self, __x: _Decimal, __y: _Decimal) -> Tuple[Decimal, Decimal]: ... + def divmod(self, __x: _Decimal, __y: _Decimal) -> tuple[Decimal, Decimal]: ... def exp(self, __x: _Decimal) -> Decimal: ... def fma(self, __x: _Decimal, __y: _Decimal, __z: _Decimal) -> Decimal: ... def is_canonical(self, __x: _Decimal) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/difflib.pyi b/mypy/typeshed/stdlib/@python2/difflib.pyi index 41ffc6a286d1..c4e59f54c66d 100644 --- a/mypy/typeshed/stdlib/@python2/difflib.pyi +++ b/mypy/typeshed/stdlib/@python2/difflib.pyi @@ -1,19 +1,4 @@ -from typing import ( - Any, - AnyStr, - Callable, - Generic, - Iterable, - Iterator, - List, - NamedTuple, - Sequence, - Text, - Tuple, - TypeVar, - Union, - overload, -) +from typing import Any, AnyStr, Callable, Generic, Iterable, Iterator, NamedTuple, Sequence, Text, TypeVar, Union, overload _T = TypeVar("_T") @@ -35,9 +20,9 @@ class SequenceMatcher(Generic[_T]): def set_seq1(self, a: Sequence[_T]) -> None: ... def set_seq2(self, b: Sequence[_T]) -> None: ... def find_longest_match(self, alo: int, ahi: int, blo: int, bhi: int) -> Match: ... - def get_matching_blocks(self) -> List[Match]: ... - def get_opcodes(self) -> List[Tuple[str, int, int, int, int]]: ... - def get_grouped_opcodes(self, n: int = ...) -> Iterable[List[Tuple[str, int, int, int, int]]]: ... + def get_matching_blocks(self) -> list[Match]: ... + def get_opcodes(self) -> list[tuple[str, int, int, int, int]]: ... + def get_grouped_opcodes(self, n: int = ...) -> Iterable[list[tuple[str, int, int, int, int]]]: ... def ratio(self) -> float: ... def quick_ratio(self) -> float: ... def real_quick_ratio(self) -> float: ... @@ -46,11 +31,11 @@ class SequenceMatcher(Generic[_T]): @overload def get_close_matches( # type: ignore word: AnyStr, possibilities: Iterable[AnyStr], n: int = ..., cutoff: float = ... -) -> List[AnyStr]: ... +) -> list[AnyStr]: ... @overload def get_close_matches( word: Sequence[_T], possibilities: Iterable[Sequence[_T]], n: int = ..., cutoff: float = ... -) -> List[Sequence[_T]]: ... +) -> list[Sequence[_T]]: ... class Differ: def __init__(self, linejunk: _JunkCallback | None = ..., charjunk: _JunkCallback | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/dircache.pyi b/mypy/typeshed/stdlib/@python2/dircache.pyi index 366909d87133..dc1e129648e8 100644 --- a/mypy/typeshed/stdlib/@python2/dircache.pyi +++ b/mypy/typeshed/stdlib/@python2/dircache.pyi @@ -1,7 +1,7 @@ -from typing import List, MutableSequence, Text +from typing import MutableSequence, Text def reset() -> None: ... -def listdir(path: Text) -> List[str]: ... +def listdir(path: Text) -> list[str]: ... opendir = listdir diff --git a/mypy/typeshed/stdlib/@python2/dis.pyi b/mypy/typeshed/stdlib/@python2/dis.pyi index 1d6537667a60..f6be1a8dfa83 100644 --- a/mypy/typeshed/stdlib/@python2/dis.pyi +++ b/mypy/typeshed/stdlib/@python2/dis.pyi @@ -13,17 +13,17 @@ from opcode import ( opmap as opmap, opname as opname, ) -from typing import Any, Callable, Dict, Iterator, List, Tuple, Union +from typing import Any, Callable, Iterator, Union # Strictly this should not have to include Callable, but mypy doesn't use FunctionType # for functions (python/mypy#3171) _have_code = Union[types.MethodType, types.FunctionType, types.CodeType, type, Callable[..., Any]] _have_code_or_string = Union[_have_code, str, bytes] -COMPILER_FLAG_NAMES: Dict[int, str] +COMPILER_FLAG_NAMES: dict[int, str] -def findlabels(code: _have_code) -> List[int]: ... -def findlinestarts(code: _have_code) -> Iterator[Tuple[int, int]]: ... +def findlabels(code: _have_code) -> list[int]: ... +def findlinestarts(code: _have_code) -> Iterator[tuple[int, int]]: ... def dis(x: _have_code_or_string = ...) -> None: ... def distb(tb: types.TracebackType = ...) -> None: ... def disassemble(co: _have_code, lasti: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi b/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi index b0539bf9e5dc..7c7023ed0b65 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/ccompiler.pyi @@ -1,11 +1,11 @@ -from typing import Any, Callable, List, Optional, Tuple, Union +from typing import Any, Callable, Optional, Union -_Macro = Union[Tuple[str], Tuple[str, Optional[str]]] +_Macro = Union[tuple[str], tuple[str, Optional[str]]] def gen_lib_options( - compiler: CCompiler, library_dirs: List[str], runtime_library_dirs: List[str], libraries: List[str] -) -> List[str]: ... -def gen_preprocess_options(macros: List[_Macro], include_dirs: List[str]) -> List[str]: ... + compiler: CCompiler, library_dirs: list[str], runtime_library_dirs: list[str], libraries: list[str] +) -> list[str]: ... +def gen_preprocess_options(macros: list[_Macro], include_dirs: list[str]) -> list[str]: ... def get_default_compiler(osname: str | None = ..., platform: str | None = ...) -> str: ... def new_compiler( plat: str | None = ..., compiler: str | None = ..., verbose: int = ..., dry_run: int = ..., force: int = ... @@ -17,34 +17,34 @@ class CCompiler: force: bool verbose: bool output_dir: str | None - macros: List[_Macro] - include_dirs: List[str] - libraries: List[str] - library_dirs: List[str] - runtime_library_dirs: List[str] - objects: List[str] + macros: list[_Macro] + include_dirs: list[str] + libraries: list[str] + library_dirs: list[str] + runtime_library_dirs: list[str] + objects: list[str] def __init__(self, verbose: int = ..., dry_run: int = ..., force: int = ...) -> None: ... def add_include_dir(self, dir: str) -> None: ... - def set_include_dirs(self, dirs: List[str]) -> None: ... + def set_include_dirs(self, dirs: list[str]) -> None: ... def add_library(self, libname: str) -> None: ... - def set_libraries(self, libnames: List[str]) -> None: ... + def set_libraries(self, libnames: list[str]) -> None: ... def add_library_dir(self, dir: str) -> None: ... - def set_library_dirs(self, dirs: List[str]) -> None: ... + def set_library_dirs(self, dirs: list[str]) -> None: ... def add_runtime_library_dir(self, dir: str) -> None: ... - def set_runtime_library_dirs(self, dirs: List[str]) -> None: ... + def set_runtime_library_dirs(self, dirs: list[str]) -> None: ... def define_macro(self, name: str, value: str | None = ...) -> None: ... def undefine_macro(self, name: str) -> None: ... def add_link_object(self, object: str) -> None: ... - def set_link_objects(self, objects: List[str]) -> None: ... - def detect_language(self, sources: str | List[str]) -> str | None: ... - def find_library_file(self, dirs: List[str], lib: str, debug: bool = ...) -> str | None: ... + def set_link_objects(self, objects: list[str]) -> None: ... + def detect_language(self, sources: str | list[str]) -> str | None: ... + def find_library_file(self, dirs: list[str], lib: str, debug: bool = ...) -> str | None: ... def has_function( self, funcname: str, - includes: List[str] | None = ..., - include_dirs: List[str] | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., + includes: list[str] | None = ..., + include_dirs: list[str] | None = ..., + libraries: list[str] | None = ..., + library_dirs: list[str] | None = ..., ) -> bool: ... def library_dir_option(self, dir: str) -> str: ... def library_option(self, lib: str) -> str: ... @@ -52,18 +52,18 @@ class CCompiler: def set_executables(self, **args: str) -> None: ... def compile( self, - sources: List[str], + sources: list[str], output_dir: str | None = ..., macros: _Macro | None = ..., - include_dirs: List[str] | None = ..., + include_dirs: list[str] | None = ..., debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., - depends: List[str] | None = ..., - ) -> List[str]: ... + extra_preargs: list[str] | None = ..., + extra_postargs: list[str] | None = ..., + depends: list[str] | None = ..., + ) -> list[str]: ... def create_static_lib( self, - objects: List[str], + objects: list[str], output_libname: str, output_dir: str | None = ..., debug: bool = ..., @@ -72,59 +72,59 @@ class CCompiler: def link( self, target_desc: str, - objects: List[str], + objects: list[str], output_filename: str, output_dir: str | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., - runtime_library_dirs: List[str] | None = ..., - export_symbols: List[str] | None = ..., + libraries: list[str] | None = ..., + library_dirs: list[str] | None = ..., + runtime_library_dirs: list[str] | None = ..., + export_symbols: list[str] | None = ..., debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., + extra_preargs: list[str] | None = ..., + extra_postargs: list[str] | None = ..., build_temp: str | None = ..., target_lang: str | None = ..., ) -> None: ... def link_executable( self, - objects: List[str], + objects: list[str], output_progname: str, output_dir: str | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., - runtime_library_dirs: List[str] | None = ..., + libraries: list[str] | None = ..., + library_dirs: list[str] | None = ..., + runtime_library_dirs: list[str] | None = ..., debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., + extra_preargs: list[str] | None = ..., + extra_postargs: list[str] | None = ..., target_lang: str | None = ..., ) -> None: ... def link_shared_lib( self, - objects: List[str], + objects: list[str], output_libname: str, output_dir: str | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., - runtime_library_dirs: List[str] | None = ..., - export_symbols: List[str] | None = ..., + libraries: list[str] | None = ..., + library_dirs: list[str] | None = ..., + runtime_library_dirs: list[str] | None = ..., + export_symbols: list[str] | None = ..., debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., + extra_preargs: list[str] | None = ..., + extra_postargs: list[str] | None = ..., build_temp: str | None = ..., target_lang: str | None = ..., ) -> None: ... def link_shared_object( self, - objects: List[str], + objects: list[str], output_filename: str, output_dir: str | None = ..., - libraries: List[str] | None = ..., - library_dirs: List[str] | None = ..., - runtime_library_dirs: List[str] | None = ..., - export_symbols: List[str] | None = ..., + libraries: list[str] | None = ..., + library_dirs: list[str] | None = ..., + runtime_library_dirs: list[str] | None = ..., + export_symbols: list[str] | None = ..., debug: bool = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., + extra_preargs: list[str] | None = ..., + extra_postargs: list[str] | None = ..., build_temp: str | None = ..., target_lang: str | None = ..., ) -> None: ... @@ -132,17 +132,17 @@ class CCompiler: self, source: str, output_file: str | None = ..., - macros: List[_Macro] | None = ..., - include_dirs: List[str] | None = ..., - extra_preargs: List[str] | None = ..., - extra_postargs: List[str] | None = ..., + macros: list[_Macro] | None = ..., + include_dirs: list[str] | None = ..., + extra_preargs: list[str] | None = ..., + extra_postargs: list[str] | None = ..., ) -> None: ... def executable_filename(self, basename: str, strip_dir: int = ..., output_dir: str = ...) -> str: ... def library_filename(self, libname: str, lib_type: str = ..., strip_dir: int = ..., output_dir: str = ...) -> str: ... - def object_filenames(self, source_filenames: List[str], strip_dir: int = ..., output_dir: str = ...) -> List[str]: ... + def object_filenames(self, source_filenames: list[str], strip_dir: int = ..., output_dir: str = ...) -> list[str]: ... def shared_object_filename(self, basename: str, strip_dir: int = ..., output_dir: str = ...) -> str: ... - def execute(self, func: Callable[..., None], args: Tuple[Any, ...], msg: str | None = ..., level: int = ...) -> None: ... - def spawn(self, cmd: List[str]) -> None: ... + def execute(self, func: Callable[..., None], args: tuple[Any, ...], msg: str | None = ..., level: int = ...) -> None: ... + def spawn(self, cmd: list[str]) -> None: ... def mkpath(self, name: str, mode: int = ...) -> None: ... def move_file(self, src: str, dst: str) -> str: ... def announce(self, msg: str, level: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/cmd.pyi b/mypy/typeshed/stdlib/@python2/distutils/cmd.pyi index d4e90bf69970..3b5b85912cbe 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/cmd.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/cmd.pyi @@ -1,9 +1,9 @@ from abc import abstractmethod from distutils.dist import Distribution -from typing import Any, Callable, Iterable, List, Text, Tuple +from typing import Any, Callable, Iterable, Text class Command: - sub_commands: List[Tuple[str, Callable[[Command], bool] | None]] + sub_commands: list[tuple[str, Callable[[Command], bool] | None]] def __init__(self, dist: Distribution) -> None: ... @abstractmethod def initialize_options(self) -> None: ... @@ -14,15 +14,15 @@ class Command: def announce(self, msg: Text, level: int = ...) -> None: ... def debug_print(self, msg: Text) -> None: ... def ensure_string(self, option: str, default: str | None = ...) -> None: ... - def ensure_string_list(self, option: str | List[str]) -> None: ... + def ensure_string_list(self, option: str | list[str]) -> None: ... def ensure_filename(self, option: str) -> None: ... def ensure_dirname(self, option: str) -> None: ... def get_command_name(self) -> str: ... - def set_undefined_options(self, src_cmd: Text, *option_pairs: Tuple[str, str]) -> None: ... + def set_undefined_options(self, src_cmd: Text, *option_pairs: tuple[str, str]) -> None: ... def get_finalized_command(self, command: Text, create: int = ...) -> Command: ... def reinitialize_command(self, command: Command | Text, reinit_subcommands: int = ...) -> Command: ... def run_command(self, command: Text) -> None: ... - def get_sub_commands(self) -> List[str]: ... + def get_sub_commands(self) -> list[str]: ... def warn(self, msg: Text) -> None: ... def execute(self, func: Callable[..., Any], args: Iterable[Any], msg: Text | None = ..., level: int = ...) -> None: ... def mkpath(self, name: str, mode: int = ...) -> None: ... @@ -34,7 +34,7 @@ class Command: preserve_times: int = ..., link: str | None = ..., level: Any = ..., - ) -> Tuple[str, bool]: ... # level is not used + ) -> tuple[str, bool]: ... # level is not used def copy_tree( self, infile: str, @@ -43,7 +43,7 @@ class Command: preserve_times: int = ..., preserve_symlinks: int = ..., level: Any = ..., - ) -> List[str]: ... # level is not used + ) -> list[str]: ... # level is not used def move_file(self, src: str, dst: str, level: Any = ...) -> str: ... # level is not used def spawn(self, cmd: Iterable[str], search_path: int = ..., level: Any = ...) -> None: ... # level is not used def make_archive( @@ -57,10 +57,10 @@ class Command: ) -> str: ... def make_file( self, - infiles: str | List[str] | Tuple[str], + infiles: str | list[str] | tuple[str], outfile: str, func: Callable[..., Any], - args: List[Any], + args: list[Any], exec_msg: str | None = ..., skip_msg: str | None = ..., level: Any = ..., diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/bdist_msi.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/bdist_msi.pyi index a761792018a9..150229fb01c9 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/command/bdist_msi.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/command/bdist_msi.pyi @@ -1,6 +1,8 @@ -from distutils.cmd import Command +import sys -class bdist_msi(Command): - def initialize_options(self) -> None: ... - def finalize_options(self) -> None: ... - def run(self) -> None: ... +if sys.platform == "win32": + from distutils.cmd import Command + class bdist_msi(Command): + def initialize_options(self) -> None: ... + def finalize_options(self) -> None: ... + def run(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/config.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/config.pyi index d0fd762e83b2..790a8b485a56 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/command/config.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/command/config.pyi @@ -3,14 +3,14 @@ from distutils.ccompiler import CCompiler from distutils.core import Command as Command from distutils.errors import DistutilsExecError as DistutilsExecError from distutils.sysconfig import customize_compiler as customize_compiler -from typing import Dict, List, Pattern, Sequence, Tuple +from typing import Pattern, Sequence -LANG_EXT: Dict[str, str] +LANG_EXT: dict[str, str] class config(Command): description: str = ... # Tuple is full name, short name, description - user_options: Sequence[Tuple[str, str | None, str]] = ... + user_options: Sequence[tuple[str, str | None, str]] = ... compiler: str | CCompiler | None = ... cc: str | None = ... include_dirs: Sequence[str] | None = ... @@ -74,7 +74,7 @@ class config(Command): library_dirs: Sequence[str] | None = ..., headers: Sequence[str] | None = ..., include_dirs: Sequence[str] | None = ..., - other_libraries: List[str] = ..., + other_libraries: list[str] = ..., ) -> bool: ... def check_header( self, header: str, include_dirs: Sequence[str] | None = ..., library_dirs: Sequence[str] | None = ..., lang: str = ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/install_egg_info.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/install_egg_info.pyi index bf3d0737f244..1bee1ed07e45 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/command/install_egg_info.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/command/install_egg_info.pyi @@ -1,10 +1,10 @@ from distutils.cmd import Command -from typing import ClassVar, List, Tuple +from typing import ClassVar class install_egg_info(Command): description: ClassVar[str] - user_options: ClassVar[List[Tuple[str, str | None, str]]] + user_options: ClassVar[list[tuple[str, str | None, str]]] def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... def run(self) -> None: ... - def get_outputs(self) -> List[str]: ... + def get_outputs(self) -> list[str]: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/command/upload.pyi b/mypy/typeshed/stdlib/@python2/distutils/command/upload.pyi index 3835d9fd6ec6..005db872b0bf 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/command/upload.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/command/upload.pyi @@ -1,8 +1,8 @@ from distutils.config import PyPIRCCommand -from typing import ClassVar, List, Tuple +from typing import ClassVar class upload(PyPIRCCommand): description: ClassVar[str] - boolean_options: ClassVar[List[str]] + boolean_options: ClassVar[list[str]] def run(self) -> None: ... def upload_file(self, command, pyversion, filename) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/config.pyi b/mypy/typeshed/stdlib/@python2/distutils/config.pyi index bcd626c81d48..5814a82841cc 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/config.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/config.pyi @@ -1,6 +1,6 @@ from abc import abstractmethod from distutils.cmd import Command -from typing import ClassVar, List, Tuple +from typing import ClassVar DEFAULT_PYPIRC: str @@ -9,8 +9,8 @@ class PyPIRCCommand(Command): DEFAULT_REALM: ClassVar[str] repository: None realm: None - user_options: ClassVar[List[Tuple[str, str | None, str]]] - boolean_options: ClassVar[List[str]] + user_options: ClassVar[list[tuple[str, str | None, str]]] + boolean_options: ClassVar[list[str]] def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... @abstractmethod diff --git a/mypy/typeshed/stdlib/@python2/distutils/core.pyi b/mypy/typeshed/stdlib/@python2/distutils/core.pyi index 48bd7b5018bc..6564c9a86ded 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/core.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/core.pyi @@ -1,7 +1,7 @@ from distutils.cmd import Command as Command from distutils.dist import Distribution as Distribution from distutils.extension import Extension as Extension -from typing import Any, List, Mapping, Tuple, Type +from typing import Any, Mapping def setup( *, @@ -15,34 +15,34 @@ def setup( maintainer_email: str = ..., url: str = ..., download_url: str = ..., - packages: List[str] = ..., - py_modules: List[str] = ..., - scripts: List[str] = ..., - ext_modules: List[Extension] = ..., - classifiers: List[str] = ..., - distclass: Type[Distribution] = ..., + packages: list[str] = ..., + py_modules: list[str] = ..., + scripts: list[str] = ..., + ext_modules: list[Extension] = ..., + classifiers: list[str] = ..., + distclass: type[Distribution] = ..., script_name: str = ..., - script_args: List[str] = ..., + script_args: list[str] = ..., options: Mapping[str, Any] = ..., license: str = ..., - keywords: List[str] | str = ..., - platforms: List[str] | str = ..., - cmdclass: Mapping[str, Type[Command]] = ..., - data_files: List[Tuple[str, List[str]]] = ..., + keywords: list[str] | str = ..., + platforms: list[str] | str = ..., + cmdclass: Mapping[str, type[Command]] = ..., + data_files: list[tuple[str, list[str]]] = ..., package_dir: Mapping[str, str] = ..., - obsoletes: List[str] = ..., - provides: List[str] = ..., - requires: List[str] = ..., - command_packages: List[str] = ..., - command_options: Mapping[str, Mapping[str, Tuple[Any, Any]]] = ..., - package_data: Mapping[str, List[str]] = ..., + obsoletes: list[str] = ..., + provides: list[str] = ..., + requires: list[str] = ..., + command_packages: list[str] = ..., + command_options: Mapping[str, Mapping[str, tuple[Any, Any]]] = ..., + package_data: Mapping[str, list[str]] = ..., include_package_data: bool = ..., - libraries: List[str] = ..., - headers: List[str] = ..., + libraries: list[str] = ..., + headers: list[str] = ..., ext_package: str = ..., - include_dirs: List[str] = ..., + include_dirs: list[str] = ..., password: str = ..., fullname: str = ..., **attrs: Any, ) -> None: ... -def run_setup(script_name: str, script_args: List[str] | None = ..., stop_after: str = ...) -> Distribution: ... +def run_setup(script_name: str, script_args: list[str] | None = ..., stop_after: str = ...) -> Distribution: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/dep_util.pyi b/mypy/typeshed/stdlib/@python2/distutils/dep_util.pyi index 6f779d540e5e..929d6ffd0c81 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/dep_util.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/dep_util.pyi @@ -1,5 +1,3 @@ -from typing import List, Tuple - def newer(source: str, target: str) -> bool: ... -def newer_pairwise(sources: List[str], targets: List[str]) -> List[Tuple[str, str]]: ... -def newer_group(sources: List[str], target: str, missing: str = ...) -> bool: ... +def newer_pairwise(sources: list[str], targets: list[str]) -> list[tuple[str, str]]: ... +def newer_group(sources: list[str], target: str, missing: str = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/dir_util.pyi b/mypy/typeshed/stdlib/@python2/distutils/dir_util.pyi index 4c4a22102558..ffe5ff1cfbd4 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/dir_util.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/dir_util.pyi @@ -1,7 +1,5 @@ -from typing import List - -def mkpath(name: str, mode: int = ..., verbose: int = ..., dry_run: int = ...) -> List[str]: ... -def create_tree(base_dir: str, files: List[str], mode: int = ..., verbose: int = ..., dry_run: int = ...) -> None: ... +def mkpath(name: str, mode: int = ..., verbose: int = ..., dry_run: int = ...) -> list[str]: ... +def create_tree(base_dir: str, files: list[str], mode: int = ..., verbose: int = ..., dry_run: int = ...) -> None: ... def copy_tree( src: str, dst: str, @@ -11,5 +9,5 @@ def copy_tree( update: int = ..., verbose: int = ..., dry_run: int = ..., -) -> List[str]: ... +) -> list[str]: ... def remove_tree(directory: str, verbose: int = ..., dry_run: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/dist.pyi b/mypy/typeshed/stdlib/@python2/distutils/dist.pyi index adba8f093569..8e6eeafc15b3 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/dist.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/dist.pyi @@ -1,9 +1,9 @@ from distutils.cmd import Command -from typing import Any, Dict, Iterable, Mapping, Text, Tuple, Type +from typing import Any, Iterable, Mapping, Text class Distribution: - cmdclass: Dict[str, Type[Command]] + cmdclass: dict[str, type[Command]] def __init__(self, attrs: Mapping[str, Any] | None = ...) -> None: ... - def get_option_dict(self, command: str) -> Dict[str, Tuple[str, Text]]: ... + def get_option_dict(self, command: str) -> dict[str, tuple[str, Text]]: ... def parse_config_files(self, filenames: Iterable[Text] | None = ...) -> None: ... def get_command_obj(self, command: str, create: bool = ...) -> Command | None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/extension.pyi b/mypy/typeshed/stdlib/@python2/distutils/extension.pyi index 9335fad86418..cff84ef59b6b 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/extension.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/extension.pyi @@ -1,21 +1,19 @@ -from typing import List, Tuple - class Extension: def __init__( self, name: str, - sources: List[str], - include_dirs: List[str] = ..., - define_macros: List[Tuple[str, str | None]] = ..., - undef_macros: List[str] = ..., - library_dirs: List[str] = ..., - libraries: List[str] = ..., - runtime_library_dirs: List[str] = ..., - extra_objects: List[str] = ..., - extra_compile_args: List[str] = ..., - extra_link_args: List[str] = ..., - export_symbols: List[str] = ..., + sources: list[str], + include_dirs: list[str] = ..., + define_macros: list[tuple[str, str | None]] = ..., + undef_macros: list[str] = ..., + library_dirs: list[str] = ..., + libraries: list[str] = ..., + runtime_library_dirs: list[str] = ..., + extra_objects: list[str] = ..., + extra_compile_args: list[str] = ..., + extra_link_args: list[str] = ..., + export_symbols: list[str] = ..., swig_opts: str | None = ..., # undocumented - depends: List[str] = ..., + depends: list[str] = ..., language: str = ..., ) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/fancy_getopt.pyi b/mypy/typeshed/stdlib/@python2/distutils/fancy_getopt.pyi index d0e3309c2d77..02301aed63f4 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/fancy_getopt.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/fancy_getopt.pyi @@ -1,21 +1,21 @@ -from typing import Any, List, Mapping, Optional, Tuple, overload +from typing import Any, Mapping, Optional, overload -_Option = Tuple[str, Optional[str], str] -_GR = Tuple[List[str], OptionDummy] +_Option = tuple[str, Optional[str], str] +_GR = tuple[list[str], OptionDummy] def fancy_getopt( - options: List[_Option], negative_opt: Mapping[_Option, _Option], object: Any, args: List[str] | None -) -> List[str] | _GR: ... -def wrap_text(text: str, width: int) -> List[str]: ... + options: list[_Option], negative_opt: Mapping[_Option, _Option], object: Any, args: list[str] | None +) -> list[str] | _GR: ... +def wrap_text(text: str, width: int) -> list[str]: ... class FancyGetopt: - def __init__(self, option_table: List[_Option] | None = ...) -> None: ... + def __init__(self, option_table: list[_Option] | None = ...) -> None: ... # TODO kinda wrong, `getopt(object=object())` is invalid @overload - def getopt(self, args: List[str] | None = ...) -> _GR: ... + def getopt(self, args: list[str] | None = ...) -> _GR: ... @overload - def getopt(self, args: List[str] | None, object: Any) -> List[str]: ... - def get_option_order(self) -> List[Tuple[str, str]]: ... - def generate_help(self, header: str | None = ...) -> List[str]: ... + def getopt(self, args: list[str] | None, object: Any) -> list[str]: ... + def get_option_order(self) -> list[tuple[str, str]]: ... + def generate_help(self, header: str | None = ...) -> list[str]: ... class OptionDummy: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/file_util.pyi b/mypy/typeshed/stdlib/@python2/distutils/file_util.pyi index cfe840e71040..a7f24105a678 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/file_util.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/file_util.pyi @@ -1,4 +1,4 @@ -from typing import Sequence, Tuple +from typing import Sequence def copy_file( src: str, @@ -9,6 +9,6 @@ def copy_file( link: str | None = ..., verbose: bool = ..., dry_run: bool = ..., -) -> Tuple[str, str]: ... +) -> tuple[str, str]: ... def move_file(src: str, dst: str, verbose: bool = ..., dry_run: bool = ...) -> str: ... def write_file(filename: str, contents: Sequence[str]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/spawn.pyi b/mypy/typeshed/stdlib/@python2/distutils/spawn.pyi index 0fffc5402c62..dda05ad7e85a 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/spawn.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/spawn.pyi @@ -1,4 +1,2 @@ -from typing import List - -def spawn(cmd: List[str], search_path: bool = ..., verbose: bool = ..., dry_run: bool = ...) -> None: ... +def spawn(cmd: list[str], search_path: bool = ..., verbose: bool = ..., dry_run: bool = ...) -> None: ... def find_executable(executable: str, path: str | None = ...) -> str | None: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/text_file.pyi b/mypy/typeshed/stdlib/@python2/distutils/text_file.pyi index 26ba5a6fabb6..364bcf9ff154 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/text_file.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/text_file.pyi @@ -1,4 +1,4 @@ -from typing import IO, List, Tuple +from typing import IO class TextFile: def __init__( @@ -15,7 +15,7 @@ class TextFile: ) -> None: ... def open(self, filename: str) -> None: ... def close(self) -> None: ... - def warn(self, msg: str, line: List[int] | Tuple[int, int] | int = ...) -> None: ... + def warn(self, msg: str, line: list[int] | tuple[int, int] | int = ...) -> None: ... def readline(self) -> str | None: ... - def readlines(self) -> List[str]: ... + def readlines(self) -> list[str]: ... def unreadline(self, line: str) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/distutils/util.pyi b/mypy/typeshed/stdlib/@python2/distutils/util.pyi index c0882d1dd1cb..935a695e58db 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/util.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/util.pyi @@ -1,17 +1,18 @@ -from typing import Any, Callable, List, Mapping, Tuple +from typing import Any, Callable, Mapping +from typing_extensions import Literal def get_platform() -> str: ... def convert_path(pathname: str) -> str: ... def change_root(new_root: str, pathname: str) -> str: ... def check_environ() -> None: ... def subst_vars(s: str, local_vars: Mapping[str, str]) -> None: ... -def split_quoted(s: str) -> List[str]: ... +def split_quoted(s: str) -> list[str]: ... def execute( - func: Callable[..., None], args: Tuple[Any, ...], msg: str | None = ..., verbose: bool = ..., dry_run: bool = ... + func: Callable[..., None], args: tuple[Any, ...], msg: str | None = ..., verbose: bool = ..., dry_run: bool = ... ) -> None: ... -def strtobool(val: str) -> bool: ... +def strtobool(val: str) -> Literal[0, 1]: ... def byte_compile( - py_files: List[str], + py_files: list[str], optimize: int = ..., force: bool = ..., prefix: str | None = ..., diff --git a/mypy/typeshed/stdlib/@python2/distutils/version.pyi b/mypy/typeshed/stdlib/@python2/distutils/version.pyi index dd0969b8635f..b3bb9ea4909f 100644 --- a/mypy/typeshed/stdlib/@python2/distutils/version.pyi +++ b/mypy/typeshed/stdlib/@python2/distutils/version.pyi @@ -1,14 +1,14 @@ +from _typeshed import Self from abc import abstractmethod -from typing import Pattern, Text, Tuple, TypeVar +from typing import Pattern, Text, TypeVar _T = TypeVar("_T", bound=Version) class Version: - def __repr__(self) -> str: ... @abstractmethod def __init__(self, vstring: Text | None = ...) -> None: ... @abstractmethod - def parse(self: _T, vstring: Text) -> _T: ... + def parse(self: Self, vstring: Text) -> Self: ... @abstractmethod def __str__(self) -> str: ... @abstractmethod @@ -16,18 +16,18 @@ class Version: class StrictVersion(Version): version_re: Pattern[str] - version: Tuple[int, int, int] - prerelease: Tuple[Text, int] | None + version: tuple[int, int, int] + prerelease: tuple[Text, int] | None def __init__(self, vstring: Text | None = ...) -> None: ... - def parse(self: _T, vstring: Text) -> _T: ... - def __str__(self) -> str: ... + def parse(self: Self, vstring: Text) -> Self: ... + def __str__(self) -> str: ... # noqa Y029 def __cmp__(self: _T, other: _T | str) -> bool: ... class LooseVersion(Version): component_re: Pattern[str] vstring: Text - version: Tuple[Text | int, ...] + version: tuple[Text | int, ...] def __init__(self, vstring: Text | None = ...) -> None: ... - def parse(self: _T, vstring: Text) -> _T: ... - def __str__(self) -> str: ... + def parse(self: Self, vstring: Text) -> Self: ... + def __str__(self) -> str: ... # noqa Y029 def __cmp__(self: _T, other: _T | str) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/doctest.pyi b/mypy/typeshed/stdlib/@python2/doctest.pyi index 6c3b922244f4..9f95d122eea5 100644 --- a/mypy/typeshed/stdlib/@python2/doctest.pyi +++ b/mypy/typeshed/stdlib/@python2/doctest.pyi @@ -1,12 +1,12 @@ import types import unittest -from typing import Any, Callable, Dict, List, NamedTuple, Tuple, Type +from typing import Any, Callable, NamedTuple class TestResults(NamedTuple): failed: int attempted: int -OPTIONFLAGS_BY_NAME: Dict[str, int] +OPTIONFLAGS_BY_NAME: dict[str, int] def register_optionflag(name: str) -> int: ... @@ -34,7 +34,7 @@ class Example: exc_msg: str | None lineno: int indent: int - options: Dict[int, bool] + options: dict[int, bool] def __init__( self, source: str, @@ -42,21 +42,21 @@ class Example: exc_msg: str | None = ..., lineno: int = ..., indent: int = ..., - options: Dict[int, bool] | None = ..., + options: dict[int, bool] | None = ..., ) -> None: ... def __hash__(self) -> int: ... class DocTest: - examples: List[Example] - globs: Dict[str, Any] + examples: list[Example] + globs: dict[str, Any] name: str filename: str | None lineno: int | None docstring: str | None def __init__( self, - examples: List[Example], - globs: Dict[str, Any], + examples: list[Example], + globs: dict[str, Any], name: str, filename: str | None, lineno: int | None, @@ -66,9 +66,9 @@ class DocTest: def __lt__(self, other: DocTest) -> bool: ... class DocTestParser: - def parse(self, string: str, name: str = ...) -> List[str | Example]: ... - def get_doctest(self, string: str, globs: Dict[str, Any], name: str, filename: str | None, lineno: int | None) -> DocTest: ... - def get_examples(self, string: str, name: str = ...) -> List[Example]: ... + def parse(self, string: str, name: str = ...) -> list[str | Example]: ... + def get_doctest(self, string: str, globs: dict[str, Any], name: str, filename: str | None, lineno: int | None) -> DocTest: ... + def get_examples(self, string: str, name: str = ...) -> list[Example]: ... class DocTestFinder: def __init__( @@ -79,12 +79,12 @@ class DocTestFinder: obj: object, name: str | None = ..., module: None | bool | types.ModuleType = ..., - globs: Dict[str, Any] | None = ..., - extraglobs: Dict[str, Any] | None = ..., - ) -> List[DocTest]: ... + globs: dict[str, Any] | None = ..., + extraglobs: dict[str, Any] | None = ..., + ) -> list[DocTest]: ... _Out = Callable[[str], Any] -_ExcInfo = Tuple[Type[BaseException], BaseException, types.TracebackType] +_ExcInfo = tuple[type[BaseException], BaseException, types.TracebackType] class DocTestRunner: DIVIDER: str @@ -127,11 +127,11 @@ master: DocTestRunner | None def testmod( m: types.ModuleType | None = ..., name: str | None = ..., - globs: Dict[str, Any] | None = ..., + globs: dict[str, Any] | None = ..., verbose: bool | None = ..., report: bool = ..., optionflags: int = ..., - extraglobs: Dict[str, Any] | None = ..., + extraglobs: dict[str, Any] | None = ..., raise_on_error: bool = ..., exclude_empty: bool = ..., ) -> TestResults: ... @@ -140,17 +140,17 @@ def testfile( module_relative: bool = ..., name: str | None = ..., package: None | str | types.ModuleType = ..., - globs: Dict[str, Any] | None = ..., + globs: dict[str, Any] | None = ..., verbose: bool | None = ..., report: bool = ..., optionflags: int = ..., - extraglobs: Dict[str, Any] | None = ..., + extraglobs: dict[str, Any] | None = ..., raise_on_error: bool = ..., parser: DocTestParser = ..., encoding: str | None = ..., ) -> TestResults: ... def run_docstring_examples( - f: object, globs: Dict[str, Any], verbose: bool = ..., name: str = ..., compileflags: int | None = ..., optionflags: int = ... + f: object, globs: dict[str, Any], verbose: bool = ..., name: str = ..., compileflags: int | None = ..., optionflags: int = ... ) -> None: ... def set_unittest_reportflags(flags: int) -> int: ... @@ -182,8 +182,8 @@ _DocTestSuite = unittest.TestSuite def DocTestSuite( module: None | str | types.ModuleType = ..., - globs: Dict[str, Any] | None = ..., - extraglobs: Dict[str, Any] | None = ..., + globs: dict[str, Any] | None = ..., + extraglobs: dict[str, Any] | None = ..., test_finder: DocTestFinder | None = ..., **options: Any, ) -> _DocTestSuite: ... @@ -196,7 +196,7 @@ def DocFileTest( path: str, module_relative: bool = ..., package: None | str | types.ModuleType = ..., - globs: Dict[str, Any] | None = ..., + globs: dict[str, Any] | None = ..., parser: DocTestParser = ..., encoding: str | None = ..., **options: Any, @@ -204,6 +204,6 @@ def DocFileTest( def DocFileSuite(*paths: str, **kw: Any) -> _DocTestSuite: ... def script_from_examples(s: str) -> str: ... def testsource(module: None | str | types.ModuleType, name: str) -> str: ... -def debug_src(src: str, pm: bool = ..., globs: Dict[str, Any] | None = ...) -> None: ... -def debug_script(src: str, pm: bool = ..., globs: Dict[str, Any] | None = ...) -> None: ... +def debug_src(src: str, pm: bool = ..., globs: dict[str, Any] | None = ...) -> None: ... +def debug_script(src: str, pm: bool = ..., globs: dict[str, Any] | None = ...) -> None: ... def debug(module: None | str | types.ModuleType, name: str, pm: bool = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/dummy_thread.pyi b/mypy/typeshed/stdlib/@python2/dummy_thread.pyi index 0a28b3aaeeb9..1bd324b7eaaf 100644 --- a/mypy/typeshed/stdlib/@python2/dummy_thread.pyi +++ b/mypy/typeshed/stdlib/@python2/dummy_thread.pyi @@ -1,9 +1,9 @@ -from typing import Any, Callable, Dict, NoReturn, Tuple +from typing import Any, Callable, NoReturn class error(Exception): def __init__(self, *args: Any) -> None: ... -def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: Dict[str, Any] = ...) -> None: ... +def start_new_thread(function: Callable[..., Any], args: tuple[Any, ...], kwargs: dict[str, Any] = ...) -> None: ... def exit() -> NoReturn: ... def get_ident() -> int: ... def allocate_lock() -> LockType: ... diff --git a/mypy/typeshed/stdlib/@python2/email/mime/application.pyi b/mypy/typeshed/stdlib/@python2/email/mime/application.pyi index 4245e3e0f980..308b296c4d53 100644 --- a/mypy/typeshed/stdlib/@python2/email/mime/application.pyi +++ b/mypy/typeshed/stdlib/@python2/email/mime/application.pyi @@ -1,7 +1,7 @@ from email.mime.nonmultipart import MIMENonMultipart -from typing import Callable, Optional, Tuple, Union +from typing import Callable, Optional, Union -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] +_ParamsType = Union[str, None, tuple[str, Optional[str], str]] class MIMEApplication(MIMENonMultipart): def __init__( diff --git a/mypy/typeshed/stdlib/@python2/encodings/utf_8.pyi b/mypy/typeshed/stdlib/@python2/encodings/utf_8.pyi index d38bd58d0e43..349b61432eab 100644 --- a/mypy/typeshed/stdlib/@python2/encodings/utf_8.pyi +++ b/mypy/typeshed/stdlib/@python2/encodings/utf_8.pyi @@ -1,11 +1,11 @@ import codecs -from typing import Text, Tuple +from typing import Text class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input: Text, final: bool = ...) -> bytes: ... class IncrementalDecoder(codecs.BufferedIncrementalDecoder): - def _buffer_decode(self, input: bytes, errors: str, final: bool) -> Tuple[Text, int]: ... + def _buffer_decode(self, input: bytes, errors: str, final: bool) -> tuple[Text, int]: ... class StreamWriter(codecs.StreamWriter): ... class StreamReader(codecs.StreamReader): ... diff --git a/mypy/typeshed/stdlib/@python2/fcntl.pyi b/mypy/typeshed/stdlib/@python2/fcntl.pyi index b3730270f1cc..0d9d598ab7c5 100644 --- a/mypy/typeshed/stdlib/@python2/fcntl.pyi +++ b/mypy/typeshed/stdlib/@python2/fcntl.pyi @@ -1,82 +1,83 @@ +import sys from _typeshed import FileDescriptorLike from typing import Any -FASYNC: int -FD_CLOEXEC: int +if sys.platform != "win32": + FASYNC: int + FD_CLOEXEC: int -DN_ACCESS: int -DN_ATTRIB: int -DN_CREATE: int -DN_DELETE: int -DN_MODIFY: int -DN_MULTISHOT: int -DN_RENAME: int -F_DUPFD: int -F_EXLCK: int -F_GETFD: int -F_GETFL: int -F_GETLEASE: int -F_GETLK: int -F_GETLK64: int -F_GETOWN: int -F_GETSIG: int -F_NOTIFY: int -F_RDLCK: int -F_SETFD: int -F_SETFL: int -F_SETLEASE: int -F_SETLK: int -F_SETLK64: int -F_SETLKW: int -F_SETLKW64: int -F_SETOWN: int -F_SETSIG: int -F_SHLCK: int -F_UNLCK: int -F_WRLCK: int -I_ATMARK: int -I_CANPUT: int -I_CKBAND: int -I_FDINSERT: int -I_FIND: int -I_FLUSH: int -I_FLUSHBAND: int -I_GETBAND: int -I_GETCLTIME: int -I_GETSIG: int -I_GRDOPT: int -I_GWROPT: int -I_LINK: int -I_LIST: int -I_LOOK: int -I_NREAD: int -I_PEEK: int -I_PLINK: int -I_POP: int -I_PUNLINK: int -I_PUSH: int -I_RECVFD: int -I_SENDFD: int -I_SETCLTIME: int -I_SETSIG: int -I_SRDOPT: int -I_STR: int -I_SWROPT: int -I_UNLINK: int -LOCK_EX: int -LOCK_MAND: int -LOCK_NB: int -LOCK_READ: int -LOCK_RW: int -LOCK_SH: int -LOCK_UN: int -LOCK_WRITE: int + DN_ACCESS: int + DN_ATTRIB: int + DN_CREATE: int + DN_DELETE: int + DN_MODIFY: int + DN_MULTISHOT: int + DN_RENAME: int + F_DUPFD: int + F_EXLCK: int + F_GETFD: int + F_GETFL: int + F_GETLEASE: int + F_GETLK: int + F_GETLK64: int + F_GETOWN: int + F_GETSIG: int + F_NOTIFY: int + F_RDLCK: int + F_SETFD: int + F_SETFL: int + F_SETLEASE: int + F_SETLK: int + F_SETLK64: int + F_SETLKW: int + F_SETLKW64: int + F_SETOWN: int + F_SETSIG: int + F_SHLCK: int + F_UNLCK: int + F_WRLCK: int + I_ATMARK: int + I_CANPUT: int + I_CKBAND: int + I_FDINSERT: int + I_FIND: int + I_FLUSH: int + I_FLUSHBAND: int + I_GETBAND: int + I_GETCLTIME: int + I_GETSIG: int + I_GRDOPT: int + I_GWROPT: int + I_LINK: int + I_LIST: int + I_LOOK: int + I_NREAD: int + I_PEEK: int + I_PLINK: int + I_POP: int + I_PUNLINK: int + I_PUSH: int + I_RECVFD: int + I_SENDFD: int + I_SETCLTIME: int + I_SETSIG: int + I_SRDOPT: int + I_STR: int + I_SWROPT: int + I_UNLINK: int + LOCK_EX: int + LOCK_MAND: int + LOCK_NB: int + LOCK_READ: int + LOCK_RW: int + LOCK_SH: int + LOCK_UN: int + LOCK_WRITE: int -# TODO All these return either int or bytes depending on the value of -# cmd (not on the type of arg). -def fcntl(fd: FileDescriptorLike, op: int, arg: int | bytes = ...) -> Any: ... - -# TODO: arg: int or read-only buffer interface or read-write buffer interface -def ioctl(fd: FileDescriptorLike, op: int, arg: int | bytes = ..., mutate_flag: bool = ...) -> Any: ... -def flock(fd: FileDescriptorLike, op: int) -> None: ... -def lockf(fd: FileDescriptorLike, op: int, length: int = ..., start: int = ..., whence: int = ...) -> Any: ... + # TODO All these return either int or bytes depending on the value of + # cmd (not on the type of arg). + def fcntl(fd: FileDescriptorLike, op: int, arg: int | bytes = ...) -> Any: ... + # TODO: arg: int or read-only buffer interface or read-write buffer interface + def ioctl(fd: FileDescriptorLike, op: int, arg: int | bytes = ..., mutate_flag: bool = ...) -> Any: ... + def flock(fd: FileDescriptorLike, op: int) -> None: ... + def lockf(fd: FileDescriptorLike, op: int, length: int = ..., start: int = ..., whence: int = ...) -> Any: ... diff --git a/mypy/typeshed/stdlib/@python2/filecmp.pyi b/mypy/typeshed/stdlib/@python2/filecmp.pyi index 0be5596c2bdb..c50faedf2fa1 100644 --- a/mypy/typeshed/stdlib/@python2/filecmp.pyi +++ b/mypy/typeshed/stdlib/@python2/filecmp.pyi @@ -1,11 +1,11 @@ -from typing import AnyStr, Callable, Dict, Generic, Iterable, List, Sequence, Text, Tuple +from typing import AnyStr, Callable, Generic, Iterable, Sequence, Text -DEFAULT_IGNORES: List[str] +DEFAULT_IGNORES: list[str] def cmp(f1: bytes | Text, f2: bytes | Text, shallow: int | bool = ...) -> bool: ... def cmpfiles( a: AnyStr, b: AnyStr, common: Iterable[AnyStr], shallow: int | bool = ... -) -> Tuple[List[AnyStr], List[AnyStr], List[AnyStr]]: ... +) -> tuple[list[AnyStr], list[AnyStr], list[AnyStr]]: ... class dircmp(Generic[AnyStr]): def __init__( @@ -16,22 +16,22 @@ class dircmp(Generic[AnyStr]): hide: Sequence[AnyStr] ignore: Sequence[AnyStr] # These properties are created at runtime by __getattr__ - subdirs: Dict[AnyStr, dircmp[AnyStr]] - same_files: List[AnyStr] - diff_files: List[AnyStr] - funny_files: List[AnyStr] - common_dirs: List[AnyStr] - common_files: List[AnyStr] - common_funny: List[AnyStr] - common: List[AnyStr] - left_only: List[AnyStr] - right_only: List[AnyStr] - left_list: List[AnyStr] - right_list: List[AnyStr] + subdirs: dict[AnyStr, dircmp[AnyStr]] + same_files: list[AnyStr] + diff_files: list[AnyStr] + funny_files: list[AnyStr] + common_dirs: list[AnyStr] + common_files: list[AnyStr] + common_funny: list[AnyStr] + common: list[AnyStr] + left_only: list[AnyStr] + right_only: list[AnyStr] + left_list: list[AnyStr] + right_list: list[AnyStr] def report(self) -> None: ... def report_partial_closure(self) -> None: ... def report_full_closure(self) -> None: ... - methodmap: Dict[str, Callable[[], None]] + methodmap: dict[str, Callable[[], None]] def phase0(self) -> None: ... def phase1(self) -> None: ... def phase2(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/fnmatch.pyi b/mypy/typeshed/stdlib/@python2/fnmatch.pyi index e933b7b2cb62..ead2dd5bf38e 100644 --- a/mypy/typeshed/stdlib/@python2/fnmatch.pyi +++ b/mypy/typeshed/stdlib/@python2/fnmatch.pyi @@ -1,8 +1,8 @@ -from typing import AnyStr, Iterable, List, Union +from typing import AnyStr, Iterable, Union _EitherStr = Union[str, unicode] def fnmatch(filename: _EitherStr, pattern: _EitherStr) -> bool: ... def fnmatchcase(filename: _EitherStr, pattern: _EitherStr) -> bool: ... -def filter(names: Iterable[AnyStr], pattern: _EitherStr) -> List[AnyStr]: ... +def filter(names: Iterable[AnyStr], pattern: _EitherStr) -> list[AnyStr]: ... def translate(pattern: AnyStr) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/@python2/formatter.pyi b/mypy/typeshed/stdlib/@python2/formatter.pyi index da165f2d55e3..f5d8348d08a1 100644 --- a/mypy/typeshed/stdlib/@python2/formatter.pyi +++ b/mypy/typeshed/stdlib/@python2/formatter.pyi @@ -1,8 +1,8 @@ -from typing import IO, Any, Iterable, List, Tuple +from typing import IO, Any, Iterable AS_IS: None -_FontType = Tuple[str, bool, bool, bool] -_StylesType = Tuple[Any, ...] +_FontType = tuple[str, bool, bool, bool] +_StylesType = tuple[Any, ...] class NullFormatter: writer: NullWriter | None @@ -28,9 +28,9 @@ class NullFormatter: class AbstractFormatter: writer: NullWriter align: str | None - align_stack: List[str | None] - font_stack: List[_FontType] - margin_stack: List[int] + align_stack: list[str | None] + font_stack: list[_FontType] + margin_stack: list[int] spacing: str | None style_stack: Any nospace: int @@ -68,7 +68,7 @@ class NullWriter: def new_font(self, font: _FontType) -> None: ... def new_margin(self, margin: int, level: int) -> None: ... def new_spacing(self, spacing: str | None) -> None: ... - def new_styles(self, styles: Tuple[Any, ...]) -> None: ... + def new_styles(self, styles: tuple[Any, ...]) -> None: ... def send_paragraph(self, blankline: int) -> None: ... def send_line_break(self) -> None: ... def send_hor_rule(self, *args: Any, **kw: Any) -> None: ... @@ -81,7 +81,7 @@ class AbstractWriter(NullWriter): def new_font(self, font: _FontType) -> None: ... def new_margin(self, margin: int, level: int) -> None: ... def new_spacing(self, spacing: str | None) -> None: ... - def new_styles(self, styles: Tuple[Any, ...]) -> None: ... + def new_styles(self, styles: tuple[Any, ...]) -> None: ... def send_paragraph(self, blankline: int) -> None: ... def send_line_break(self) -> None: ... def send_hor_rule(self, *args: Any, **kw: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/fractions.pyi b/mypy/typeshed/stdlib/@python2/fractions.pyi index 872e20ede688..7835e9aa56b6 100644 --- a/mypy/typeshed/stdlib/@python2/fractions.pyi +++ b/mypy/typeshed/stdlib/@python2/fractions.pyi @@ -1,10 +1,10 @@ +from _typeshed import Self from decimal import Decimal from numbers import Integral, Rational, Real -from typing import Tuple, Type, TypeVar, Union, overload +from typing import Union, overload from typing_extensions import Literal _ComparableNum = Union[int, float, Decimal, Real] -_T = TypeVar("_T") @overload def gcd(a: int, b: int) -> int: ... @@ -18,10 +18,10 @@ def gcd(a: Integral, b: Integral) -> Integral: ... class Fraction(Rational): @overload def __new__( - cls: Type[_T], numerator: int | Rational = ..., denominator: int | Rational | None = ..., *, _normalize: bool = ... - ) -> _T: ... + cls: type[Self], numerator: int | Rational = ..., denominator: int | Rational | None = ..., *, _normalize: bool = ... + ) -> Self: ... @overload - def __new__(cls: Type[_T], __value: float | Decimal | str, *, _normalize: bool = ...) -> _T: ... + def __new__(cls: type[Self], __value: float | Decimal | str, *, _normalize: bool = ...) -> Self: ... @classmethod def from_float(cls, f: float) -> Fraction: ... @classmethod @@ -108,13 +108,13 @@ class Fraction(Rational): @overload def __rmod__(self, other: float) -> float: ... @overload - def __divmod__(self, other: int | Fraction) -> Tuple[int, Fraction]: ... + def __divmod__(self, other: int | Fraction) -> tuple[int, Fraction]: ... @overload - def __divmod__(self, other: float) -> Tuple[float, Fraction]: ... + def __divmod__(self, other: float) -> tuple[float, Fraction]: ... @overload - def __rdivmod__(self, other: int | Fraction) -> Tuple[int, Fraction]: ... + def __rdivmod__(self, other: int | Fraction) -> tuple[int, Fraction]: ... @overload - def __rdivmod__(self, other: float) -> Tuple[float, Fraction]: ... + def __rdivmod__(self, other: float) -> tuple[float, Fraction]: ... @overload def __pow__(self, other: int) -> Fraction: ... @overload diff --git a/mypy/typeshed/stdlib/@python2/ftplib.pyi b/mypy/typeshed/stdlib/@python2/ftplib.pyi index 0931a9d171cd..b8c2bbd40371 100644 --- a/mypy/typeshed/stdlib/@python2/ftplib.pyi +++ b/mypy/typeshed/stdlib/@python2/ftplib.pyi @@ -1,10 +1,9 @@ from _typeshed import SupportsRead, SupportsReadline from socket import socket from ssl import SSLContext -from typing import Any, BinaryIO, Callable, List, Text, Tuple, Type, TypeVar, Union +from typing import Any, BinaryIO, Callable, Text, Union from typing_extensions import Literal -_T = TypeVar("_T") _IntOrStr = Union[int, Text] MSG_OOB: int @@ -18,7 +17,7 @@ class error_temp(Error): ... class error_perm(Error): ... class error_proto(Error): ... -all_errors: Tuple[Type[Exception], ...] +all_errors: tuple[type[Exception], ...] class FTP: debugging: int @@ -58,10 +57,10 @@ class FTP: def sendport(self, host: Text, port: int) -> str: ... def sendeprt(self, host: Text, port: int) -> str: ... def makeport(self) -> socket: ... - def makepasv(self) -> Tuple[str, int]: ... + def makepasv(self) -> tuple[str, int]: ... def login(self, user: Text = ..., passwd: Text = ..., acct: Text = ...) -> str: ... # In practice, `rest` rest can actually be anything whose str() is an integer sequence, so to make it simple we allow integers. - def ntransfercmd(self, cmd: Text, rest: _IntOrStr | None = ...) -> Tuple[socket, int]: ... + def ntransfercmd(self, cmd: Text, rest: _IntOrStr | None = ...) -> tuple[socket, int]: ... def transfercmd(self, cmd: Text, rest: _IntOrStr | None = ...) -> socket: ... def retrbinary( self, cmd: Text, callback: Callable[[bytes], Any], blocksize: int = ..., rest: _IntOrStr | None = ... @@ -77,7 +76,7 @@ class FTP: def retrlines(self, cmd: Text, callback: Callable[[str], Any] | None = ...) -> str: ... def storlines(self, cmd: Text, fp: SupportsReadline[bytes], callback: Callable[[bytes], Any] | None = ...) -> str: ... def acct(self, password: Text) -> str: ... - def nlst(self, *args: Text) -> List[str]: ... + def nlst(self, *args: Text) -> list[str]: ... # Technically only the last arg can be a Callable but ... def dir(self, *args: str | Callable[[str], None]) -> None: ... def rename(self, fromname: Text, toname: Text) -> str: ... @@ -101,7 +100,7 @@ class FTP_TLS(FTP): certfile: str | None = ..., context: SSLContext | None = ..., timeout: float = ..., - source_address: Tuple[str, int] | None = ..., + source_address: tuple[str, int] | None = ..., ) -> None: ... ssl_version: int keyfile: str | None @@ -114,14 +113,14 @@ class FTP_TLS(FTP): class Netrc: def __init__(self, filename: Text | None = ...) -> None: ... - def get_hosts(self) -> List[str]: ... - def get_account(self, host: Text) -> Tuple[str | None, str | None, str | None]: ... - def get_macros(self) -> List[str]: ... - def get_macro(self, macro: Text) -> Tuple[str, ...]: ... + def get_hosts(self) -> list[str]: ... + def get_account(self, host: Text) -> tuple[str | None, str | None, str | None]: ... + def get_macros(self) -> list[str]: ... + def get_macro(self, macro: Text) -> tuple[str, ...]: ... def parse150(resp: str) -> int | None: ... # undocumented -def parse227(resp: str) -> Tuple[str, int]: ... # undocumented -def parse229(resp: str, peer: Any) -> Tuple[str, int]: ... # undocumented +def parse227(resp: str) -> tuple[str, int]: ... # undocumented +def parse229(resp: str, peer: Any) -> tuple[str, int]: ... # undocumented def parse257(resp: str) -> str: ... # undocumented def ftpcp( source: FTP, sourcename: str, target: FTP, targetname: str = ..., type: Literal["A", "I"] = ... diff --git a/mypy/typeshed/stdlib/@python2/functools.pyi b/mypy/typeshed/stdlib/@python2/functools.pyi index dd873708fea4..026a74faf6ff 100644 --- a/mypy/typeshed/stdlib/@python2/functools.pyi +++ b/mypy/typeshed/stdlib/@python2/functools.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Dict, Generic, Iterable, Sequence, Tuple, Type, TypeVar, overload +from typing import Any, Callable, Generic, Iterable, Sequence, TypeVar, overload _AnyCallable = Callable[..., Any] @@ -19,12 +19,12 @@ def update_wrapper( def wraps( wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ... ) -> Callable[[_AnyCallable], _AnyCallable]: ... -def total_ordering(cls: Type[_T]) -> Type[_T]: ... +def total_ordering(cls: type[_T]) -> type[_T]: ... def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], Any]: ... class partial(Generic[_T]): func = ... # Callable[..., _T] - args: Tuple[Any, ...] - keywords: Dict[str, Any] + args: tuple[Any, ...] + keywords: dict[str, Any] def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> _T: ... diff --git a/mypy/typeshed/stdlib/@python2/gc.pyi b/mypy/typeshed/stdlib/@python2/gc.pyi index b1fb1acc07d2..0ee05387a5a8 100644 --- a/mypy/typeshed/stdlib/@python2/gc.pyi +++ b/mypy/typeshed/stdlib/@python2/gc.pyi @@ -1,4 +1,4 @@ -from typing import Any, List, Tuple +from typing import Any def enable() -> None: ... def disable() -> None: ... @@ -6,15 +6,15 @@ def isenabled() -> bool: ... def collect(generation: int = ...) -> int: ... def set_debug(flags: int) -> None: ... def get_debug() -> int: ... -def get_objects() -> List[Any]: ... +def get_objects() -> list[Any]: ... def set_threshold(threshold0: int, threshold1: int = ..., threshold2: int = ...) -> None: ... -def get_count() -> Tuple[int, int, int]: ... -def get_threshold() -> Tuple[int, int, int]: ... -def get_referrers(*objs: Any) -> List[Any]: ... -def get_referents(*objs: Any) -> List[Any]: ... +def get_count() -> tuple[int, int, int]: ... +def get_threshold() -> tuple[int, int, int]: ... +def get_referrers(*objs: Any) -> list[Any]: ... +def get_referents(*objs: Any) -> list[Any]: ... def is_tracked(obj: Any) -> bool: ... -garbage: List[Any] +garbage: list[Any] DEBUG_STATS: int DEBUG_COLLECTABLE: int diff --git a/mypy/typeshed/stdlib/@python2/genericpath.pyi b/mypy/typeshed/stdlib/@python2/genericpath.pyi index ba29db4692bb..fecb3b70af42 100644 --- a/mypy/typeshed/stdlib/@python2/genericpath.pyi +++ b/mypy/typeshed/stdlib/@python2/genericpath.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsLessThanT -from typing import List, Sequence, Text, Tuple, Union, overload +from typing import Sequence, Text, Union, overload from typing_extensions import Literal # All overloads can return empty string. Ideally, Literal[""] would be a valid @@ -10,9 +10,9 @@ def commonprefix(m: Sequence[str]) -> str | Literal[""]: ... # type: ignore @overload def commonprefix(m: Sequence[Text]) -> Text: ... # type: ignore @overload -def commonprefix(m: Sequence[List[SupportsLessThanT]]) -> Sequence[SupportsLessThanT]: ... +def commonprefix(m: Sequence[list[SupportsLessThanT]]) -> Sequence[SupportsLessThanT]: ... @overload -def commonprefix(m: Sequence[Tuple[SupportsLessThanT, ...]]) -> Sequence[SupportsLessThanT]: ... +def commonprefix(m: Sequence[tuple[SupportsLessThanT, ...]]) -> Sequence[SupportsLessThanT]: ... def exists(path: Text) -> bool: ... def getsize(filename: Text) -> int: ... def isfile(path: Text) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/getopt.pyi b/mypy/typeshed/stdlib/@python2/getopt.pyi index 370d4d5c1cba..b1e90a6c5a67 100644 --- a/mypy/typeshed/stdlib/@python2/getopt.pyi +++ b/mypy/typeshed/stdlib/@python2/getopt.pyi @@ -1,12 +1,9 @@ -from typing import List, Tuple - class GetoptError(Exception): opt: str msg: str def __init__(self, msg: str, opt: str = ...) -> None: ... - def __str__(self) -> str: ... error = GetoptError -def getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... -def gnu_getopt(args: List[str], shortopts: str, longopts: List[str] = ...) -> Tuple[List[Tuple[str, str]], List[str]]: ... +def getopt(args: list[str], shortopts: str, longopts: list[str] = ...) -> tuple[list[tuple[str, str]], list[str]]: ... +def gnu_getopt(args: list[str], shortopts: str, longopts: list[str] = ...) -> tuple[list[tuple[str, str]], list[str]]: ... diff --git a/mypy/typeshed/stdlib/@python2/gettext.pyi b/mypy/typeshed/stdlib/@python2/gettext.pyi index a91234f6b2d3..02e306978160 100644 --- a/mypy/typeshed/stdlib/@python2/gettext.pyi +++ b/mypy/typeshed/stdlib/@python2/gettext.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Container, Dict, List, Sequence, Type +from typing import IO, Any, Container, Sequence def bindtextdomain(domain: str, localedir: str = ...) -> str: ... def bind_textdomain_codeset(domain: str, codeset: str = ...) -> str: ... @@ -22,7 +22,7 @@ class NullTranslations(object): def ngettext(self, singular: str, plural: str, n: int) -> str: ... def lngettext(self, singular: str, plural: str, n: int) -> str: ... def ungettext(self, singular: str | unicode, plural: str | unicode, n: int) -> unicode: ... - def info(self) -> Dict[str, str]: ... + def info(self) -> dict[str, str]: ... def charset(self) -> str | None: ... def output_charset(self) -> str | None: ... def set_output_charset(self, charset: str | None) -> None: ... @@ -34,12 +34,12 @@ class GNUTranslations(NullTranslations): def find( domain: str, localedir: str | None = ..., languages: Sequence[str] | None = ..., all: Any = ... -) -> str | List[str] | None: ... +) -> str | list[str] | None: ... def translation( domain: str, localedir: str | None = ..., languages: Sequence[str] | None = ..., - class_: Type[NullTranslations] | None = ..., + class_: type[NullTranslations] | None = ..., fallback: bool = ..., codeset: str | None = ..., ) -> NullTranslations: ... diff --git a/mypy/typeshed/stdlib/@python2/glob.pyi b/mypy/typeshed/stdlib/@python2/glob.pyi index f5a389a0ddfa..2fc01a03a48b 100644 --- a/mypy/typeshed/stdlib/@python2/glob.pyi +++ b/mypy/typeshed/stdlib/@python2/glob.pyi @@ -1,7 +1,7 @@ -from typing import AnyStr, Iterator, List +from typing import AnyStr, Iterator -def glob(pathname: AnyStr) -> List[AnyStr]: ... +def glob(pathname: AnyStr) -> list[AnyStr]: ... def iglob(pathname: AnyStr) -> Iterator[AnyStr]: ... -def glob1(dirname: str | unicode, pattern: AnyStr) -> List[AnyStr]: ... -def glob0(dirname: str | unicode, basename: AnyStr) -> List[AnyStr]: ... +def glob1(dirname: str | unicode, pattern: AnyStr) -> list[AnyStr]: ... +def glob0(dirname: str | unicode, basename: AnyStr) -> list[AnyStr]: ... def has_magic(s: str | unicode) -> bool: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/grp.pyi b/mypy/typeshed/stdlib/@python2/grp.pyi index 63898b26bf17..1651663eb242 100644 --- a/mypy/typeshed/stdlib/@python2/grp.pyi +++ b/mypy/typeshed/stdlib/@python2/grp.pyi @@ -1,11 +1,12 @@ -from typing import List, NamedTuple +import sys +from typing import NamedTuple -class struct_group(NamedTuple): - gr_name: str - gr_passwd: str | None - gr_gid: int - gr_mem: List[str] - -def getgrall() -> List[struct_group]: ... -def getgrgid(id: int) -> struct_group: ... -def getgrnam(name: str) -> struct_group: ... +if sys.platform != "win32": + class struct_group(NamedTuple): + gr_name: str + gr_passwd: str | None + gr_gid: int + gr_mem: list[str] + def getgrall() -> list[struct_group]: ... + def getgrgid(id: int) -> struct_group: ... + def getgrnam(name: str) -> struct_group: ... diff --git a/mypy/typeshed/stdlib/@python2/hashlib.pyi b/mypy/typeshed/stdlib/@python2/hashlib.pyi index 9c53d2b6b30d..8f881aaaf419 100644 --- a/mypy/typeshed/stdlib/@python2/hashlib.pyi +++ b/mypy/typeshed/stdlib/@python2/hashlib.pyi @@ -1,4 +1,4 @@ -from typing import Tuple, Union +from typing import Union _DataType = Union[str, unicode, bytearray, buffer, memoryview] @@ -25,8 +25,8 @@ def sha256(s: _DataType = ...) -> _hash: ... def sha384(s: _DataType = ...) -> _hash: ... def sha512(s: _DataType = ...) -> _hash: ... -algorithms: Tuple[str, ...] -algorithms_guaranteed: Tuple[str, ...] -algorithms_available: Tuple[str, ...] +algorithms: tuple[str, ...] +algorithms_guaranteed: tuple[str, ...] +algorithms_available: tuple[str, ...] def pbkdf2_hmac(name: str, password: str, salt: str, rounds: int, dklen: int = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/heapq.pyi b/mypy/typeshed/stdlib/@python2/heapq.pyi index 78ce6fd03928..5c393436d3c2 100644 --- a/mypy/typeshed/stdlib/@python2/heapq.pyi +++ b/mypy/typeshed/stdlib/@python2/heapq.pyi @@ -1,15 +1,15 @@ from _typeshed import SupportsLessThan -from typing import Callable, Iterable, List, TypeVar +from typing import Callable, Iterable, TypeVar _T = TypeVar("_T") def cmp_lt(x, y) -> bool: ... -def heappush(heap: List[_T], item: _T) -> None: ... -def heappop(heap: List[_T]) -> _T: ... -def heappushpop(heap: List[_T], item: _T) -> _T: ... -def heapify(x: List[_T]) -> None: ... -def heapreplace(heap: List[_T], item: _T) -> _T: ... +def heappush(heap: list[_T], item: _T) -> None: ... +def heappop(heap: list[_T]) -> _T: ... +def heappushpop(heap: list[_T], item: _T) -> _T: ... +def heapify(x: list[_T]) -> None: ... +def heapreplace(heap: list[_T], item: _T) -> _T: ... def merge(*iterables: Iterable[_T]) -> Iterable[_T]: ... -def nlargest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsLessThan] | None = ...) -> List[_T]: ... -def nsmallest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsLessThan] | None = ...) -> List[_T]: ... -def _heapify_max(__x: List[_T]) -> None: ... # undocumented +def nlargest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsLessThan] | None = ...) -> list[_T]: ... +def nsmallest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsLessThan] | None = ...) -> list[_T]: ... +def _heapify_max(__x: list[_T]) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/htmlentitydefs.pyi b/mypy/typeshed/stdlib/@python2/htmlentitydefs.pyi index 749b3039dfc3..3fcc4be2d5a0 100644 --- a/mypy/typeshed/stdlib/@python2/htmlentitydefs.pyi +++ b/mypy/typeshed/stdlib/@python2/htmlentitydefs.pyi @@ -1,5 +1,3 @@ -from typing import Dict - -name2codepoint: Dict[str, int] -codepoint2name: Dict[int, str] -entitydefs: Dict[str, str] +name2codepoint: dict[str, int] +codepoint2name: dict[int, str] +entitydefs: dict[str, str] diff --git a/mypy/typeshed/stdlib/@python2/httplib.pyi b/mypy/typeshed/stdlib/@python2/httplib.pyi index f2163818fae4..b72423fc8ea9 100644 --- a/mypy/typeshed/stdlib/@python2/httplib.pyi +++ b/mypy/typeshed/stdlib/@python2/httplib.pyi @@ -1,9 +1,9 @@ import mimetools -from typing import Any, Dict, Protocol +from typing import Any, Protocol class HTTPMessage(mimetools.Message): def addcontinue(self, key: str, more: str) -> None: ... - dict: Dict[str, str] + dict: dict[str, str] def addheader(self, key: str, value: str) -> None: ... unixfrom: str headers: Any @@ -151,7 +151,7 @@ class LineAndFileWrapper: # Constants -responses: Dict[int, str] +responses: dict[int, str] HTTP_PORT: int HTTPS_PORT: int diff --git a/mypy/typeshed/stdlib/@python2/imaplib.pyi b/mypy/typeshed/stdlib/@python2/imaplib.pyi index c4346851bdac..b7e455f45062 100644 --- a/mypy/typeshed/stdlib/@python2/imaplib.pyi +++ b/mypy/typeshed/stdlib/@python2/imaplib.pyi @@ -1,33 +1,34 @@ import subprocess import time +from builtins import list as List # alias to avoid name clashes with `IMAP4.list` from socket import socket as _socket from ssl import SSLSocket -from typing import IO, Any, Callable, Dict, List, Pattern, Text, Tuple, Type, Union +from typing import IO, Any, Callable, Pattern, Text, Union from typing_extensions import Literal # TODO: Commands should use their actual return types, not this type alias. -# E.g. Tuple[Literal["OK"], List[bytes]] -_CommandResults = Tuple[str, List[Any]] +# E.g. tuple[Literal["OK"], list[bytes]] +_CommandResults = tuple[str, list[Any]] -_AnyResponseData = Union[List[None], List[Union[bytes, Tuple[bytes, bytes]]]] +_AnyResponseData = Union[list[None], list[Union[bytes, tuple[bytes, bytes]]]] class IMAP4: - error: Type[Exception] = ... - abort: Type[Exception] = ... - readonly: Type[Exception] = ... + error: type[Exception] = ... + abort: type[Exception] = ... + readonly: type[Exception] = ... mustquote: Pattern[Text] = ... debug: int = ... state: str = ... literal: Text | None = ... - tagged_commands: Dict[bytes, List[bytes] | None] - untagged_responses: Dict[str, List[bytes | Tuple[bytes, bytes]]] + tagged_commands: dict[bytes, List[bytes] | None] + untagged_responses: dict[str, List[bytes | tuple[bytes, bytes]]] continuation_response: str = ... is_readonly: bool = ... tagnum: int = ... tagpre: str = ... tagre: Pattern[Text] = ... welcome: bytes = ... - capabilities: Tuple[str] = ... + capabilities: tuple[str] = ... PROTOCOL_VERSION: str = ... def __init__(self, host: str = ..., port: int = ...) -> None: ... def open(self, host: str = ..., port: int = ...) -> None: ... @@ -44,7 +45,7 @@ class IMAP4: def recent(self) -> _CommandResults: ... def response(self, code: str) -> _CommandResults: ... def append(self, mailbox: str, flags: str, date_time: str, message: str) -> str: ... - def authenticate(self, mechanism: str, authobject: Callable[[bytes], bytes | None]) -> Tuple[str, str]: ... + def authenticate(self, mechanism: str, authobject: Callable[[bytes], bytes | None]) -> tuple[str, str]: ... def capability(self) -> _CommandResults: ... def check(self) -> _CommandResults: ... def close(self) -> _CommandResults: ... @@ -53,24 +54,24 @@ class IMAP4: def delete(self, mailbox: str) -> _CommandResults: ... def deleteacl(self, mailbox: str, who: str) -> _CommandResults: ... def expunge(self) -> _CommandResults: ... - def fetch(self, message_set: str, message_parts: str) -> Tuple[str, _AnyResponseData]: ... + def fetch(self, message_set: str, message_parts: str) -> tuple[str, _AnyResponseData]: ... def getacl(self, mailbox: str) -> _CommandResults: ... def getannotation(self, mailbox: str, entry: str, attribute: str) -> _CommandResults: ... def getquota(self, root: str) -> _CommandResults: ... def getquotaroot(self, mailbox: str) -> _CommandResults: ... - def list(self, directory: str = ..., pattern: str = ...) -> Tuple[str, _AnyResponseData]: ... - def login(self, user: str, password: str) -> Tuple[Literal["OK"], List[bytes]]: ... + def list(self, directory: str = ..., pattern: str = ...) -> tuple[str, _AnyResponseData]: ... + def login(self, user: str, password: str) -> tuple[Literal["OK"], List[bytes]]: ... def login_cram_md5(self, user: str, password: str) -> _CommandResults: ... - def logout(self) -> Tuple[str, _AnyResponseData]: ... + def logout(self) -> tuple[str, _AnyResponseData]: ... def lsub(self, directory: str = ..., pattern: str = ...) -> _CommandResults: ... def myrights(self, mailbox: str) -> _CommandResults: ... def namespace(self) -> _CommandResults: ... - def noop(self) -> Tuple[str, List[bytes]]: ... + def noop(self) -> tuple[str, List[bytes]]: ... def partial(self, message_num: str, message_part: str, start: str, length: str) -> _CommandResults: ... def proxyauth(self, user: str) -> _CommandResults: ... def rename(self, oldmailbox: str, newmailbox: str) -> _CommandResults: ... def search(self, charset: str | None, *criteria: str) -> _CommandResults: ... - def select(self, mailbox: str = ..., readonly: bool = ...) -> Tuple[str, List[bytes | None]]: ... + def select(self, mailbox: str = ..., readonly: bool = ...) -> tuple[str, List[bytes | None]]: ... def setacl(self, mailbox: str, who: str, what: str) -> _CommandResults: ... def setannotation(self, *args: str) -> _CommandResults: ... def setquota(self, root: str, limits: str) -> _CommandResults: ... @@ -126,5 +127,5 @@ class _Authenticator: def Internaldate2tuple(resp: str) -> time.struct_time: ... def Int2AP(num: int) -> str: ... -def ParseFlags(resp: str) -> Tuple[str]: ... +def ParseFlags(resp: str) -> tuple[str]: ... def Time2Internaldate(date_time: float | time.struct_time | str) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/imghdr.pyi b/mypy/typeshed/stdlib/@python2/imghdr.pyi index d60cafa4c78f..dcfc3506fb9a 100644 --- a/mypy/typeshed/stdlib/@python2/imghdr.pyi +++ b/mypy/typeshed/stdlib/@python2/imghdr.pyi @@ -1,4 +1,4 @@ -from typing import Any, BinaryIO, Callable, List, Protocol, Text, Union, overload +from typing import Any, BinaryIO, Callable, Protocol, Text, Union, overload class _ReadableBinary(Protocol): def tell(self) -> int: ... @@ -12,4 +12,4 @@ def what(file: _File, h: None = ...) -> str | None: ... @overload def what(file: Any, h: bytes) -> str | None: ... -tests: List[Callable[[bytes, BinaryIO | None], str | None]] +tests: list[Callable[[bytes, BinaryIO | None], str | None]] diff --git a/mypy/typeshed/stdlib/@python2/imp.pyi b/mypy/typeshed/stdlib/@python2/imp.pyi index 128bd900e996..15d689249563 100644 --- a/mypy/typeshed/stdlib/@python2/imp.pyi +++ b/mypy/typeshed/stdlib/@python2/imp.pyi @@ -1,5 +1,5 @@ import types -from typing import IO, Any, Iterable, List, Tuple +from typing import IO, Any, Iterable C_BUILTIN: int C_EXTENSION: int @@ -13,16 +13,16 @@ PY_SOURCE: int SEARCH_ERROR: int def acquire_lock() -> None: ... -def find_module(name: str, path: Iterable[str] = ...) -> Tuple[IO[Any], str, Tuple[str, str, int]] | None: ... +def find_module(name: str, path: Iterable[str] = ...) -> tuple[IO[Any], str, tuple[str, str, int]] | None: ... def get_magic() -> str: ... -def get_suffixes() -> List[Tuple[str, str, int]]: ... +def get_suffixes() -> list[tuple[str, str, int]]: ... def init_builtin(name: str) -> types.ModuleType: ... def init_frozen(name: str) -> types.ModuleType: ... def is_builtin(name: str) -> int: ... def is_frozen(name: str) -> bool: ... def load_compiled(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... def load_dynamic(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... -def load_module(name: str, file: str, pathname: str, description: Tuple[str, str, int]) -> types.ModuleType: ... +def load_module(name: str, file: str, pathname: str, description: tuple[str, str, int]) -> types.ModuleType: ... def load_source(name: str, pathname: str, file: IO[Any] = ...) -> types.ModuleType: ... def lock_held() -> bool: ... def new_module(name: str) -> types.ModuleType: ... diff --git a/mypy/typeshed/stdlib/@python2/inspect.pyi b/mypy/typeshed/stdlib/@python2/inspect.pyi index c6118ea8aebb..aa0450ce6785 100644 --- a/mypy/typeshed/stdlib/@python2/inspect.pyi +++ b/mypy/typeshed/stdlib/@python2/inspect.pyi @@ -1,5 +1,5 @@ from types import CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType -from typing import Any, AnyStr, Callable, Dict, List, NamedTuple, Optional, Sequence, Tuple, Type, Union +from typing import Any, AnyStr, Callable, NamedTuple, Optional, Sequence, Union # Types and members class EndOfBlock(Exception): ... @@ -11,7 +11,7 @@ class BlockFinder: passline: bool last: int def tokeneater( - self, type: int, token: AnyStr, srow_scol: Tuple[int, int], erow_ecol: Tuple[int, int], line: AnyStr + self, type: int, token: AnyStr, srow_scol: tuple[int, int], erow_ecol: tuple[int, int], line: AnyStr ) -> None: ... CO_GENERATOR: int @@ -29,7 +29,7 @@ class ModuleInfo(NamedTuple): mode: str module_type: int -def getmembers(object: object, predicate: Callable[[Any], bool] | None = ...) -> List[Tuple[str, Any]]: ... +def getmembers(object: object, predicate: Callable[[Any], bool] | None = ...) -> list[tuple[str, Any]]: ... def getmoduleinfo(path: str | unicode) -> ModuleInfo | None: ... def getmodulename(path: AnyStr) -> AnyStr | None: ... def ismodule(object: object) -> bool: ... @@ -50,9 +50,9 @@ def isgetsetdescriptor(object: object) -> bool: ... def ismemberdescriptor(object: object) -> bool: ... # Retrieving source code -_SourceObjectType = Union[ModuleType, Type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] +_SourceObjectType = Union[ModuleType, type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] -def findsource(object: _SourceObjectType) -> Tuple[List[str], int]: ... +def findsource(object: _SourceObjectType) -> tuple[list[str], int]: ... def getabsfile(object: _SourceObjectType) -> str: ... def getblock(lines: Sequence[AnyStr]) -> Sequence[AnyStr]: ... def getdoc(object: object) -> str | None: ... @@ -60,28 +60,28 @@ def getcomments(object: object) -> str | None: ... def getfile(object: _SourceObjectType) -> str: ... def getmodule(object: object) -> ModuleType | None: ... def getsourcefile(object: _SourceObjectType) -> str | None: ... -def getsourcelines(object: _SourceObjectType) -> Tuple[List[str], int]: ... +def getsourcelines(object: _SourceObjectType) -> tuple[list[str], int]: ... def getsource(object: _SourceObjectType) -> str: ... def cleandoc(doc: AnyStr) -> AnyStr: ... def indentsize(line: str | unicode) -> int: ... # Classes and functions -def getclasstree(classes: List[type], unique: bool = ...) -> List[Tuple[type, Tuple[type, ...]] | List[Any]]: ... +def getclasstree(classes: list[type], unique: bool = ...) -> list[tuple[type, tuple[type, ...]] | list[Any]]: ... class ArgSpec(NamedTuple): - args: List[str] + args: list[str] varargs: str | None keywords: str | None - defaults: Tuple[Any, ...] + defaults: tuple[Any, ...] class ArgInfo(NamedTuple): - args: List[str] + args: list[str] varargs: str | None keywords: str | None - locals: Dict[str, Any] + locals: dict[str, Any] class Arguments(NamedTuple): - args: List[str | List[Any]] + args: list[str | list[Any]] varargs: str | None keywords: str | None @@ -94,8 +94,8 @@ def formatargspec( def formatargvalues( args, varargs=..., varkw=..., defaults=..., formatarg=..., formatvarargs=..., formatvarkw=..., formatvalue=..., join=... ) -> str: ... -def getmro(cls: type) -> Tuple[type, ...]: ... -def getcallargs(func, *args, **kwds) -> Dict[str, Any]: ... +def getmro(cls: type) -> tuple[type, ...]: ... +def getcallargs(func, *args, **kwds) -> dict[str, Any]: ... # The interpreter stack @@ -103,18 +103,18 @@ class Traceback(NamedTuple): filename: str lineno: int function: str - code_context: List[str] | None + code_context: list[str] | None index: int | None # type: ignore -_FrameInfo = Tuple[FrameType, str, int, str, Optional[List[str]], Optional[int]] +_FrameInfo = tuple[FrameType, str, int, str, Optional[list[str]], Optional[int]] -def getouterframes(frame: FrameType, context: int = ...) -> List[_FrameInfo]: ... +def getouterframes(frame: FrameType, context: int = ...) -> list[_FrameInfo]: ... def getframeinfo(frame: FrameType | TracebackType, context: int = ...) -> Traceback: ... -def getinnerframes(traceback: TracebackType, context: int = ...) -> List[_FrameInfo]: ... +def getinnerframes(traceback: TracebackType, context: int = ...) -> list[_FrameInfo]: ... def getlineno(frame: FrameType) -> int: ... def currentframe(depth: int = ...) -> FrameType: ... -def stack(context: int = ...) -> List[_FrameInfo]: ... -def trace(context: int = ...) -> List[_FrameInfo]: ... +def stack(context: int = ...) -> list[_FrameInfo]: ... +def trace(context: int = ...) -> list[_FrameInfo]: ... # Create private type alias to avoid conflict with symbol of same # name created in Attribute class. @@ -126,4 +126,4 @@ class Attribute(NamedTuple): defining_class: type object: _Object -def classify_class_attrs(cls: type) -> List[Attribute]: ... +def classify_class_attrs(cls: type) -> list[Attribute]: ... diff --git a/mypy/typeshed/stdlib/@python2/itertools.pyi b/mypy/typeshed/stdlib/@python2/itertools.pyi index 12996d44628b..c16ca8debb03 100644 --- a/mypy/typeshed/stdlib/@python2/itertools.pyi +++ b/mypy/typeshed/stdlib/@python2/itertools.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Generic, Iterable, Iterator, Sequence, Tuple, TypeVar, overload +from typing import Any, Callable, Generic, Iterable, Iterator, Sequence, TypeVar, overload _T = TypeVar("_T") _S = TypeVar("_S") @@ -24,9 +24,9 @@ def dropwhile(predicate: Callable[[_T], Any], iterable: Iterable[_T]) -> Iterato def ifilter(predicate: Callable[[_T], Any] | None, iterable: Iterable[_T]) -> Iterator[_T]: ... def ifilterfalse(predicate: Callable[[_T], Any] | None, iterable: Iterable[_T]) -> Iterator[_T]: ... @overload -def groupby(iterable: Iterable[_T], key: None = ...) -> Iterator[Tuple[_T, Iterator[_T]]]: ... +def groupby(iterable: Iterable[_T], key: None = ...) -> Iterator[tuple[_T, Iterator[_T]]]: ... @overload -def groupby(iterable: Iterable[_T], key: Callable[[_T], _S]) -> Iterator[Tuple[_S, Iterator[_T]]]: ... +def groupby(iterable: Iterable[_T], key: Callable[[_T], _S]) -> Iterator[tuple[_S, Iterator[_T]]]: ... @overload def islice(iterable: Iterable[_T], stop: int | None) -> Iterator[_T]: ... @overload @@ -88,21 +88,21 @@ def imap( ) -> Iterator[_S]: ... def starmap(func: Any, iterable: Iterable[Any]) -> Iterator[Any]: ... def takewhile(predicate: Callable[[_T], Any], iterable: Iterable[_T]) -> Iterator[_T]: ... -def tee(iterable: Iterable[_T], n: int = ...) -> Tuple[Iterator[_T], ...]: ... +def tee(iterable: Iterable[_T], n: int = ...) -> tuple[Iterator[_T], ...]: ... @overload -def izip(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +def izip(iter1: Iterable[_T1]) -> Iterator[tuple[_T1]]: ... @overload -def izip(iter1: Iterable[_T1], iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +def izip(iter1: Iterable[_T1], iter2: Iterable[_T2]) -> Iterator[tuple[_T1, _T2]]: ... @overload -def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... +def izip(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3]) -> Iterator[tuple[_T1, _T2, _T3]]: ... @overload def izip( iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4] -) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... +) -> Iterator[tuple[_T1, _T2, _T3, _T4]]: ... @overload def izip( iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5] -) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +) -> Iterator[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def izip( iter1: Iterable[_T1], @@ -111,7 +111,7 @@ def izip( iter4: Iterable[_T4], iter5: Iterable[_T5], iter6: Iterable[_T6], -) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... +) -> Iterator[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... @overload def izip( iter1: Iterable[Any], @@ -122,22 +122,22 @@ def izip( iter6: Iterable[Any], iter7: Iterable[Any], *iterables: Iterable[Any], -) -> Iterator[Tuple[Any, ...]]: ... +) -> Iterator[tuple[Any, ...]]: ... def izip_longest(*p: Iterable[Any], fillvalue: Any = ...) -> Iterator[Any]: ... @overload -def product(iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... +def product(iter1: Iterable[_T1]) -> Iterator[tuple[_T1]]: ... @overload -def product(iter1: Iterable[_T1], iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... +def product(iter1: Iterable[_T1], iter2: Iterable[_T2]) -> Iterator[tuple[_T1, _T2]]: ... @overload -def product(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... +def product(iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3]) -> Iterator[tuple[_T1, _T2, _T3]]: ... @overload def product( iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4] -) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... +) -> Iterator[tuple[_T1, _T2, _T3, _T4]]: ... @overload def product( iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5] -) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... +) -> Iterator[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def product( iter1: Iterable[_T1], @@ -146,7 +146,7 @@ def product( iter4: Iterable[_T4], iter5: Iterable[_T5], iter6: Iterable[_T6], -) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... +) -> Iterator[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... @overload def product( iter1: Iterable[Any], @@ -157,9 +157,9 @@ def product( iter6: Iterable[Any], iter7: Iterable[Any], *iterables: Iterable[Any], -) -> Iterator[Tuple[Any, ...]]: ... +) -> Iterator[tuple[Any, ...]]: ... @overload -def product(*iterables: Iterable[Any], repeat: int) -> Iterator[Tuple[Any, ...]]: ... +def product(*iterables: Iterable[Any], repeat: int) -> Iterator[tuple[Any, ...]]: ... def permutations(iterable: Iterable[_T], r: int = ...) -> Iterator[Sequence[_T]]: ... def combinations(iterable: Iterable[_T], r: int) -> Iterator[Sequence[_T]]: ... def combinations_with_replacement(iterable: Iterable[_T], r: int) -> Iterator[Sequence[_T]]: ... diff --git a/mypy/typeshed/stdlib/@python2/json.pyi b/mypy/typeshed/stdlib/@python2/json.pyi index bfbddb2a6835..fa6fdc49b9a9 100644 --- a/mypy/typeshed/stdlib/@python2/json.pyi +++ b/mypy/typeshed/stdlib/@python2/json.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsRead -from typing import IO, Any, Callable, Dict, List, Text, Tuple, Type +from typing import IO, Any, Callable, Text def dumps( obj: Any, @@ -7,9 +7,9 @@ def dumps( ensure_ascii: bool = ..., check_circular: bool = ..., allow_nan: bool = ..., - cls: Type[JSONEncoder] | None = ..., + cls: type[JSONEncoder] | None = ..., indent: int | None = ..., - separators: Tuple[str, str] | None = ..., + separators: tuple[str, str] | None = ..., encoding: str = ..., default: Callable[[Any], Any] | None = ..., sort_keys: bool = ..., @@ -22,9 +22,9 @@ def dump( ensure_ascii: bool = ..., check_circular: bool = ..., allow_nan: bool = ..., - cls: Type[JSONEncoder] | None = ..., + cls: type[JSONEncoder] | None = ..., indent: int | None = ..., - separators: Tuple[str, str] | None = ..., + separators: tuple[str, str] | None = ..., encoding: str = ..., default: Callable[[Any], Any] | None = ..., sort_keys: bool = ..., @@ -33,23 +33,23 @@ def dump( def loads( s: Text | bytes, encoding: Any = ..., - cls: Type[JSONDecoder] | None = ..., - object_hook: Callable[[Dict[Any, Any]], Any] | None = ..., + cls: type[JSONDecoder] | None = ..., + object_hook: Callable[[dict[Any, Any]], Any] | None = ..., parse_float: Callable[[str], Any] | None = ..., parse_int: Callable[[str], Any] | None = ..., parse_constant: Callable[[str], Any] | None = ..., - object_pairs_hook: Callable[[List[Tuple[Any, Any]]], Any] | None = ..., + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = ..., **kwds: Any, ) -> Any: ... def load( fp: SupportsRead[Text | bytes], encoding: str | None = ..., - cls: Type[JSONDecoder] | None = ..., - object_hook: Callable[[Dict[Any, Any]], Any] | None = ..., + cls: type[JSONDecoder] | None = ..., + object_hook: Callable[[dict[Any, Any]], Any] | None = ..., parse_float: Callable[[str], Any] | None = ..., parse_int: Callable[[str], Any] | None = ..., parse_constant: Callable[[str], Any] | None = ..., - object_pairs_hook: Callable[[List[Tuple[Any, Any]]], Any] | None = ..., + object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = ..., **kwds: Any, ) -> Any: ... @@ -65,7 +65,7 @@ class JSONDecoder(object): object_pairs_hook: Callable[..., Any] = ..., ) -> None: ... def decode(self, s: Text | bytes, _w: Any = ...) -> Any: ... - def raw_decode(self, s: Text | bytes, idx: int = ...) -> Tuple[Any, Any]: ... + def raw_decode(self, s: Text | bytes, idx: int = ...) -> tuple[Any, Any]: ... class JSONEncoder(object): item_separator: str @@ -84,7 +84,7 @@ class JSONEncoder(object): allow_nan: bool = ..., sort_keys: bool = ..., indent: int | None = ..., - separators: Tuple[Text | bytes, Text | bytes] = ..., + separators: tuple[Text | bytes, Text | bytes] = ..., encoding: Text | bytes = ..., default: Callable[..., Any] = ..., ) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi index 6ec97ce849d2..32eed63d42f9 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/grammar.pyi @@ -1,26 +1,25 @@ -from _typeshed import StrPath -from typing import Dict, List, Optional, Text, Tuple, TypeVar +from _typeshed import Self, StrPath +from typing import Optional, Text -_P = TypeVar("_P") -_Label = Tuple[int, Optional[Text]] -_DFA = List[List[Tuple[int, int]]] -_DFAS = Tuple[_DFA, Dict[int, int]] +_Label = tuple[int, Optional[Text]] +_DFA = list[list[tuple[int, int]]] +_DFAS = tuple[_DFA, dict[int, int]] class Grammar: - symbol2number: Dict[Text, int] - number2symbol: Dict[int, Text] - states: List[_DFA] - dfas: Dict[int, _DFAS] - labels: List[_Label] - keywords: Dict[Text, int] - tokens: Dict[int, int] - symbol2label: Dict[Text, int] + symbol2number: dict[Text, int] + number2symbol: dict[int, Text] + states: list[_DFA] + dfas: dict[int, _DFAS] + labels: list[_Label] + keywords: dict[Text, int] + tokens: dict[int, int] + symbol2label: dict[Text, int] start: int def __init__(self) -> None: ... def dump(self, filename: StrPath) -> None: ... def load(self, filename: StrPath) -> None: ... - def copy(self: _P) -> _P: ... + def copy(self: Self) -> Self: ... def report(self) -> None: ... opmap_raw: Text -opmap: Dict[Text, Text] +opmap: dict[Text, Text] diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/literals.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/literals.pyi index 160d6fd76f76..c7a219b5f9af 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/literals.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/literals.pyi @@ -1,6 +1,6 @@ -from typing import Dict, Match, Text +from typing import Match, Text -simple_escapes: Dict[Text, Text] +simple_escapes: dict[Text, Text] def escape(m: Match[str]) -> Text: ... def evalString(s: Text) -> Text: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/parse.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/parse.pyi index eed165db551c..be66a8e21e7e 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/parse.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/parse.pyi @@ -1,6 +1,6 @@ from lib2to3.pgen2.grammar import _DFAS, Grammar from lib2to3.pytree import _NL, _Convert, _RawNode -from typing import Any, List, Sequence, Set, Text, Tuple +from typing import Any, Sequence, Text _Context = Sequence[Any] @@ -14,9 +14,9 @@ class ParseError(Exception): class Parser: grammar: Grammar convert: _Convert - stack: List[Tuple[_DFAS, int, _RawNode]] + stack: list[tuple[_DFAS, int, _RawNode]] rootnode: _NL | None - used_names: Set[Text] + used_names: set[Text] def __init__(self, grammar: Grammar, convert: _Convert | None = ...) -> None: ... def setup(self, start: int | None = ...) -> None: ... def addtoken(self, type: int, value: Text | None, context: _Context) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/pgen.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/pgen.pyi index 67dbbccdd4a6..5b2dc70ed826 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/pgen.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/pgen.pyi @@ -1,7 +1,7 @@ from _typeshed import StrPath from lib2to3.pgen2 import grammar from lib2to3.pgen2.tokenize import _TokenInfo -from typing import IO, Any, Dict, Iterable, Iterator, List, NoReturn, Text, Tuple +from typing import IO, Any, Iterable, Iterator, NoReturn, Text class PgenGrammar(grammar.Grammar): ... @@ -9,36 +9,36 @@ class ParserGenerator: filename: StrPath stream: IO[Text] generator: Iterator[_TokenInfo] - first: Dict[Text, Dict[Text, int]] + first: dict[Text, dict[Text, int]] def __init__(self, filename: StrPath, stream: IO[Text] | None = ...) -> None: ... def make_grammar(self) -> PgenGrammar: ... - def make_first(self, c: PgenGrammar, name: Text) -> Dict[int, int]: ... + def make_first(self, c: PgenGrammar, name: Text) -> dict[int, int]: ... def make_label(self, c: PgenGrammar, label: Text) -> int: ... def addfirstsets(self) -> None: ... def calcfirst(self, name: Text) -> None: ... - def parse(self) -> Tuple[Dict[Text, List[DFAState]], Text]: ... - def make_dfa(self, start: NFAState, finish: NFAState) -> List[DFAState]: ... - def dump_nfa(self, name: Text, start: NFAState, finish: NFAState) -> List[DFAState]: ... + def parse(self) -> tuple[dict[Text, list[DFAState]], Text]: ... + def make_dfa(self, start: NFAState, finish: NFAState) -> list[DFAState]: ... + def dump_nfa(self, name: Text, start: NFAState, finish: NFAState) -> list[DFAState]: ... def dump_dfa(self, name: Text, dfa: Iterable[DFAState]) -> None: ... - def simplify_dfa(self, dfa: List[DFAState]) -> None: ... - def parse_rhs(self) -> Tuple[NFAState, NFAState]: ... - def parse_alt(self) -> Tuple[NFAState, NFAState]: ... - def parse_item(self) -> Tuple[NFAState, NFAState]: ... - def parse_atom(self) -> Tuple[NFAState, NFAState]: ... + def simplify_dfa(self, dfa: list[DFAState]) -> None: ... + def parse_rhs(self) -> tuple[NFAState, NFAState]: ... + def parse_alt(self) -> tuple[NFAState, NFAState]: ... + def parse_item(self) -> tuple[NFAState, NFAState]: ... + def parse_atom(self) -> tuple[NFAState, NFAState]: ... def expect(self, type: int, value: Any | None = ...) -> Text: ... def gettoken(self) -> None: ... def raise_error(self, msg: str, *args: Any) -> NoReturn: ... class NFAState: - arcs: List[Tuple[Text | None, NFAState]] + arcs: list[tuple[Text | None, NFAState]] def __init__(self) -> None: ... def addarc(self, next: NFAState, label: Text | None = ...) -> None: ... class DFAState: - nfaset: Dict[NFAState, Any] + nfaset: dict[NFAState, Any] isfinal: bool - arcs: Dict[Text, DFAState] - def __init__(self, nfaset: Dict[NFAState, Any], final: NFAState) -> None: ... + arcs: dict[Text, DFAState] + def __init__(self, nfaset: dict[NFAState, Any], final: NFAState) -> None: ... def addarc(self, next: DFAState, label: Text) -> None: ... def unifystate(self, old: DFAState, new: DFAState) -> None: ... def __eq__(self, other: Any) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/token.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/token.pyi index 3f4e41d49bd5..967c4df5d721 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/token.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/token.pyi @@ -1,4 +1,4 @@ -from typing import Dict, Text +from typing import Text ENDMARKER: int NAME: int @@ -56,7 +56,7 @@ NL: int ERRORTOKEN: int N_TOKENS: int NT_OFFSET: int -tok_name: Dict[int, Text] +tok_name: dict[int, Text] def ISTERMINAL(x: int) -> bool: ... def ISNONTERMINAL(x: int) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/tokenize.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/tokenize.pyi index 477341c1a54e..d93d3f482766 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/tokenize.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pgen2/tokenize.pyi @@ -1,9 +1,9 @@ from lib2to3.pgen2.token import * # noqa -from typing import Callable, Iterable, Iterator, List, Text, Tuple +from typing import Callable, Iterable, Iterator, Text -_Coord = Tuple[int, int] +_Coord = tuple[int, int] _TokenEater = Callable[[int, Text, _Coord, _Coord, Text], None] -_TokenInfo = Tuple[int, Text, _Coord, _Coord, Text] +_TokenInfo = tuple[int, Text, _Coord, _Coord, Text] class TokenError(Exception): ... class StopTokenizing(Exception): ... @@ -11,13 +11,13 @@ class StopTokenizing(Exception): ... def tokenize(readline: Callable[[], Text], tokeneater: _TokenEater = ...) -> None: ... class Untokenizer: - tokens: List[Text] + tokens: list[Text] prev_row: int prev_col: int def __init__(self) -> None: ... def add_whitespace(self, start: _Coord) -> None: ... def untokenize(self, iterable: Iterable[_TokenInfo]) -> Text: ... - def compat(self, token: Tuple[int, Text], iterable: Iterable[_TokenInfo]) -> None: ... + def compat(self, token: tuple[int, Text], iterable: Iterable[_TokenInfo]) -> None: ... def untokenize(iterable: Iterable[_TokenInfo]) -> Text: ... def generate_tokens(readline: Callable[[], Text]) -> Iterator[_TokenInfo]: ... diff --git a/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi b/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi index 27c64853329e..d96df2a9dc9e 100644 --- a/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi +++ b/mypy/typeshed/stdlib/@python2/lib2to3/pytree.pyi @@ -1,11 +1,12 @@ +from _typeshed import Self from lib2to3.pgen2.grammar import Grammar -from typing import Any, Callable, Dict, Iterator, List, Optional, Text, Tuple, TypeVar, Union +from typing import Any, Callable, Iterator, Optional, Text, TypeVar, Union _P = TypeVar("_P") _NL = Union[Node, Leaf] -_Context = Tuple[Text, int, int] -_Results = Dict[Text, _NL] -_RawNode = Tuple[int, Text, _Context, Optional[List[_NL]]] +_Context = tuple[Text, int, int] +_Results = dict[Text, _NL] +_RawNode = tuple[int, Text, _Context, Optional[list[_NL]]] _Convert = Callable[[Grammar, _RawNode], Any] HUGE: int @@ -16,15 +17,15 @@ class Base: type: int parent: Node | None prefix: Text - children: List[_NL] + children: list[_NL] was_changed: bool was_checked: bool def __eq__(self, other: Any) -> bool: ... def _eq(self: _P, other: _P) -> bool: ... - def clone(self: _P) -> _P: ... + def clone(self: Self) -> Self: ... def post_order(self) -> Iterator[_NL]: ... def pre_order(self) -> Iterator[_NL]: ... - def replace(self, new: _NL | List[_NL]) -> None: ... + def replace(self, new: _NL | list[_NL]) -> None: ... def get_lineno(self) -> int: ... def changed(self) -> None: ... def remove(self) -> int | None: ... @@ -39,14 +40,14 @@ class Base: def set_prefix(self, prefix: Text) -> None: ... class Node(Base): - fixers_applied: List[Any] + fixers_applied: list[Any] def __init__( self, type: int, - children: List[_NL], + children: list[_NL], context: Any | None = ..., prefix: Text | None = ..., - fixers_applied: List[Any] | None = ..., + fixers_applied: list[Any] | None = ..., ) -> None: ... def set_child(self, i: int, child: _NL) -> None: ... def insert_child(self, i: int, child: _NL) -> None: ... @@ -56,9 +57,9 @@ class Leaf(Base): lineno: int column: int value: Text - fixers_applied: List[Any] + fixers_applied: list[Any] def __init__( - self, type: int, value: Text, context: _Context | None = ..., prefix: Text | None = ..., fixers_applied: List[Any] = ... + self, type: int, value: Text, context: _Context | None = ..., prefix: Text | None = ..., fixers_applied: list[Any] = ... ) -> None: ... def convert(gr: Grammar, raw_node: _RawNode) -> _NL: ... @@ -69,8 +70,8 @@ class BasePattern: name: Text | None def optimize(self) -> BasePattern: ... # sic, subclasses are free to optimize themselves into different patterns def match(self, node: _NL, results: _Results | None = ...) -> bool: ... - def match_seq(self, nodes: List[_NL], results: _Results | None = ...) -> bool: ... - def generate_matches(self, nodes: List[_NL]) -> Iterator[Tuple[int, _Results]]: ... + def match_seq(self, nodes: list[_NL], results: _Results | None = ...) -> bool: ... + def generate_matches(self, nodes: list[_NL]) -> Iterator[tuple[int, _Results]]: ... class LeafPattern(BasePattern): def __init__(self, type: int | None = ..., content: Text | None = ..., name: Text | None = ...) -> None: ... @@ -87,4 +88,4 @@ class WildcardPattern(BasePattern): class NegatedPattern(BasePattern): def __init__(self, content: Text | None = ...) -> None: ... -def generate_matches(patterns: List[BasePattern], nodes: List[_NL]) -> Iterator[Tuple[int, _Results]]: ... +def generate_matches(patterns: list[BasePattern], nodes: list[_NL]) -> Iterator[tuple[int, _Results]]: ... diff --git a/mypy/typeshed/stdlib/@python2/linecache.pyi b/mypy/typeshed/stdlib/@python2/linecache.pyi index 8628a0c58adc..68c907499867 100644 --- a/mypy/typeshed/stdlib/@python2/linecache.pyi +++ b/mypy/typeshed/stdlib/@python2/linecache.pyi @@ -1,9 +1,9 @@ -from typing import Any, Dict, List, Text +from typing import Any, Text -_ModuleGlobals = Dict[str, Any] +_ModuleGlobals = dict[str, Any] def getline(filename: Text, lineno: int, module_globals: _ModuleGlobals | None = ...) -> str: ... def clearcache() -> None: ... -def getlines(filename: Text, module_globals: _ModuleGlobals | None = ...) -> List[str]: ... +def getlines(filename: Text, module_globals: _ModuleGlobals | None = ...) -> list[str]: ... def checkcache(filename: Text | None = ...) -> None: ... -def updatecache(filename: Text, module_globals: _ModuleGlobals | None = ...) -> List[str]: ... +def updatecache(filename: Text, module_globals: _ModuleGlobals | None = ...) -> list[str]: ... diff --git a/mypy/typeshed/stdlib/@python2/locale.pyi b/mypy/typeshed/stdlib/@python2/locale.pyi index 21a7da166e29..c75d865b8746 100644 --- a/mypy/typeshed/stdlib/@python2/locale.pyi +++ b/mypy/typeshed/stdlib/@python2/locale.pyi @@ -1,7 +1,7 @@ # workaround for mypy#2010 from __builtin__ import str as _str from decimal import Decimal -from typing import Any, Callable, Dict, Iterable, List, Mapping, Sequence, Tuple +from typing import Any, Callable, Iterable, Mapping, Sequence CODESET: int D_T_FMT: int @@ -75,9 +75,9 @@ CHAR_MAX: int class Error(Exception): ... def setlocale(category: int, locale: _str | Iterable[_str] | None = ...) -> _str: ... -def localeconv() -> Mapping[_str, int | _str | List[int]]: ... +def localeconv() -> Mapping[_str, int | _str | list[int]]: ... def nl_langinfo(__key: int) -> _str: ... -def getdefaultlocale(envvars: Tuple[_str, ...] = ...) -> Tuple[_str | None, _str | None]: ... +def getdefaultlocale(envvars: tuple[_str, ...] = ...) -> tuple[_str | None, _str | None]: ... def getlocale(category: int = ...) -> Sequence[_str]: ... def getpreferredencoding(do_setlocale: bool = ...) -> _str: ... def normalize(localename: _str) -> _str: ... @@ -91,6 +91,6 @@ def atof(string: _str, func: Callable[[_str], float] = ...) -> float: ... def atoi(string: _str) -> int: ... def str(val: float) -> _str: ... -locale_alias: Dict[_str, _str] # undocumented -locale_encoding_alias: Dict[_str, _str] # undocumented -windows_locale: Dict[int, _str] # undocumented +locale_alias: dict[_str, _str] # undocumented +locale_encoding_alias: dict[_str, _str] # undocumented +windows_locale: dict[int, _str] # undocumented diff --git a/mypy/typeshed/stdlib/@python2/logging/__init__.pyi b/mypy/typeshed/stdlib/@python2/logging/__init__.pyi index f981e2400624..9ca64dc966ae 100644 --- a/mypy/typeshed/stdlib/@python2/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/logging/__init__.pyi @@ -2,27 +2,11 @@ import threading from _typeshed import StrPath, SupportsWrite from time import struct_time from types import FrameType, TracebackType -from typing import ( - IO, - Any, - Callable, - Dict, - Generic, - List, - Mapping, - MutableMapping, - Optional, - Sequence, - Text, - Tuple, - TypeVar, - Union, - overload, -) +from typing import IO, Any, Callable, Generic, Mapping, MutableMapping, Optional, Sequence, Text, TypeVar, Union, overload -_SysExcInfoType = Union[Tuple[type, BaseException, Optional[TracebackType]], Tuple[None, None, None]] +_SysExcInfoType = Union[tuple[type, BaseException, Optional[TracebackType]], tuple[None, None, None]] _ExcInfoType = Union[None, bool, _SysExcInfoType] -_ArgsType = Union[Tuple[Any, ...], Mapping[str, Any]] +_ArgsType = Union[tuple[Any, ...], Mapping[str, Any]] _FilterType = Union[Filter, Callable[[LogRecord], int]] _Level = Union[int, Text] @@ -34,10 +18,10 @@ _srcfile: str | None def currentframe() -> FrameType: ... -_levelNames: Dict[int | str, str | int] # Union[int:str, str:int] +_levelNames: dict[int | str, str | int] # Union[int:str, str:int] class Filterer(object): - filters: List[Filter] + filters: list[Filter] def __init__(self) -> None: ... def addFilter(self, filter: _FilterType) -> None: ... def removeFilter(self, filter: _FilterType) -> None: ... @@ -48,7 +32,7 @@ class Logger(Filterer): level: int parent: Logger | PlaceHolder propagate: bool - handlers: List[Handler] + handlers: list[Handler] disabled: int def __init__(self, name: str, level: _Level = ...) -> None: ... def setLevel(self, level: _Level) -> None: ... @@ -56,35 +40,35 @@ class Logger(Filterer): def getEffectiveLevel(self) -> int: ... def getChild(self, suffix: str) -> Logger: ... def debug( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def info( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def warning( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... warn = warning def error( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def critical( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... fatal = critical def log( - self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def exception( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def _log( - self, level: int, msg: Any, args: _ArgsType, exc_info: _ExcInfoType | None = ..., extra: Dict[str, Any] | None = ... + self, level: int, msg: Any, args: _ArgsType, exc_info: _ExcInfoType | None = ..., extra: dict[str, Any] | None = ... ) -> None: ... # undocumented def filter(self, record: LogRecord) -> bool: ... def addHandler(self, hdlr: Handler) -> None: ... def removeHandler(self, hdlr: Handler) -> None: ... - def findCaller(self) -> Tuple[str, int, str]: ... + def findCaller(self) -> tuple[str, int, str]: ... def handle(self, record: LogRecord) -> None: ... def makeRecord( self, @@ -181,27 +165,27 @@ class LoggerAdapter(Generic[_L]): logger: _L extra: Mapping[str, Any] 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 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 + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def info( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def warning( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def error( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def exception( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def critical( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def log( - self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + self, level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... def isEnabledFor(self, level: int) -> bool: ... @@ -210,17 +194,17 @@ def getLogger() -> Logger: ... @overload def getLogger(name: Text | str) -> Logger: ... def getLoggerClass() -> type: ... -def debug(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... -def info(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... -def warning(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... +def debug(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any) -> None: ... +def info(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any) -> None: ... +def warning(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any) -> None: ... warn = warning -def error(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... -def critical(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... -def exception(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any) -> None: ... +def error(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any) -> None: ... +def critical(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any) -> None: ... +def exception(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any) -> None: ... def log( - level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Dict[str, Any] | None = ..., **kwargs: Any + level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: dict[str, Any] | None = ..., **kwargs: Any ) -> None: ... fatal = critical diff --git a/mypy/typeshed/stdlib/@python2/logging/config.pyi b/mypy/typeshed/stdlib/@python2/logging/config.pyi index 03707bb98f55..5597347d0961 100644 --- a/mypy/typeshed/stdlib/@python2/logging/config.pyi +++ b/mypy/typeshed/stdlib/@python2/logging/config.pyi @@ -1,10 +1,10 @@ from _typeshed import StrPath from threading import Thread -from typing import IO, Any, Dict +from typing import IO, Any _Path = StrPath -def dictConfig(config: Dict[str, Any]) -> None: ... -def fileConfig(fname: str | IO[str], defaults: Dict[str, str] | None = ..., disable_existing_loggers: bool = ...) -> None: ... +def dictConfig(config: dict[str, Any]) -> None: ... +def fileConfig(fname: str | IO[str], defaults: dict[str, str] | None = ..., disable_existing_loggers: bool = ...) -> None: ... def listen(port: int = ...) -> Thread: ... def stopListening() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/logging/handlers.pyi b/mypy/typeshed/stdlib/@python2/logging/handlers.pyi index d18d57e77af4..360e76c66558 100644 --- a/mypy/typeshed/stdlib/@python2/logging/handlers.pyi +++ b/mypy/typeshed/stdlib/@python2/logging/handlers.pyi @@ -1,7 +1,7 @@ from _typeshed import StrPath from logging import FileHandler, Handler, LogRecord from socket import SocketKind, SocketType -from typing import Any, ClassVar, Dict, List, Tuple +from typing import Any, ClassVar DEFAULT_TCP_LOGGING_PORT: int DEFAULT_UDP_LOGGING_PORT: int @@ -84,14 +84,14 @@ class SysLogHandler(Handler): LOG_LOCAL5: int LOG_LOCAL6: int LOG_LOCAL7: int - address: Tuple[str, int] | str # undocumented + address: tuple[str, int] | str # undocumented unixsocket: bool # undocumented socktype: SocketKind # undocumented facility: int # undocumented - priority_names: ClassVar[Dict[str, int]] # undocumented - facility_names: ClassVar[Dict[str, int]] # undocumented - priority_map: ClassVar[Dict[str, str]] # undocumented - def __init__(self, address: Tuple[str, int] | str = ..., facility: int = ..., socktype: SocketKind | None = ...) -> None: ... + priority_names: ClassVar[dict[str, int]] # undocumented + facility_names: ClassVar[dict[str, int]] # undocumented + priority_map: ClassVar[dict[str, str]] # undocumented + def __init__(self, address: tuple[str, int] | str = ..., facility: int = ..., socktype: SocketKind | None = ...) -> None: ... def encodePriority(self, facility: int | str, priority: int | str) -> int: ... def mapPriority(self, levelName: str) -> str: ... @@ -106,17 +106,17 @@ class SMTPHandler(Handler): # TODO `secure` can also be an empty tuple def __init__( self, - mailhost: str | Tuple[str, int], + mailhost: str | tuple[str, int], fromaddr: str, - toaddrs: List[str], + toaddrs: list[str], subject: str, - credentials: Tuple[str, str] | None = ..., - secure: Tuple[str] | Tuple[str, str] | None = ..., + credentials: tuple[str, str] | None = ..., + secure: tuple[str] | tuple[str, str] | None = ..., ) -> None: ... def getSubject(self, record: LogRecord) -> str: ... class BufferingHandler(Handler): - buffer: List[LogRecord] + buffer: list[LogRecord] def __init__(self, capacity: int) -> None: ... def shouldFlush(self, record: LogRecord) -> bool: ... @@ -126,4 +126,4 @@ class MemoryHandler(BufferingHandler): class HTTPHandler(Handler): def __init__(self, host: str, url: str, method: str = ...) -> None: ... - def mapLogRecord(self, record: LogRecord) -> Dict[str, Any]: ... + def mapLogRecord(self, record: LogRecord) -> dict[str, Any]: ... diff --git a/mypy/typeshed/stdlib/@python2/macpath.pyi b/mypy/typeshed/stdlib/@python2/macpath.pyi index bcb882e23eef..73d55b15328f 100644 --- a/mypy/typeshed/stdlib/@python2/macpath.pyi +++ b/mypy/typeshed/stdlib/@python2/macpath.pyi @@ -27,7 +27,7 @@ from posixpath import ( splitext as splitext, supports_unicode_filenames as supports_unicode_filenames, ) -from typing import AnyStr, Text, Tuple, overload +from typing import AnyStr, Text, overload altsep: str | None @@ -52,4 +52,4 @@ def join(__p1: bytes, __p2: bytes, __p3: Text, *p: Text) -> Text: ... def join(__p1: bytes, __p2: Text, *p: Text) -> Text: ... @overload def join(__p1: Text, *p: Text) -> Text: ... -def split(s: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def split(s: AnyStr) -> tuple[AnyStr, AnyStr]: ... diff --git a/mypy/typeshed/stdlib/@python2/mailbox.pyi b/mypy/typeshed/stdlib/@python2/mailbox.pyi index 18a66fa964c4..9c4aa66cdbb7 100644 --- a/mypy/typeshed/stdlib/@python2/mailbox.pyi +++ b/mypy/typeshed/stdlib/@python2/mailbox.pyi @@ -5,17 +5,13 @@ from typing import ( Any, AnyStr, Callable, - Dict, Generic, Iterable, Iterator, - List, Mapping, Protocol, Sequence, Text, - Tuple, - Type, TypeVar, Union, overload, @@ -27,10 +23,10 @@ _MessageT = TypeVar("_MessageT", bound=Message) _MessageData = Union[email.message.Message, bytes, str, IO[str], IO[bytes]] class _HasIteritems(Protocol): - def iteritems(self) -> Iterator[Tuple[str, _MessageData]]: ... + def iteritems(self) -> Iterator[tuple[str, _MessageData]]: ... class _HasItems(Protocol): - def items(self) -> Iterator[Tuple[str, _MessageData]]: ... + def items(self) -> Iterator[tuple[str, _MessageData]]: ... linesep: bytes @@ -55,12 +51,12 @@ class Mailbox(Generic[_MessageT]): # As '_ProxyFile' doesn't implement the full IO spec, and BytesIO is incompatible with it, get_file return is Any here def get_file(self, key: str) -> Any: ... def iterkeys(self) -> Iterator[str]: ... - def keys(self) -> List[str]: ... + def keys(self) -> list[str]: ... def itervalues(self) -> Iterator[_MessageT]: ... def __iter__(self) -> Iterator[_MessageT]: ... - def values(self) -> List[_MessageT]: ... - def iteritems(self) -> Iterator[Tuple[str, _MessageT]]: ... - def items(self) -> List[Tuple[str, _MessageT]]: ... + def values(self) -> list[_MessageT]: ... + def iteritems(self) -> Iterator[tuple[str, _MessageT]]: ... + def items(self) -> list[tuple[str, _MessageT]]: ... def __contains__(self, key: str) -> bool: ... def __len__(self) -> int: ... def clear(self) -> None: ... @@ -68,8 +64,8 @@ class Mailbox(Generic[_MessageT]): def pop(self, key: str, default: None = ...) -> _MessageT | None: ... @overload def pop(self, key: str, default: _T = ...) -> _MessageT | _T: ... - def popitem(self) -> Tuple[str, _MessageT]: ... - def update(self, arg: _HasIteritems | _HasItems | Iterable[Tuple[str, _MessageData]] | None = ...) -> None: ... + def popitem(self) -> tuple[str, _MessageT]: ... + def update(self, arg: _HasIteritems | _HasItems | Iterable[tuple[str, _MessageData]] | None = ...) -> None: ... def flush(self) -> None: ... def lock(self) -> None: ... def unlock(self) -> None: ... @@ -80,7 +76,7 @@ class Maildir(Mailbox[MaildirMessage]): colon: str def __init__(self, dirname: Text, factory: Callable[[IO[Any]], MaildirMessage] | None = ..., create: bool = ...) -> None: ... def get_file(self, key: str) -> _ProxyFile[bytes]: ... - def list_folders(self) -> List[str]: ... + def list_folders(self) -> list[str]: ... def get_folder(self, folder: Text) -> Maildir: ... def add_folder(self, folder: Text) -> Maildir: ... def remove_folder(self, folder: Text) -> None: ... @@ -103,18 +99,18 @@ class MMDF(_mboxMMDF[MMDFMessage]): class MH(Mailbox[MHMessage]): def __init__(self, path: Text, factory: Callable[[IO[Any]], MHMessage] | None = ..., create: bool = ...) -> None: ... def get_file(self, key: str) -> _ProxyFile[bytes]: ... - def list_folders(self) -> List[str]: ... + def list_folders(self) -> list[str]: ... def get_folder(self, folder: Text) -> MH: ... def add_folder(self, folder: Text) -> MH: ... def remove_folder(self, folder: Text) -> None: ... - def get_sequences(self) -> Dict[str, List[int]]: ... + def get_sequences(self) -> dict[str, list[int]]: ... def set_sequences(self, sequences: Mapping[str, Sequence[int]]) -> None: ... def pack(self) -> None: ... class Babyl(_singlefileMailbox[BabylMessage]): def __init__(self, path: Text, factory: Callable[[IO[Any]], BabylMessage] | None = ..., create: bool = ...) -> None: ... def get_file(self, key: str) -> IO[bytes]: ... - def get_labels(self) -> List[str]: ... + def get_labels(self) -> list[str]: ... class Message(email.message.Message): def __init__(self, message: _MessageData | None = ...) -> None: ... @@ -133,7 +129,7 @@ class MaildirMessage(Message): class _mboxMMDFMessage(Message): def get_from(self) -> str: ... - def set_from(self, from_: str, time_: bool | Tuple[int, int, int, int, int, int, int, int, int] | None = ...) -> None: ... + def set_from(self, from_: str, time_: bool | tuple[int, int, int, int, int, int, int, int, int] | None = ...) -> None: ... def get_flags(self) -> str: ... def set_flags(self, flags: Iterable[str]) -> None: ... def add_flag(self, flag: str) -> None: ... @@ -142,13 +138,13 @@ class _mboxMMDFMessage(Message): class mboxMessage(_mboxMMDFMessage): ... class MHMessage(Message): - def get_sequences(self) -> List[str]: ... + def get_sequences(self) -> list[str]: ... def set_sequences(self, sequences: Iterable[str]) -> None: ... def add_sequence(self, sequence: str) -> None: ... def remove_sequence(self, sequence: str) -> None: ... class BabylMessage(Message): - def get_labels(self) -> List[str]: ... + def get_labels(self) -> list[str]: ... def set_labels(self, labels: Iterable[str]) -> None: ... def add_label(self, label: str) -> None: ... def remove_label(self, label: str) -> None: ... @@ -163,13 +159,13 @@ class _ProxyFile(Generic[AnyStr]): def read(self, size: int | None = ...) -> AnyStr: ... def read1(self, size: int | None = ...) -> AnyStr: ... def readline(self, size: int | None = ...) -> AnyStr: ... - def readlines(self, sizehint: int | None = ...) -> List[AnyStr]: ... + def readlines(self, sizehint: int | None = ...) -> list[AnyStr]: ... def __iter__(self) -> Iterator[AnyStr]: ... def tell(self) -> int: ... def seek(self, offset: int, whence: int = ...) -> None: ... def close(self) -> None: ... def __enter__(self) -> _ProxyFile[AnyStr]: ... - def __exit__(self, exc_type: Type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... + def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... def readable(self) -> bool: ... def writable(self) -> bool: ... def seekable(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/mailcap.pyi b/mypy/typeshed/stdlib/@python2/mailcap.pyi index b29854f3c744..56218d1370fe 100644 --- a/mypy/typeshed/stdlib/@python2/mailcap.pyi +++ b/mypy/typeshed/stdlib/@python2/mailcap.pyi @@ -1,8 +1,8 @@ -from typing import Dict, List, Mapping, Sequence, Tuple, Union +from typing import Mapping, Sequence, Union -_Cap = Dict[str, Union[str, int]] +_Cap = dict[str, Union[str, int]] def findmatch( - caps: Mapping[str, List[_Cap]], MIMEtype: str, key: str = ..., filename: str = ..., plist: Sequence[str] = ... -) -> Tuple[str | None, _Cap | None]: ... -def getcaps() -> Dict[str, List[_Cap]]: ... + caps: Mapping[str, list[_Cap]], MIMEtype: str, key: str = ..., filename: str = ..., plist: Sequence[str] = ... +) -> tuple[str | None, _Cap | None]: ... +def getcaps() -> dict[str, list[_Cap]]: ... diff --git a/mypy/typeshed/stdlib/@python2/markupbase.pyi b/mypy/typeshed/stdlib/@python2/markupbase.pyi index 727daaacf25e..869c341b66aa 100644 --- a/mypy/typeshed/stdlib/@python2/markupbase.pyi +++ b/mypy/typeshed/stdlib/@python2/markupbase.pyi @@ -1,8 +1,6 @@ -from typing import Tuple - class ParserBase(object): def __init__(self) -> None: ... def error(self, message: str) -> None: ... def reset(self) -> None: ... - def getpos(self) -> Tuple[int, int]: ... + def getpos(self) -> tuple[int, int]: ... def unknown_decl(self, data: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/math.pyi b/mypy/typeshed/stdlib/@python2/math.pyi index caddcedd864b..643242a73fa9 100644 --- a/mypy/typeshed/stdlib/@python2/math.pyi +++ b/mypy/typeshed/stdlib/@python2/math.pyi @@ -1,4 +1,4 @@ -from typing import Iterable, SupportsFloat, SupportsInt, Tuple +from typing import Iterable, SupportsFloat, SupportsInt e: float pi: float @@ -23,7 +23,7 @@ def fabs(__x: SupportsFloat) -> float: ... def factorial(__x: SupportsInt) -> int: ... def floor(__x: SupportsFloat) -> float: ... def fmod(__x: SupportsFloat, __y: SupportsFloat) -> float: ... -def frexp(__x: SupportsFloat) -> Tuple[float, int]: ... +def frexp(__x: SupportsFloat) -> tuple[float, int]: ... def fsum(__seq: Iterable[float]) -> float: ... def gamma(__x: SupportsFloat) -> float: ... def hypot(__x: SupportsFloat, __y: SupportsFloat) -> float: ... @@ -34,7 +34,7 @@ def lgamma(__x: SupportsFloat) -> float: ... def log(x: SupportsFloat, base: SupportsFloat = ...) -> float: ... def log10(__x: SupportsFloat) -> float: ... def log1p(__x: SupportsFloat) -> float: ... -def modf(__x: SupportsFloat) -> Tuple[float, float]: ... +def modf(__x: SupportsFloat) -> tuple[float, float]: ... def pow(__x: SupportsFloat, __y: SupportsFloat) -> float: ... def radians(__x: SupportsFloat) -> float: ... def sin(__x: SupportsFloat) -> float: ... diff --git a/mypy/typeshed/stdlib/@python2/mimetypes.pyi b/mypy/typeshed/stdlib/@python2/mimetypes.pyi index a9661dab56ad..a7cddca65921 100644 --- a/mypy/typeshed/stdlib/@python2/mimetypes.pyi +++ b/mypy/typeshed/stdlib/@python2/mimetypes.pyi @@ -1,29 +1,29 @@ import sys -from typing import IO, Dict, List, Sequence, Text, Tuple +from typing import IO, Sequence, Text -def guess_type(url: Text, strict: bool = ...) -> Tuple[str | None, str | None]: ... -def guess_all_extensions(type: str, strict: bool = ...) -> List[str]: ... +def guess_type(url: Text, strict: bool = ...) -> tuple[str | None, str | None]: ... +def guess_all_extensions(type: str, strict: bool = ...) -> list[str]: ... def guess_extension(type: str, strict: bool = ...) -> str | None: ... def init(files: Sequence[str] | None = ...) -> None: ... -def read_mime_types(file: str) -> Dict[str, str] | None: ... +def read_mime_types(file: str) -> dict[str, str] | None: ... def add_type(type: str, ext: str, strict: bool = ...) -> None: ... inited: bool -knownfiles: List[str] -suffix_map: Dict[str, str] -encodings_map: Dict[str, str] -types_map: Dict[str, str] -common_types: Dict[str, str] +knownfiles: list[str] +suffix_map: dict[str, str] +encodings_map: dict[str, str] +types_map: dict[str, str] +common_types: dict[str, str] class MimeTypes: - suffix_map: Dict[str, str] - encodings_map: Dict[str, str] - types_map: Tuple[Dict[str, str], Dict[str, str]] - types_map_inv: Tuple[Dict[str, str], Dict[str, str]] - def __init__(self, filenames: Tuple[str, ...] = ..., strict: bool = ...) -> None: ... + suffix_map: dict[str, str] + encodings_map: dict[str, str] + types_map: tuple[dict[str, str], dict[str, str]] + types_map_inv: tuple[dict[str, str], dict[str, str]] + def __init__(self, filenames: tuple[str, ...] = ..., strict: bool = ...) -> None: ... def guess_extension(self, type: str, strict: bool = ...) -> str | None: ... - def guess_type(self, url: str, strict: bool = ...) -> Tuple[str | None, str | None]: ... - def guess_all_extensions(self, type: str, strict: bool = ...) -> List[str]: ... + def guess_type(self, url: str, strict: bool = ...) -> tuple[str | None, str | None]: ... + def guess_all_extensions(self, type: str, strict: bool = ...) -> list[str]: ... def read(self, filename: str, strict: bool = ...) -> None: ... def readfp(self, fp: IO[str], strict: bool = ...) -> None: ... if sys.platform == "win32": diff --git a/mypy/typeshed/stdlib/@python2/modulefinder.pyi b/mypy/typeshed/stdlib/@python2/modulefinder.pyi index 76fd014daf6e..458b037723f3 100644 --- a/mypy/typeshed/stdlib/@python2/modulefinder.pyi +++ b/mypy/typeshed/stdlib/@python2/modulefinder.pyi @@ -1,40 +1,39 @@ from types import CodeType -from typing import IO, Any, Container, Dict, Iterable, List, Sequence, Tuple +from typing import IO, Any, Container, Iterable, Sequence LOAD_CONST: int # undocumented IMPORT_NAME: int # undocumented STORE_NAME: int # undocumented STORE_GLOBAL: int # undocumented -STORE_OPS: Tuple[int, int] # undocumented +STORE_OPS: tuple[int, int] # undocumented EXTENDED_ARG: int # undocumented -packagePathMap: Dict[str, List[str]] # undocumented +packagePathMap: dict[str, list[str]] # undocumented def AddPackagePath(packagename: str, path: str) -> None: ... -replacePackageMap: Dict[str, str] # undocumented +replacePackageMap: dict[str, str] # undocumented def ReplacePackage(oldname: str, newname: str) -> None: ... class Module: # undocumented def __init__(self, name: str, file: str | None = ..., path: str | None = ...) -> None: ... - def __repr__(self) -> str: ... class ModuleFinder: - modules: Dict[str, Module] - path: List[str] # undocumented - badmodules: Dict[str, Dict[str, int]] # undocumented + modules: dict[str, Module] + path: list[str] # undocumented + badmodules: dict[str, dict[str, int]] # undocumented debug: int # undocumented indent: int # undocumented excludes: Container[str] # undocumented - replace_paths: Sequence[Tuple[str, str]] # undocumented + replace_paths: Sequence[tuple[str, str]] # undocumented def __init__( self, - path: List[str] | None = ..., + path: list[str] | None = ..., debug: int = ..., excludes: Container[str] = ..., - replace_paths: Sequence[Tuple[str, str]] = ..., + replace_paths: Sequence[tuple[str, str]] = ..., ) -> None: ... def msg(self, level: int, str: str, *args: Any) -> None: ... # undocumented def msgin(self, *args: Any) -> None: ... # undocumented @@ -42,22 +41,22 @@ class ModuleFinder: def run_script(self, pathname: str) -> None: ... def load_file(self, pathname: str) -> None: ... # undocumented def import_hook( - self, name: str, caller: Module | None = ..., fromlist: List[str] | None = ..., level: int = ... + self, name: str, caller: Module | None = ..., fromlist: list[str] | None = ..., level: int = ... ) -> Module | None: ... # undocumented def determine_parent(self, caller: Module | None, level: int = ...) -> Module | None: ... # undocumented - def find_head_package(self, parent: Module, name: str) -> Tuple[Module, str]: ... # undocumented + def find_head_package(self, parent: Module, name: str) -> tuple[Module, str]: ... # undocumented def load_tail(self, q: Module, tail: str) -> Module: ... # undocumented def ensure_fromlist(self, m: Module, fromlist: Iterable[str], recursive: int = ...) -> None: ... # undocumented def find_all_submodules(self, m: Module) -> Iterable[str]: ... # undocumented def import_module(self, partname: str, fqname: str, parent: Module) -> Module | None: ... # undocumented - def load_module(self, fqname: str, fp: IO[str], pathname: str, file_info: Tuple[str, str, str]) -> Module: ... # undocumented + def load_module(self, fqname: str, fp: IO[str], pathname: str, file_info: tuple[str, str, str]) -> Module: ... # undocumented def scan_code(self, co: CodeType, m: Module) -> None: ... # undocumented def load_package(self, fqname: str, pathname: str) -> Module: ... # undocumented def add_module(self, fqname: str) -> Module: ... # undocumented def find_module( self, name: str, path: str | None, parent: Module | None = ... - ) -> Tuple[IO[Any] | None, str | None, Tuple[str, str, int]]: ... # undocumented + ) -> tuple[IO[Any] | None, str | None, tuple[str, str, int]]: ... # undocumented def report(self) -> None: ... - def any_missing(self) -> List[str]: ... # undocumented - def any_missing_maybe(self) -> Tuple[List[str], List[str]]: ... # undocumented + def any_missing(self) -> list[str]: ... # undocumented + def any_missing_maybe(self) -> tuple[list[str], list[str]]: ... # undocumented def replace_paths_in_code(self, co: CodeType) -> CodeType: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/msilib/__init__.pyi b/mypy/typeshed/stdlib/@python2/msilib/__init__.pyi index fa6757696845..381ddffa5e92 100644 --- a/mypy/typeshed/stdlib/@python2/msilib/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/msilib/__init__.pyi @@ -1,6 +1,6 @@ import sys from types import ModuleType -from typing import Any, Container, Dict, Iterable, List, Sequence, Set, Tuple, Type +from typing import Any, Container, Iterable, Sequence from typing_extensions import Literal if sys.platform == "win32": @@ -24,19 +24,19 @@ if sys.platform == "win32": class Table: name: str - fields: List[Tuple[int, str, int]] + fields: list[tuple[int, str, int]] def __init__(self, name: str) -> None: ... def add_field(self, index: int, name: str, type: int) -> None: ... def sql(self) -> str: ... def create(self, db: _Database) -> None: ... class _Unspecified: ... def change_sequence( - seq: Sequence[Tuple[str, str | None, int]], + seq: Sequence[tuple[str, str | None, int]], action: str, - seqno: int | Type[_Unspecified] = ..., - cond: str | Type[_Unspecified] = ..., + seqno: int | type[_Unspecified] = ..., + cond: str | type[_Unspecified] = ..., ) -> None: ... - def add_data(db: _Database, table: str, values: Iterable[Tuple[Any, ...]]) -> None: ... + def add_data(db: _Database, table: str, values: Iterable[tuple[Any, ...]]) -> None: ... def add_stream(db: _Database, name: str, path: str) -> None: ... def init_database( name: str, schema: ModuleType, ProductName: str, ProductCode: str, ProductVersion: str, Manufacturer: str @@ -47,14 +47,14 @@ if sys.platform == "win32": class CAB: name: str - files: List[Tuple[str, str]] - filenames: Set[str] + files: list[tuple[str, str]] + filenames: set[str] index: int def __init__(self, name: str) -> None: ... def gen_id(self, file: str) -> str: ... - def append(self, full: str, file: str, logical: str) -> Tuple[int, str]: ... + def append(self, full: str, file: str, logical: str) -> tuple[int, str]: ... def commit(self, db: _Database) -> None: ... - _directories: Set[str] + _directories: set[str] class Directory: db: _Database @@ -63,9 +63,9 @@ if sys.platform == "win32": physical: str logical: str component: str | None - short_names: Set[str] - ids: Set[str] - keyfiles: Dict[str, str] + short_names: set[str] + ids: set[str] + keyfiles: dict[str, str] componentflags: int | None absolute: str def __init__( @@ -88,13 +88,12 @@ if sys.platform == "win32": ) -> None: ... def make_short(self, file: str) -> str: ... def add_file(self, file: str, src: str | None = ..., version: str | None = ..., language: str | None = ...) -> str: ... - def glob(self, pattern: str, exclude: Container[str] | None = ...) -> List[str]: ... + def glob(self, pattern: str, exclude: Container[str] | None = ...) -> list[str]: ... def remove_pyc(self) -> None: ... class Binary: name: str def __init__(self, fname: str) -> None: ... - def __repr__(self) -> str: ... class Feature: id: str diff --git a/mypy/typeshed/stdlib/@python2/msilib/schema.pyi b/mypy/typeshed/stdlib/@python2/msilib/schema.pyi index d59e9767c3de..4ad9a1783fcd 100644 --- a/mypy/typeshed/stdlib/@python2/msilib/schema.pyi +++ b/mypy/typeshed/stdlib/@python2/msilib/schema.pyi @@ -1,5 +1,4 @@ import sys -from typing import List, Tuple if sys.platform == "win32": from . import Table @@ -90,6 +89,6 @@ if sys.platform == "win32": Upgrade: Table Verb: Table - tables: List[Table] + tables: list[Table] - _Validation_records: List[Tuple[str, str, str, int | None, int | None, str | None, int | None, str | None, str | None, str]] + _Validation_records: list[tuple[str, str, str, int | None, int | None, str | None, int | None, str | None, str | None, str]] diff --git a/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi b/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi index e4f400d33233..87dff754009d 100644 --- a/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi +++ b/mypy/typeshed/stdlib/@python2/msilib/sequence.pyi @@ -1,9 +1,9 @@ import sys -from typing import List, Optional, Tuple +from typing import Optional if sys.platform == "win32": - _SequenceType = List[Tuple[str, Optional[str], int]] + _SequenceType = list[tuple[str, Optional[str], int]] AdminExecuteSequence: _SequenceType AdminUISequence: _SequenceType @@ -11,4 +11,4 @@ if sys.platform == "win32": InstallExecuteSequence: _SequenceType InstallUISequence: _SequenceType - tables: List[str] + tables: list[str] diff --git a/mypy/typeshed/stdlib/@python2/msilib/text.pyi b/mypy/typeshed/stdlib/@python2/msilib/text.pyi index 4ae8ee68184b..879429ecea85 100644 --- a/mypy/typeshed/stdlib/@python2/msilib/text.pyi +++ b/mypy/typeshed/stdlib/@python2/msilib/text.pyi @@ -1,9 +1,8 @@ import sys -from typing import List, Tuple if sys.platform == "win32": - ActionText: List[Tuple[str, str, str | None]] - UIText: List[Tuple[str, str | None]] + ActionText: list[tuple[str, str, str | None]] + UIText: list[tuple[str, str | None]] - tables: List[str] + tables: list[str] diff --git a/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi index 80a1456d1be8..a5381ed3839c 100644 --- a/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/__init__.pyi @@ -2,7 +2,7 @@ import array import threading import weakref from Queue import Queue -from typing import Any, List +from typing import Any class DummyProcess(threading.Thread): _children: weakref.WeakKeyDictionary[Any, Any] @@ -35,7 +35,7 @@ JoinableQueue = Queue def Array(typecode, sequence, lock=...) -> array.array[Any]: ... def Manager() -> Any: ... def Pool(processes=..., initializer=..., initargs=...) -> Any: ... -def active_children() -> List[Any]: ... +def active_children() -> list[Any]: ... def current_process() -> threading.Thread: ... def freeze_support() -> None: ... def shutdown() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/connection.pyi b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/connection.pyi index ae5e05e9ccdd..f01b3f8cd660 100644 --- a/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/connection.pyi +++ b/mypy/typeshed/stdlib/@python2/multiprocessing/dummy/connection.pyi @@ -1,7 +1,7 @@ from Queue import Queue -from typing import Any, List, Tuple +from typing import Any -families: List[None] +families: list[None] class Connection(object): _in: Any @@ -22,4 +22,4 @@ class Listener(object): def close(self) -> None: ... def Client(address) -> Connection: ... -def Pipe(duplex=...) -> Tuple[Connection, Connection]: ... +def Pipe(duplex=...) -> tuple[Connection, Connection]: ... diff --git a/mypy/typeshed/stdlib/@python2/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/@python2/multiprocessing/pool.pyi index be9747e89c2f..3a1245fe1b7f 100644 --- a/mypy/typeshed/stdlib/@python2/multiprocessing/pool.pyi +++ b/mypy/typeshed/stdlib/@python2/multiprocessing/pool.pyi @@ -1,6 +1,4 @@ -from typing import Any, Callable, Dict, Iterable, Iterator, List, TypeVar - -_T = TypeVar("_T", bound=Pool) +from typing import Any, Callable, Iterable, Iterator class AsyncResult: def get(self, timeout: float | None = ...) -> Any: ... @@ -22,15 +20,15 @@ class Pool(object): initargs: Iterable[Any] = ..., maxtasksperchild: int | None = ..., ) -> None: ... - def apply(self, func: Callable[..., Any], args: Iterable[Any] = ..., kwds: Dict[str, Any] = ...) -> Any: ... + def apply(self, func: Callable[..., Any], args: Iterable[Any] = ..., kwds: dict[str, Any] = ...) -> Any: ... def apply_async( self, func: Callable[..., Any], args: Iterable[Any] = ..., - kwds: Dict[str, Any] = ..., + kwds: dict[str, Any] = ..., callback: Callable[..., None] | None = ..., ) -> AsyncResult: ... - def map(self, func: Callable[..., Any], iterable: Iterable[Any] = ..., chunksize: int | None = ...) -> List[Any]: ... + def map(self, func: Callable[..., Any], iterable: Iterable[Any] = ..., chunksize: int | None = ...) -> list[Any]: ... def map_async( self, func: Callable[..., Any], diff --git a/mypy/typeshed/stdlib/@python2/mutex.pyi b/mypy/typeshed/stdlib/@python2/mutex.pyi index e0931dc1188a..fd5363de73e5 100644 --- a/mypy/typeshed/stdlib/@python2/mutex.pyi +++ b/mypy/typeshed/stdlib/@python2/mutex.pyi @@ -1,10 +1,11 @@ -from typing import Any, Callable, Deque, TypeVar +from collections import deque +from typing import Any, Callable, TypeVar _T = TypeVar("_T") class mutex: locked: bool - queue: Deque[Any] + queue: deque[Any] def __init__(self) -> None: ... def test(self) -> bool: ... def testandset(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/netrc.pyi b/mypy/typeshed/stdlib/@python2/netrc.pyi index 3033c2f78955..3d92c7b4d43b 100644 --- a/mypy/typeshed/stdlib/@python2/netrc.pyi +++ b/mypy/typeshed/stdlib/@python2/netrc.pyi @@ -1,4 +1,4 @@ -from typing import Dict, List, Optional, Text, Tuple +from typing import Optional, Text class NetrcParseError(Exception): filename: str | None @@ -7,10 +7,10 @@ class NetrcParseError(Exception): def __init__(self, msg: str, filename: Text | None = ..., lineno: int | None = ...) -> None: ... # (login, account, password) tuple -_NetrcTuple = Tuple[str, Optional[str], Optional[str]] +_NetrcTuple = tuple[str, Optional[str], Optional[str]] class netrc: - hosts: Dict[str, _NetrcTuple] - macros: Dict[str, List[str]] + hosts: dict[str, _NetrcTuple] + macros: dict[str, list[str]] def __init__(self, file: Text | None = ...) -> None: ... def authenticators(self, host: str) -> _NetrcTuple | None: ... diff --git a/mypy/typeshed/stdlib/@python2/nis.pyi b/mypy/typeshed/stdlib/@python2/nis.pyi index bc6c2bc07256..b762ae46241c 100644 --- a/mypy/typeshed/stdlib/@python2/nis.pyi +++ b/mypy/typeshed/stdlib/@python2/nis.pyi @@ -1,9 +1,8 @@ import sys -from typing import Dict, List if sys.platform != "win32": - def cat(map: str, domain: str = ...) -> Dict[str, str]: ... + def cat(map: str, domain: str = ...) -> dict[str, str]: ... def get_default_domain() -> str: ... - def maps(domain: str = ...) -> List[str]: ... + def maps(domain: str = ...) -> list[str]: ... def match(key: str, map: str, domain: str = ...) -> str: ... class error(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/nntplib.pyi b/mypy/typeshed/stdlib/@python2/nntplib.pyi index 56545d3b88b4..602617665ea8 100644 --- a/mypy/typeshed/stdlib/@python2/nntplib.pyi +++ b/mypy/typeshed/stdlib/@python2/nntplib.pyi @@ -1,9 +1,10 @@ import datetime import socket import ssl -from typing import IO, Any, Dict, Iterable, List, NamedTuple, Tuple, TypeVar, Union +from _typeshed import Self +from builtins import list as List # alias to avoid a name clash with a method named `list` in `_NNTPBase` +from typing import IO, Any, Iterable, NamedTuple, Union -_SelfT = TypeVar("_SelfT", bound=_NNTPBase) _File = Union[IO[bytes], bytes, str, None] class NNTPError(Exception): @@ -27,7 +28,7 @@ class GroupInfo(NamedTuple): class ArticleInfo(NamedTuple): number: int message_id: str - lines: List[bytes] + lines: list[bytes] def decode_header(header_str: str) -> str: ... @@ -45,35 +46,35 @@ class _NNTPBase: nntp_implementation: str nntp_version: int def __init__(self, file: IO[bytes], host: str, readermode: bool | None = ..., timeout: float = ...) -> None: ... - def __enter__(self: _SelfT) -> _SelfT: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... def getwelcome(self) -> str: ... - def getcapabilities(self) -> Dict[str, List[str]]: ... + def getcapabilities(self) -> dict[str, List[str]]: ... def set_debuglevel(self, level: int) -> None: ... def debug(self, level: int) -> None: ... - def capabilities(self) -> Tuple[str, Dict[str, List[str]]]: ... - def newgroups(self, date: datetime.date | datetime.datetime, *, file: _File = ...) -> Tuple[str, List[str]]: ... - def newnews(self, group: str, date: datetime.date | datetime.datetime, *, file: _File = ...) -> Tuple[str, List[str]]: ... - def list(self, group_pattern: str | None = ..., *, file: _File = ...) -> Tuple[str, List[str]]: ... + def capabilities(self) -> tuple[str, dict[str, List[str]]]: ... + def newgroups(self, date: datetime.date | datetime.datetime, *, file: _File = ...) -> tuple[str, List[str]]: ... + def newnews(self, group: str, date: datetime.date | datetime.datetime, *, file: _File = ...) -> tuple[str, List[str]]: ... + def list(self, group_pattern: str | None = ..., *, file: _File = ...) -> tuple[str, List[str]]: ... def description(self, group: str) -> str: ... - def descriptions(self, group_pattern: str) -> Tuple[str, Dict[str, str]]: ... - def group(self, name: str) -> Tuple[str, int, int, int, str]: ... - def help(self, *, file: _File = ...) -> Tuple[str, List[str]]: ... - def stat(self, message_spec: Any = ...) -> Tuple[str, int, str]: ... - def next(self) -> Tuple[str, int, str]: ... - def last(self) -> Tuple[str, int, str]: ... - def head(self, message_spec: Any = ..., *, file: _File = ...) -> Tuple[str, ArticleInfo]: ... - def body(self, message_spec: Any = ..., *, file: _File = ...) -> Tuple[str, ArticleInfo]: ... - def article(self, message_spec: Any = ..., *, file: _File = ...) -> Tuple[str, ArticleInfo]: ... + def descriptions(self, group_pattern: str) -> tuple[str, dict[str, str]]: ... + def group(self, name: str) -> tuple[str, int, int, int, str]: ... + def help(self, *, file: _File = ...) -> tuple[str, List[str]]: ... + def stat(self, message_spec: Any = ...) -> tuple[str, int, str]: ... + def next(self) -> tuple[str, int, str]: ... + def last(self) -> tuple[str, int, str]: ... + def head(self, message_spec: Any = ..., *, file: _File = ...) -> tuple[str, ArticleInfo]: ... + def body(self, message_spec: Any = ..., *, file: _File = ...) -> tuple[str, ArticleInfo]: ... + def article(self, message_spec: Any = ..., *, file: _File = ...) -> tuple[str, ArticleInfo]: ... def slave(self) -> str: ... - def xhdr(self, hdr: str, str: Any, *, file: _File = ...) -> Tuple[str, List[str]]: ... - def xover(self, start: int, end: int, *, file: _File = ...) -> Tuple[str, List[Tuple[int, Dict[str, str]]]]: ... + def xhdr(self, hdr: str, str: Any, *, file: _File = ...) -> tuple[str, List[str]]: ... + def xover(self, start: int, end: int, *, file: _File = ...) -> tuple[str, List[tuple[int, dict[str, str]]]]: ... def over( - self, message_spec: None | str | List[Any] | Tuple[Any, ...], *, file: _File = ... - ) -> Tuple[str, List[Tuple[int, Dict[str, str]]]]: ... - def xgtitle(self, group: str, *, file: _File = ...) -> Tuple[str, List[Tuple[str, str]]]: ... - def xpath(self, id: Any) -> Tuple[str, str]: ... - def date(self) -> Tuple[str, datetime.datetime]: ... + self, message_spec: None | str | List[Any] | tuple[Any, ...], *, file: _File = ... + ) -> tuple[str, List[tuple[int, dict[str, str]]]]: ... + def xgtitle(self, group: str, *, file: _File = ...) -> tuple[str, List[tuple[str, str]]]: ... + def xpath(self, id: Any) -> tuple[str, str]: ... + def date(self) -> tuple[str, datetime.datetime]: ... def post(self, data: bytes | Iterable[bytes]) -> str: ... def ihave(self, message_id: Any, data: bytes | Iterable[bytes]) -> str: ... def quit(self) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/ntpath.pyi b/mypy/typeshed/stdlib/@python2/ntpath.pyi index 514db760886f..33732903cb4c 100644 --- a/mypy/typeshed/stdlib/@python2/ntpath.pyi +++ b/mypy/typeshed/stdlib/@python2/ntpath.pyi @@ -1,7 +1,7 @@ import os import sys from genericpath import exists as exists -from typing import Any, AnyStr, Callable, List, Sequence, Text, Tuple, TypeVar, overload +from typing import Any, AnyStr, Callable, Sequence, Text, TypeVar, overload _T = TypeVar("_T") @@ -74,11 +74,11 @@ def relpath(path: Text, start: Text | None = ...) -> Text: ... def samefile(f1: Text, f2: Text) -> bool: ... def sameopenfile(fp1: int, fp2: int) -> bool: ... def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... -def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def split(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... +def splitdrive(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... +def splitext(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... if sys.platform == "win32": - def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + def splitunc(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... # deprecated -def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... +def walk(path: AnyStr, visit: Callable[[_T, AnyStr, list[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/opcode.pyi b/mypy/typeshed/stdlib/@python2/opcode.pyi index 893dd7c7df9c..be162da4e496 100644 --- a/mypy/typeshed/stdlib/@python2/opcode.pyi +++ b/mypy/typeshed/stdlib/@python2/opcode.pyi @@ -1,15 +1,15 @@ -from typing import Dict, List, Sequence +from typing import Sequence cmp_op: Sequence[str] -hasconst: List[int] -hasname: List[int] -hasjrel: List[int] -hasjabs: List[int] -haslocal: List[int] -hascompare: List[int] -hasfree: List[int] -opname: List[str] +hasconst: list[int] +hasname: list[int] +hasjrel: list[int] +hasjabs: list[int] +haslocal: list[int] +hascompare: list[int] +hasfree: list[int] +opname: list[str] -opmap: Dict[str, int] +opmap: dict[str, int] HAVE_ARGUMENT: int EXTENDED_ARG: int diff --git a/mypy/typeshed/stdlib/@python2/operator.pyi b/mypy/typeshed/stdlib/@python2/operator.pyi index 76a8a9b6bee4..cff20b85898b 100644 --- a/mypy/typeshed/stdlib/@python2/operator.pyi +++ b/mypy/typeshed/stdlib/@python2/operator.pyi @@ -1,16 +1,4 @@ -from typing import ( - Any, - Container, - Generic, - Mapping, - MutableMapping, - MutableSequence, - Sequence, - SupportsAbs, - Tuple, - TypeVar, - overload, -) +from typing import Any, Container, Generic, Mapping, MutableMapping, MutableSequence, Sequence, SupportsAbs, TypeVar, overload _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) @@ -128,26 +116,26 @@ class attrgetter(Generic[_T_co]): @overload def __new__(cls, attr: str) -> attrgetter[Any]: ... @overload - def __new__(cls, attr: str, __attr2: str) -> attrgetter[Tuple[Any, Any]]: ... + def __new__(cls, attr: str, __attr2: str) -> attrgetter[tuple[Any, Any]]: ... @overload - def __new__(cls, attr: str, __attr2: str, __attr3: str) -> attrgetter[Tuple[Any, Any, Any]]: ... + def __new__(cls, attr: str, __attr2: str, __attr3: str) -> attrgetter[tuple[Any, Any, Any]]: ... @overload - def __new__(cls, attr: str, __attr2: str, __attr3: str, __attr4: str) -> attrgetter[Tuple[Any, Any, Any, Any]]: ... + def __new__(cls, attr: str, __attr2: str, __attr3: str, __attr4: str) -> attrgetter[tuple[Any, Any, Any, Any]]: ... @overload - def __new__(cls, attr: str, *attrs: str) -> attrgetter[Tuple[Any, ...]]: ... + def __new__(cls, attr: str, *attrs: str) -> attrgetter[tuple[Any, ...]]: ... def __call__(self, obj: Any) -> _T_co: ... class itemgetter(Generic[_T_co]): @overload def __new__(cls, item: Any) -> itemgetter[Any]: ... @overload - def __new__(cls, item: Any, __item2: Any) -> itemgetter[Tuple[Any, Any]]: ... + def __new__(cls, item: Any, __item2: Any) -> itemgetter[tuple[Any, Any]]: ... @overload - def __new__(cls, item: Any, __item2: Any, __item3: Any) -> itemgetter[Tuple[Any, Any, Any]]: ... + def __new__(cls, item: Any, __item2: Any, __item3: Any) -> itemgetter[tuple[Any, Any, Any]]: ... @overload - def __new__(cls, item: Any, __item2: Any, __item3: Any, __item4: Any) -> itemgetter[Tuple[Any, Any, Any, Any]]: ... + def __new__(cls, item: Any, __item2: Any, __item3: Any, __item4: Any) -> itemgetter[tuple[Any, Any, Any, Any]]: ... @overload - def __new__(cls, item: Any, *items: Any) -> itemgetter[Tuple[Any, ...]]: ... + def __new__(cls, item: Any, *items: Any) -> itemgetter[tuple[Any, ...]]: ... def __call__(self, obj: Any) -> _T_co: ... class methodcaller: diff --git a/mypy/typeshed/stdlib/@python2/optparse.pyi b/mypy/typeshed/stdlib/@python2/optparse.pyi index 08a926e301b3..a99bc0a6fb3b 100644 --- a/mypy/typeshed/stdlib/@python2/optparse.pyi +++ b/mypy/typeshed/stdlib/@python2/optparse.pyi @@ -1,9 +1,9 @@ -from typing import IO, Any, AnyStr, Callable, Dict, Iterable, List, Mapping, Sequence, Tuple, Type, Union, overload +from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, Sequence, Union, overload # See https://groups.google.com/forum/#!topic/python-ideas/gA1gdj3RZ5g _Text = Union[str, unicode] -NO_DEFAULT: Tuple[_Text, ...] +NO_DEFAULT: tuple[_Text, ...] SUPPRESS_HELP: _Text SUPPRESS_USAGE: _Text @@ -42,7 +42,7 @@ class HelpFormatter: indent_increment: int level: int max_help_position: int - option_strings: Dict[Option, _Text] + option_strings: dict[Option, _Text] parser: OptionParser short_first: Any width: int @@ -76,25 +76,25 @@ class TitledHelpFormatter(HelpFormatter): def format_usage(self, usage: _Text) -> _Text: ... class Option: - ACTIONS: Tuple[_Text, ...] - ALWAYS_TYPED_ACTIONS: Tuple[_Text, ...] - ATTRS: List[_Text] - CHECK_METHODS: List[Callable[..., Any]] | None - CONST_ACTIONS: Tuple[_Text, ...] - STORE_ACTIONS: Tuple[_Text, ...] - TYPED_ACTIONS: Tuple[_Text, ...] - TYPES: Tuple[_Text, ...] - TYPE_CHECKER: Dict[_Text, Callable[..., Any]] - _long_opts: List[_Text] - _short_opts: List[_Text] + ACTIONS: tuple[_Text, ...] + ALWAYS_TYPED_ACTIONS: tuple[_Text, ...] + ATTRS: list[_Text] + CHECK_METHODS: list[Callable[..., Any]] | None + CONST_ACTIONS: tuple[_Text, ...] + STORE_ACTIONS: tuple[_Text, ...] + TYPED_ACTIONS: tuple[_Text, ...] + TYPES: tuple[_Text, ...] + TYPE_CHECKER: dict[_Text, Callable[..., Any]] + _long_opts: list[_Text] + _short_opts: list[_Text] action: _Text dest: _Text | None default: Any nargs: int type: Any callback: Callable[..., Any] | None - callback_args: Tuple[Any, ...] | None - callback_kwargs: Dict[_Text, Any] | None + callback_args: tuple[Any, ...] | None + callback_kwargs: dict[_Text, Any] | None help: _Text | None metavar: _Text | None def __init__(self, *opts: _Text | None, **attrs: Any) -> None: ... @@ -104,9 +104,9 @@ class Option: def _check_const(self) -> None: ... def _check_dest(self) -> None: ... def _check_nargs(self) -> None: ... - def _check_opt_strings(self, opts: Iterable[_Text | None]) -> List[_Text]: ... + def _check_opt_strings(self, opts: Iterable[_Text | None]) -> list[_Text]: ... def _check_type(self) -> None: ... - def _set_attrs(self, attrs: Dict[_Text, Any]) -> None: ... + def _set_attrs(self, attrs: dict[_Text, Any]) -> None: ... def _set_opt_strings(self, opts: Iterable[_Text]) -> None: ... def check_value(self, opt: _Text, value: Any) -> Any: ... def convert_value(self, opt: _Text, value: Any) -> Any: ... @@ -118,13 +118,13 @@ class Option: make_option = Option class OptionContainer: - _long_opt: Dict[_Text, Option] - _short_opt: Dict[_Text, Option] + _long_opt: dict[_Text, Option] + _short_opt: dict[_Text, Option] conflict_handler: _Text - defaults: Dict[_Text, Any] + defaults: dict[_Text, Any] description: Any - option_class: Type[Option] - def __init__(self, option_class: Type[Option], conflict_handler: Any, description: Any) -> None: ... + option_class: type[Option] + def __init__(self, option_class: type[Option], conflict_handler: Any, description: Any) -> None: ... def _check_conflict(self, option: Any) -> None: ... def _create_option_mappings(self) -> None: ... def _share_option_mappings(self, parser: OptionParser) -> None: ... @@ -145,7 +145,7 @@ class OptionContainer: def set_description(self, description: Any) -> None: ... class OptionGroup(OptionContainer): - option_list: List[Option] + option_list: list[Option] parser: OptionParser title: _Text def __init__(self, parser: OptionParser, title: _Text, description: _Text | None = ...) -> None: ... @@ -167,13 +167,13 @@ class OptionParser(OptionContainer): allow_interspersed_args: bool epilog: _Text | None formatter: HelpFormatter - largs: List[_Text] | None - option_groups: List[OptionGroup] - option_list: List[Option] + largs: list[_Text] | None + option_groups: list[OptionGroup] + option_list: list[Option] process_default_values: Any prog: _Text | None - rargs: List[Any] | None - standard_option_list: List[Option] + rargs: list[Any] | None + standard_option_list: list[Option] usage: _Text | None values: Values | None version: _Text @@ -181,7 +181,7 @@ class OptionParser(OptionContainer): self, usage: _Text | None = ..., option_list: Iterable[Option] | None = ..., - option_class: Type[Option] = ..., + option_class: type[Option] = ..., version: _Text | None = ..., conflict_handler: _Text = ..., description: _Text | None = ..., @@ -193,19 +193,19 @@ class OptionParser(OptionContainer): def _add_help_option(self) -> None: ... def _add_version_option(self) -> None: ... def _create_option_list(self) -> None: ... - def _get_all_options(self) -> List[Option]: ... - def _get_args(self, args: Iterable[Any]) -> List[Any]: ... + def _get_all_options(self) -> list[Option]: ... + def _get_args(self, args: Iterable[Any]) -> list[Any]: ... def _init_parsing_state(self) -> None: ... def _match_long_opt(self, opt: _Text) -> _Text: ... def _populate_option_list(self, option_list: Iterable[Option], add_help: bool = ...) -> None: ... - def _process_args(self, largs: List[Any], rargs: List[Any], values: Values) -> None: ... - def _process_long_opt(self, rargs: List[Any], values: Any) -> None: ... - def _process_short_opts(self, rargs: List[Any], values: Any) -> None: ... + def _process_args(self, largs: list[Any], rargs: list[Any], values: Values) -> None: ... + def _process_long_opt(self, rargs: list[Any], values: Any) -> None: ... + def _process_short_opts(self, rargs: list[Any], values: Any) -> None: ... @overload def add_option_group(self, __opt_group: OptionGroup) -> OptionGroup: ... @overload def add_option_group(self, *args: Any, **kwargs: Any) -> OptionGroup: ... - def check_values(self, values: Values, args: List[_Text]) -> Tuple[Values, List[_Text]]: ... + def check_values(self, values: Values, args: list[_Text]) -> tuple[Values, list[_Text]]: ... def disable_interspersed_args(self) -> None: ... def enable_interspersed_args(self) -> None: ... def error(self, msg: _Text) -> None: ... @@ -219,7 +219,7 @@ class OptionParser(OptionContainer): def get_prog_name(self) -> _Text: ... def get_usage(self) -> _Text: ... def get_version(self) -> _Text: ... - def parse_args(self, args: Sequence[AnyStr] | None = ..., values: Values | None = ...) -> Tuple[Values, List[AnyStr]]: ... + def parse_args(self, args: Sequence[AnyStr] | None = ..., values: Values | None = ...) -> tuple[Values, list[AnyStr]]: ... def print_usage(self, file: IO[str] | None = ...) -> None: ... def print_help(self, file: IO[str] | None = ...) -> None: ... def print_version(self, file: IO[str] | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/os/__init__.pyi b/mypy/typeshed/stdlib/@python2/os/__init__.pyi index 1955c07020de..c14ae1207c50 100644 --- a/mypy/typeshed/stdlib/@python2/os/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/os/__init__.pyi @@ -7,17 +7,14 @@ from typing import ( Any, AnyStr, Callable, - Dict, Generic, Iterator, - List, Mapping, MutableMapping, NamedTuple, NoReturn, Sequence, Text, - Tuple, TypeVar, Union, overload, @@ -90,7 +87,7 @@ W_OK: int X_OK: int class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): - def copy(self) -> Dict[AnyStr, AnyStr]: ... + def copy(self) -> dict[AnyStr, AnyStr]: ... def __delitem__(self, key: AnyStr) -> None: ... def __getitem__(self, key: AnyStr) -> AnyStr: ... def __setitem__(self, key: AnyStr, value: AnyStr) -> None: ... @@ -100,9 +97,9 @@ class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): environ: _Environ[str] if sys.platform != "win32": # Unix only - confstr_names: Dict[str, int] - pathconf_names: Dict[str, int] - sysconf_names: Dict[str, int] + confstr_names: dict[str, int] + pathconf_names: dict[str, int] + sysconf_names: dict[str, int] EX_OK: int EX_USAGE: int @@ -161,12 +158,12 @@ if sys.platform != "win32": def getegid() -> int: ... def geteuid() -> int: ... def getgid() -> int: ... - def getgroups() -> List[int]: ... # Unix only, behaves differently on Mac + def getgroups() -> list[int]: ... # Unix only, behaves differently on Mac def initgroups(username: str, gid: int) -> None: ... def getpgid(pid: int) -> int: ... def getpgrp() -> int: ... - def getresuid() -> Tuple[int, int, int]: ... - def getresgid() -> Tuple[int, int, int]: ... + def getresuid() -> tuple[int, int, int]: ... + def getresgid() -> tuple[int, int, int]: ... def getuid() -> int: ... def setegid(egid: int) -> None: ... def seteuid(euid: int) -> None: ... @@ -181,7 +178,7 @@ if sys.platform != "win32": def getsid(pid: int) -> int: ... def setsid() -> None: ... def setuid(uid: int) -> None: ... - def uname() -> Tuple[str, str, str, str, str]: ... + def uname() -> tuple[str, str, str, str, str]: ... @overload def getenv(key: Text) -> str | None: ... @@ -198,7 +195,7 @@ def fstat(fd: int) -> Any: ... def fsync(fd: FileDescriptorLike) -> None: ... def lseek(fd: int, pos: int, how: int) -> int: ... def open(file: Text, flags: int, mode: int = ...) -> int: ... -def pipe() -> Tuple[int, int]: ... +def pipe() -> tuple[int, int]: ... def read(fd: int, n: int) -> bytes: ... def write(fd: int, string: bytes | buffer) -> int: ... def access(path: Text, mode: int) -> bool: ... @@ -230,7 +227,7 @@ def symlink(source: Text, link_name: Text) -> None: ... def unlink(path: Text) -> None: ... # TODO: add ns, dir_fd, follow_symlinks argument -def utime(path: Text, times: Tuple[float, float] | None) -> None: ... +def utime(path: Text, times: tuple[float, float] | None) -> None: ... if sys.platform != "win32": # Unix only @@ -242,7 +239,7 @@ if sys.platform != "win32": def fstatvfs(fd: int) -> _StatVFS: ... def ftruncate(fd: int, length: int) -> None: ... def isatty(fd: int) -> bool: ... - def openpty() -> Tuple[int, int]: ... # some flavors of Unix + def openpty() -> tuple[int, int]: ... # some flavors of Unix def tcgetpgrp(fd: int) -> int: ... def tcsetpgrp(fd: int, pg: int) -> None: ... def ttyname(fd: int) -> str: ... @@ -258,7 +255,7 @@ if sys.platform != "win32": def walk( top: AnyStr, topdown: bool = ..., onerror: Callable[[OSError], Any] | None = ..., followlinks: bool = ... -) -> Iterator[Tuple[AnyStr, List[AnyStr], List[AnyStr]]]: ... +) -> Iterator[tuple[AnyStr, list[AnyStr], list[AnyStr]]]: ... def abort() -> NoReturn: ... # These are defined as execl(file, *args) but the first *arg is mandatory. @@ -271,7 +268,7 @@ def execlpe(file: Text, __arg0: bytes | Text, *args: Any) -> NoReturn: ... # The docs say `args: tuple or list of strings` # The implementation enforces tuple or list so we can't use Sequence. -_ExecVArgs = Union[Tuple[Union[bytes, Text], ...], List[bytes], List[Text], List[Union[bytes, Text]]] +_ExecVArgs = Union[tuple[Union[bytes, Text], ...], list[bytes], list[Text], list[Union[bytes, Text]]] def execv(path: Text, args: _ExecVArgs) -> NoReturn: ... def execve(path: Text, args: _ExecVArgs, env: Mapping[str, str]) -> NoReturn: ... @@ -283,22 +280,22 @@ def kill(pid: int, sig: int) -> None: ... if sys.platform != "win32": # Unix only def fork() -> int: ... - def forkpty() -> Tuple[int, int]: ... # some flavors of Unix + def forkpty() -> tuple[int, int]: ... # some flavors of Unix def killpg(__pgid: int, __signal: int) -> None: ... def nice(increment: int) -> int: ... def plock(op: int) -> None: ... # ???op is int? def popen(command: str, *args, **kwargs) -> IO[Any]: ... -def popen2(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ... -def popen3(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any], IO[Any]]: ... -def popen4(cmd: str, *args, **kwargs) -> Tuple[IO[Any], IO[Any]]: ... +def popen2(cmd: str, *args, **kwargs) -> tuple[IO[Any], IO[Any]]: ... +def popen3(cmd: str, *args, **kwargs) -> tuple[IO[Any], IO[Any], IO[Any]]: ... +def popen4(cmd: str, *args, **kwargs) -> tuple[IO[Any], IO[Any]]: ... def spawnl(mode: int, path: Text, arg0: bytes | Text, *args: bytes | Text) -> int: ... def spawnle(mode: int, path: Text, arg0: bytes | Text, *args: Any) -> int: ... # Imprecise sig -def spawnv(mode: int, path: Text, args: List[bytes | Text]) -> int: ... -def spawnve(mode: int, path: Text, args: List[bytes | Text], env: Mapping[str, str]) -> int: ... +def spawnv(mode: int, path: Text, args: list[bytes | Text]) -> int: ... +def spawnve(mode: int, path: Text, args: list[bytes | Text], env: Mapping[str, str]) -> int: ... def system(command: Text) -> int: ... -def times() -> Tuple[float, float, float, float, float]: ... -def waitpid(pid: int, options: int) -> Tuple[int, int]: ... +def times() -> tuple[float, float, float, float, float]: ... +def waitpid(pid: int, options: int) -> tuple[int, int]: ... def urandom(n: int) -> bytes: ... if sys.platform == "win32": @@ -308,11 +305,11 @@ else: # Unix only def spawnlp(mode: int, file: Text, arg0: bytes | Text, *args: bytes | Text) -> int: ... def spawnlpe(mode: int, file: Text, arg0: bytes | Text, *args: Any) -> int: ... # Imprecise signature - def spawnvp(mode: int, file: Text, args: List[bytes | Text]) -> int: ... - def spawnvpe(mode: int, file: Text, args: List[bytes | Text], env: Mapping[str, str]) -> int: ... - def wait() -> Tuple[int, int]: ... - def wait3(options: int) -> Tuple[int, int, Any]: ... - def wait4(pid: int, options: int) -> Tuple[int, int, Any]: ... + def spawnvp(mode: int, file: Text, args: list[bytes | Text]) -> int: ... + def spawnvpe(mode: int, file: Text, args: list[bytes | Text], env: Mapping[str, str]) -> int: ... + def wait() -> tuple[int, int]: ... + def wait3(options: int) -> tuple[int, int, Any]: ... + def wait4(pid: int, options: int) -> tuple[int, int, Any]: ... def WCOREDUMP(status: int) -> bool: ... def WIFCONTINUED(status: int) -> bool: ... def WIFSTOPPED(status: int) -> bool: ... @@ -322,7 +319,7 @@ else: def WSTOPSIG(status: int) -> int: ... def WTERMSIG(status: int) -> int: ... def confstr(name: str | int) -> str | None: ... - def getloadavg() -> Tuple[float, float, float]: ... + def getloadavg() -> tuple[float, float, float]: ... def sysconf(name: str | int) -> int: ... def tmpfile() -> IO[Any]: ... diff --git a/mypy/typeshed/stdlib/@python2/os/path.pyi b/mypy/typeshed/stdlib/@python2/os/path.pyi index 2ce2f592f0e2..4e484ce8a096 100644 --- a/mypy/typeshed/stdlib/@python2/os/path.pyi +++ b/mypy/typeshed/stdlib/@python2/os/path.pyi @@ -1,6 +1,6 @@ import os import sys -from typing import Any, AnyStr, Callable, List, Sequence, Text, Tuple, TypeVar, overload +from typing import Any, AnyStr, Callable, Sequence, Text, TypeVar, overload _T = TypeVar("_T") @@ -74,11 +74,11 @@ def relpath(path: Text, start: Text | None = ...) -> Text: ... def samefile(f1: Text, f2: Text) -> bool: ... def sameopenfile(fp1: int, fp2: int) -> bool: ... def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... -def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def split(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... +def splitdrive(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... +def splitext(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... if sys.platform == "win32": - def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + def splitunc(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... # deprecated -def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... +def walk(path: AnyStr, visit: Callable[[_T, AnyStr, list[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/os2emxpath.pyi b/mypy/typeshed/stdlib/@python2/os2emxpath.pyi index 514db760886f..33732903cb4c 100644 --- a/mypy/typeshed/stdlib/@python2/os2emxpath.pyi +++ b/mypy/typeshed/stdlib/@python2/os2emxpath.pyi @@ -1,7 +1,7 @@ import os import sys from genericpath import exists as exists -from typing import Any, AnyStr, Callable, List, Sequence, Text, Tuple, TypeVar, overload +from typing import Any, AnyStr, Callable, Sequence, Text, TypeVar, overload _T = TypeVar("_T") @@ -74,11 +74,11 @@ def relpath(path: Text, start: Text | None = ...) -> Text: ... def samefile(f1: Text, f2: Text) -> bool: ... def sameopenfile(fp1: int, fp2: int) -> bool: ... def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... -def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def split(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... +def splitdrive(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... +def splitext(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... if sys.platform == "win32": - def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + def splitunc(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... # deprecated -def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... +def walk(path: AnyStr, visit: Callable[[_T, AnyStr, list[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/ossaudiodev.pyi b/mypy/typeshed/stdlib/@python2/ossaudiodev.pyi index af3e2c210930..f221c95b8036 100644 --- a/mypy/typeshed/stdlib/@python2/ossaudiodev.pyi +++ b/mypy/typeshed/stdlib/@python2/ossaudiodev.pyi @@ -1,4 +1,4 @@ -from typing import Any, List, overload +from typing import Any, overload from typing_extensions import Literal AFMT_AC3: int @@ -114,8 +114,8 @@ SOUND_MIXER_TREBLE: int SOUND_MIXER_VIDEO: int SOUND_MIXER_VOLUME: int -control_labels: List[str] -control_names: List[str] +control_labels: list[str] +control_names: list[str] # TODO: oss_audio_device return type @overload diff --git a/mypy/typeshed/stdlib/@python2/parser.pyi b/mypy/typeshed/stdlib/@python2/parser.pyi index ff8bf039ee80..73ebff4c4fe7 100644 --- a/mypy/typeshed/stdlib/@python2/parser.pyi +++ b/mypy/typeshed/stdlib/@python2/parser.pyi @@ -1,12 +1,12 @@ from types import CodeType -from typing import Any, List, Sequence, Text, Tuple +from typing import Any, Sequence, Text def expr(source: Text) -> STType: ... def suite(source: Text) -> STType: ... def sequence2st(sequence: Sequence[Any]) -> STType: ... def tuple2st(sequence: Sequence[Any]) -> STType: ... -def st2list(st: STType, line_info: bool = ..., col_info: bool = ...) -> List[Any]: ... -def st2tuple(st: STType, line_info: bool = ..., col_info: bool = ...) -> Tuple[Any]: ... +def st2list(st: STType, line_info: bool = ..., col_info: bool = ...) -> list[Any]: ... +def st2tuple(st: STType, line_info: bool = ..., col_info: bool = ...) -> tuple[Any]: ... def compilest(st: STType, filename: Text = ...) -> CodeType: ... def isexpr(st: STType) -> bool: ... def issuite(st: STType) -> bool: ... @@ -17,5 +17,5 @@ class STType: def compile(self, filename: Text = ...) -> CodeType: ... def isexpr(self) -> bool: ... def issuite(self) -> bool: ... - def tolist(self, line_info: bool = ..., col_info: bool = ...) -> List[Any]: ... - def totuple(self, line_info: bool = ..., col_info: bool = ...) -> Tuple[Any]: ... + def tolist(self, line_info: bool = ..., col_info: bool = ...) -> list[Any]: ... + def totuple(self, line_info: bool = ..., col_info: bool = ...) -> tuple[Any]: ... diff --git a/mypy/typeshed/stdlib/@python2/pdb.pyi b/mypy/typeshed/stdlib/@python2/pdb.pyi index 6d3a6d5c5903..78d0c163ca72 100644 --- a/mypy/typeshed/stdlib/@python2/pdb.pyi +++ b/mypy/typeshed/stdlib/@python2/pdb.pyi @@ -1,7 +1,7 @@ from bdb import Bdb from cmd import Cmd from types import FrameType, TracebackType -from typing import IO, Any, Callable, ClassVar, Dict, Iterable, List, Mapping, Tuple, TypeVar +from typing import IO, Any, Callable, ClassVar, Iterable, Mapping, TypeVar _T = TypeVar("_T") @@ -9,9 +9,9 @@ line_prefix: str # undocumented class Restart(Exception): ... -def run(statement: str, globals: Dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... -def runeval(expression: str, globals: Dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> Any: ... -def runctx(statement: str, globals: Dict[str, Any], locals: Mapping[str, Any]) -> None: ... +def run(statement: str, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> None: ... +def runeval(expression: str, globals: dict[str, Any] | None = ..., locals: Mapping[str, Any] | None = ...) -> Any: ... +def runctx(statement: str, globals: dict[str, Any], locals: Mapping[str, Any]) -> None: ... def runcall(func: Callable[..., _T], *args: Any, **kwds: Any) -> _T | None: ... def set_trace() -> None: ... def post_mortem(t: TracebackType | None = ...) -> None: ... @@ -20,19 +20,19 @@ def pm() -> None: ... class Pdb(Bdb, Cmd): # Everything here is undocumented, except for __init__ - commands_resuming: ClassVar[List[str]] + commands_resuming: ClassVar[list[str]] - aliases: Dict[str, str] + aliases: dict[str, str] mainpyfile: str _wait_for_mainpyfile: bool - rcLines: List[str] - commands: Dict[int, List[str]] - commands_doprompt: Dict[int, bool] - commands_silent: Dict[int, bool] + rcLines: list[str] + commands: dict[int, list[str]] + commands_doprompt: dict[int, bool] + commands_silent: dict[int, bool] commands_defining: bool commands_bnum: int | None lineno: int | None - stack: List[Tuple[FrameType, int]] + stack: list[tuple[FrameType, int]] curindex: int curframe: FrameType | None curframe_locals: Mapping[str, Any] @@ -47,11 +47,11 @@ class Pdb(Bdb, Cmd): def displayhook(self, obj: object) -> None: ... def handle_command_def(self, line: str) -> bool: ... def defaultFile(self) -> str: ... - def lineinfo(self, identifier: str) -> Tuple[None, None, None] | Tuple[str, str, int]: ... + def lineinfo(self, identifier: str) -> tuple[None, None, None] | tuple[str, str, int]: ... def checkline(self, filename: str, lineno: int) -> int: ... def _getval(self, arg: str) -> object: ... def print_stack_trace(self) -> None: ... - def print_stack_entry(self, frame_lineno: Tuple[FrameType, int], prompt_prefix: str = ...) -> None: ... + def print_stack_entry(self, frame_lineno: tuple[FrameType, int], prompt_prefix: str = ...) -> None: ... def lookupmodule(self, filename: str) -> str | None: ... def _runscript(self, filename: str) -> None: ... def do_commands(self, arg: str) -> bool | None: ... @@ -157,7 +157,7 @@ class Pdb(Bdb, Cmd): # undocumented -def find_function(funcname: str, filename: str) -> Tuple[str, str, int] | None: ... +def find_function(funcname: str, filename: str) -> tuple[str, str, int] | None: ... def main() -> None: ... def help() -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pickle.pyi b/mypy/typeshed/stdlib/@python2/pickle.pyi index 07e32e64b449..bb9b6614f329 100644 --- a/mypy/typeshed/stdlib/@python2/pickle.pyi +++ b/mypy/typeshed/stdlib/@python2/pickle.pyi @@ -1,7 +1,7 @@ -from typing import IO, Any, Callable, Iterator, Optional, Tuple, Type, Union +from typing import IO, Any, Callable, Iterator, Optional, Union HIGHEST_PROTOCOL: int -bytes_types: Tuple[Type[Any], ...] # undocumented +bytes_types: tuple[type[Any], ...] # undocumented def dump(obj: Any, file: IO[bytes], protocol: int | None = ...) -> None: ... def dumps(obj: Any, protocol: int | None = ...) -> bytes: ... @@ -14,10 +14,10 @@ class UnpicklingError(PickleError): ... _reducedtype = Union[ str, - Tuple[Callable[..., Any], Tuple[Any, ...]], - Tuple[Callable[..., Any], Tuple[Any, ...], Any], - Tuple[Callable[..., Any], Tuple[Any, ...], Any, Optional[Iterator[Any]]], - Tuple[Callable[..., Any], Tuple[Any, ...], Any, Optional[Iterator[Any]], Optional[Iterator[Any]]], + tuple[Callable[..., Any], tuple[Any, ...]], + tuple[Callable[..., Any], tuple[Any, ...], Any], + tuple[Callable[..., Any], tuple[Any, ...], Any, Optional[Iterator[Any]]], + tuple[Callable[..., Any], tuple[Any, ...], Any, Optional[Iterator[Any]], Optional[Iterator[Any]]], ] class Pickler: diff --git a/mypy/typeshed/stdlib/@python2/pickletools.pyi b/mypy/typeshed/stdlib/@python2/pickletools.pyi index 14ec0fdff03a..915b700dc8e5 100644 --- a/mypy/typeshed/stdlib/@python2/pickletools.pyi +++ b/mypy/typeshed/stdlib/@python2/pickletools.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Callable, Iterator, List, MutableMapping, Text, Tuple, Type +from typing import IO, Any, Callable, Iterator, MutableMapping, Text _Reader = Callable[[IO[bytes]], Any] @@ -77,9 +77,9 @@ long4: ArgumentDescriptor class StackObject(object): name: str - obtype: Type[Any] | Tuple[Type[Any], ...] + obtype: type[Any] | tuple[type[Any], ...] doc: str - def __init__(self, name: str, obtype: Type[Any] | Tuple[Type[Any], ...], doc: str) -> None: ... + def __init__(self, name: str, obtype: type[Any] | tuple[type[Any], ...], doc: str) -> None: ... pyint: StackObject pylong: StackObject @@ -100,8 +100,8 @@ class OpcodeInfo(object): name: str code: str arg: ArgumentDescriptor | None - stack_before: List[StackObject] - stack_after: List[StackObject] + stack_before: list[StackObject] + stack_after: list[StackObject] proto: int doc: str def __init__( @@ -109,15 +109,15 @@ class OpcodeInfo(object): name: str, code: str, arg: ArgumentDescriptor | None, - stack_before: List[StackObject], - stack_after: List[StackObject], + stack_before: list[StackObject], + stack_after: list[StackObject], proto: int, doc: str, ) -> None: ... -opcodes: List[OpcodeInfo] +opcodes: list[OpcodeInfo] -def genops(pickle: bytes | IO[bytes]) -> Iterator[Tuple[OpcodeInfo, Any | None, int | None]]: ... +def genops(pickle: bytes | IO[bytes]) -> Iterator[tuple[OpcodeInfo, Any | None, int | None]]: ... def optimize(p: bytes | IO[bytes]) -> bytes: ... def dis( pickle: bytes | IO[bytes], out: IO[str] | None = ..., memo: MutableMapping[int, Any] | None = ..., indentlevel: int = ... diff --git a/mypy/typeshed/stdlib/@python2/pkgutil.pyi b/mypy/typeshed/stdlib/@python2/pkgutil.pyi index fd42af916cfe..3b006b376641 100644 --- a/mypy/typeshed/stdlib/@python2/pkgutil.pyi +++ b/mypy/typeshed/stdlib/@python2/pkgutil.pyi @@ -1,19 +1,19 @@ from _typeshed import SupportsRead -from typing import IO, Any, Callable, Iterable, Iterator, List, Tuple, Union +from typing import IO, Any, Callable, Iterable, Iterator, Union Loader = Any MetaPathFinder = Any PathEntryFinder = Any -_ModuleInfoLike = Tuple[Union[MetaPathFinder, PathEntryFinder], str, bool] +_ModuleInfoLike = tuple[Union[MetaPathFinder, PathEntryFinder], str, bool] -def extend_path(path: List[str], name: str) -> List[str]: ... +def extend_path(path: list[str], name: str) -> list[str]: ... class ImpImporter: def __init__(self, path: str | None = ...) -> None: ... class ImpLoader: - def __init__(self, fullname: str, file: IO[str], filename: str, etc: Tuple[str, str, int]) -> None: ... + def __init__(self, fullname: str, file: IO[str], filename: str, etc: tuple[str, str, int]) -> None: ... def find_loader(fullname: str) -> Loader | None: ... def get_importer(path_item: str) -> PathEntryFinder | None: ... diff --git a/mypy/typeshed/stdlib/@python2/platform.pyi b/mypy/typeshed/stdlib/@python2/platform.pyi index b984a2b2d3d5..7d71ee943da1 100644 --- a/mypy/typeshed/stdlib/@python2/platform.pyi +++ b/mypy/typeshed/stdlib/@python2/platform.pyi @@ -1,4 +1,4 @@ -from typing import Any, Tuple +from typing import Any __copyright__: Any DEV_NULL: Any @@ -19,16 +19,16 @@ class _popen: __del__: Any def popen(cmd, mode=..., bufsize: Any | None = ...): ... -def win32_ver(release: str = ..., version: str = ..., csd: str = ..., ptype: str = ...) -> Tuple[str, str, str, str]: ... +def win32_ver(release: str = ..., version: str = ..., csd: str = ..., ptype: str = ...) -> tuple[str, str, str, str]: ... def mac_ver( - release: str = ..., versioninfo: Tuple[str, str, str] = ..., machine: str = ... -) -> Tuple[str, Tuple[str, str, str], str]: ... + release: str = ..., versioninfo: tuple[str, str, str] = ..., machine: str = ... +) -> tuple[str, tuple[str, str, str], str]: ... def java_ver( - release: str = ..., vendor: str = ..., vminfo: Tuple[str, str, str] = ..., osinfo: Tuple[str, str, str] = ... -) -> Tuple[str, str, Tuple[str, str, str], Tuple[str, str, str]]: ... + release: str = ..., vendor: str = ..., vminfo: tuple[str, str, str] = ..., osinfo: tuple[str, str, str] = ... +) -> tuple[str, str, tuple[str, str, str], tuple[str, str, str]]: ... def system_alias(system, release, version): ... -def architecture(executable=..., bits=..., linkage=...) -> Tuple[str, str]: ... -def uname() -> Tuple[str, str, str, str, str, str]: ... +def architecture(executable=..., bits=..., linkage=...) -> tuple[str, str]: ... +def uname() -> tuple[str, str, str, str, str, str]: ... def system() -> str: ... def node() -> str: ... def release() -> str: ... @@ -37,9 +37,9 @@ def machine() -> str: ... def processor() -> str: ... def python_implementation() -> str: ... def python_version() -> str: ... -def python_version_tuple() -> Tuple[str, str, str]: ... +def python_version_tuple() -> tuple[str, str, str]: ... def python_branch() -> str: ... def python_revision() -> str: ... -def python_build() -> Tuple[str, str]: ... +def python_build() -> tuple[str, str]: ... def python_compiler() -> str: ... def platform(aliased: int = ..., terse: int = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/plistlib.pyi b/mypy/typeshed/stdlib/@python2/plistlib.pyi index d815e3c35404..02a1cb506d1d 100644 --- a/mypy/typeshed/stdlib/@python2/plistlib.pyi +++ b/mypy/typeshed/stdlib/@python2/plistlib.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Dict as DictT, Mapping, Text, Union +from typing import IO, Any, Mapping, Text, Union _Path = Union[str, Text] @@ -11,7 +11,7 @@ def writePlistToResource(rootObject: Mapping[str, Any], path: _Path, restype: st def readPlistFromString(data: str) -> Any: ... def writePlistToString(rootObject: Mapping[str, Any]) -> str: ... -class Dict(DictT[str, Any]): +class Dict(dict[str, Any]): def __getattr__(self, attr: str) -> Any: ... def __setattr__(self, attr: str, value: Any) -> None: ... def __delattr__(self, attr: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/popen2.pyi b/mypy/typeshed/stdlib/@python2/popen2.pyi index 0efee4e6d271..43f6804e0659 100644 --- a/mypy/typeshed/stdlib/@python2/popen2.pyi +++ b/mypy/typeshed/stdlib/@python2/popen2.pyi @@ -1,4 +1,4 @@ -from typing import Any, Iterable, TextIO, Tuple, TypeVar +from typing import Any, Iterable, TextIO, TypeVar _T = TypeVar("_T") @@ -22,6 +22,6 @@ class Popen4(Popen3): fromchild: TextIO def __init__(self, cmd: Iterable[Any] = ..., bufsize: int = ...) -> None: ... -def popen2(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ... -def popen3(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO, TextIO]: ... -def popen4(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> Tuple[TextIO, TextIO]: ... +def popen2(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> tuple[TextIO, TextIO]: ... +def popen3(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> tuple[TextIO, TextIO, TextIO]: ... +def popen4(cmd: Iterable[Any] = ..., bufsize: int = ..., mode: str = ...) -> tuple[TextIO, TextIO]: ... diff --git a/mypy/typeshed/stdlib/@python2/poplib.pyi b/mypy/typeshed/stdlib/@python2/poplib.pyi index 7a71f9850dfe..4525cac1e687 100644 --- a/mypy/typeshed/stdlib/@python2/poplib.pyi +++ b/mypy/typeshed/stdlib/@python2/poplib.pyi @@ -1,7 +1,7 @@ import socket -from typing import Any, BinaryIO, List, Pattern, Text, Tuple, overload +from typing import Any, BinaryIO, Pattern, Text, overload -_LongResp = Tuple[bytes, List[bytes], int] +_LongResp = tuple[bytes, list[bytes], int] class error_proto(Exception): ... @@ -22,7 +22,7 @@ class POP3: def set_debuglevel(self, level: int) -> None: ... def user(self, user: Text) -> bytes: ... def pass_(self, pswd: Text) -> bytes: ... - def stat(self) -> Tuple[int, int]: ... + def stat(self) -> tuple[int, int]: ... def list(self, which: Any | None = ...) -> _LongResp: ... def retr(self, which: Any) -> _LongResp: ... def dele(self, which: Any) -> bytes: ... diff --git a/mypy/typeshed/stdlib/@python2/posix.pyi b/mypy/typeshed/stdlib/@python2/posix.pyi index c39ce325289b..7ea9c0015ab0 100644 --- a/mypy/typeshed/stdlib/@python2/posix.pyi +++ b/mypy/typeshed/stdlib/@python2/posix.pyi @@ -1,12 +1,12 @@ from _typeshed import FileDescriptorLike -from typing import IO, AnyStr, Dict, List, Mapping, NamedTuple, Sequence, Tuple, TypeVar +from typing import IO, AnyStr, Mapping, NamedTuple, Sequence, TypeVar error = OSError -confstr_names: Dict[str, int] -environ: Dict[str, str] -pathconf_names: Dict[str, int] -sysconf_names: Dict[str, int] +confstr_names: dict[str, int] +environ: dict[str, str] +pathconf_names: dict[str, int] +sysconf_names: dict[str, int] _T = TypeVar("_T") @@ -112,7 +112,7 @@ def fchown(fd: int, uid: int, gid: int) -> None: ... def fdatasync(fd: FileDescriptorLike) -> None: ... def fdopen(fd: int, mode: str = ..., bufsize: int = ...) -> IO[str]: ... def fork() -> int: ... -def forkpty() -> Tuple[int, int]: ... +def forkpty() -> tuple[int, int]: ... def fpathconf(fd: int, name: str) -> None: ... def fstat(fd: int) -> stat_result: ... def fstatvfs(fd: int) -> statvfs_result: ... @@ -123,15 +123,15 @@ def getcwdu() -> unicode: ... def getegid() -> int: ... def geteuid() -> int: ... def getgid() -> int: ... -def getgroups() -> List[int]: ... -def getloadavg() -> Tuple[float, float, float]: ... +def getgroups() -> list[int]: ... +def getloadavg() -> tuple[float, float, float]: ... def getlogin() -> str: ... def getpgid(pid: int) -> int: ... def getpgrp() -> int: ... def getpid() -> int: ... def getppid() -> int: ... -def getresgid() -> Tuple[int, int, int]: ... -def getresuid() -> Tuple[int, int, int]: ... +def getresgid() -> tuple[int, int, int]: ... +def getresuid() -> tuple[int, int, int]: ... def getsid(pid: int) -> int: ... def getuid() -> int: ... def initgroups(username: str, gid: int) -> None: ... @@ -140,7 +140,7 @@ def kill(pid: int, sig: int) -> None: ... def killpg(pgid: int, sig: int) -> None: ... def lchown(path: unicode, uid: int, gid: int) -> None: ... def link(source: unicode, link_name: str) -> None: ... -def listdir(path: AnyStr) -> List[AnyStr]: ... +def listdir(path: AnyStr) -> list[AnyStr]: ... def lseek(fd: int, pos: int, how: int) -> None: ... def lstat(path: unicode) -> stat_result: ... def major(device: int) -> int: ... @@ -151,9 +151,9 @@ def mkfifo(path: unicode, mode: int = ...) -> None: ... def mknod(filename: unicode, mode: int = ..., device: int = ...) -> None: ... def nice(increment: int) -> int: ... def open(file: unicode, flags: int, mode: int = ...) -> int: ... -def openpty() -> Tuple[int, int]: ... +def openpty() -> tuple[int, int]: ... def pathconf(path: unicode, name: str) -> str: ... -def pipe() -> Tuple[int, int]: ... +def pipe() -> tuple[int, int]: ... def popen(command: str, mode: str = ..., bufsize: int = ...) -> IO[str]: ... def putenv(varname: str, value: str) -> None: ... def read(fd: int, n: int) -> str: ... @@ -182,20 +182,20 @@ def sysconf(name: str | int) -> int: ... def system(command: unicode) -> int: ... def tcgetpgrp(fd: int) -> int: ... def tcsetpgrp(fd: int, pg: int) -> None: ... -def times() -> Tuple[float, float, float, float, float]: ... +def times() -> tuple[float, float, float, float, float]: ... def tmpfile() -> IO[str]: ... def ttyname(fd: int) -> str: ... def umask(mask: int) -> int: ... -def uname() -> Tuple[str, str, str, str, str]: ... +def uname() -> tuple[str, str, str, str, str]: ... def unlink(path: unicode) -> None: ... def unsetenv(varname: str) -> None: ... def urandom(n: int) -> str: ... -def utime(path: unicode, times: Tuple[int, int] | None) -> None: ... +def utime(path: unicode, times: tuple[int, int] | None) -> None: ... def wait() -> int: ... -_r = Tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] +_r = tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] -def wait3(options: int) -> Tuple[int, int, _r]: ... -def wait4(pid: int, options: int) -> Tuple[int, int, _r]: ... +def wait3(options: int) -> tuple[int, int, _r]: ... +def wait4(pid: int, options: int) -> tuple[int, int, _r]: ... def waitpid(pid: int, options: int) -> int: ... def write(fd: int, str: str) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/posixpath.pyi b/mypy/typeshed/stdlib/@python2/posixpath.pyi index 514db760886f..33732903cb4c 100644 --- a/mypy/typeshed/stdlib/@python2/posixpath.pyi +++ b/mypy/typeshed/stdlib/@python2/posixpath.pyi @@ -1,7 +1,7 @@ import os import sys from genericpath import exists as exists -from typing import Any, AnyStr, Callable, List, Sequence, Text, Tuple, TypeVar, overload +from typing import Any, AnyStr, Callable, Sequence, Text, TypeVar, overload _T = TypeVar("_T") @@ -74,11 +74,11 @@ def relpath(path: Text, start: Text | None = ...) -> Text: ... def samefile(f1: Text, f2: Text) -> bool: ... def sameopenfile(fp1: int, fp2: int) -> bool: ... def samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ... -def split(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitdrive(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... -def splitext(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def split(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... +def splitdrive(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... +def splitext(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... if sys.platform == "win32": - def splitunc(p: AnyStr) -> Tuple[AnyStr, AnyStr]: ... # deprecated + def splitunc(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... # deprecated -def walk(path: AnyStr, visit: Callable[[_T, AnyStr, List[AnyStr]], Any], arg: _T) -> None: ... +def walk(path: AnyStr, visit: Callable[[_T, AnyStr, list[AnyStr]], Any], arg: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pprint.pyi b/mypy/typeshed/stdlib/@python2/pprint.pyi index 407a9afb8e47..e22c4464eb4d 100644 --- a/mypy/typeshed/stdlib/@python2/pprint.pyi +++ b/mypy/typeshed/stdlib/@python2/pprint.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Dict, Tuple +from typing import IO, Any def pformat(object: object, indent: int = ..., width: int = ..., depth: int | None = ...) -> str: ... def pprint( @@ -14,4 +14,4 @@ class PrettyPrinter: def pprint(self, object: object) -> None: ... def isreadable(self, object: object) -> bool: ... def isrecursive(self, object: object) -> bool: ... - def format(self, object: object, context: Dict[int, Any], maxlevels: int, level: int) -> Tuple[str, bool, bool]: ... + def format(self, object: object, context: dict[int, Any], maxlevels: int, level: int) -> tuple[str, bool, bool]: ... diff --git a/mypy/typeshed/stdlib/@python2/profile.pyi b/mypy/typeshed/stdlib/@python2/profile.pyi index 08e9b906dd0d..640cb930ddfa 100644 --- a/mypy/typeshed/stdlib/@python2/profile.pyi +++ b/mypy/typeshed/stdlib/@python2/profile.pyi @@ -1,13 +1,13 @@ -from typing import Any, Callable, Dict, Text, Tuple, TypeVar +from _typeshed import Self +from typing import Any, Callable, Text, TypeVar def run(statement: str, filename: str | None = ..., sort: str | int = ...) -> None: ... def runctx( - statement: str, globals: Dict[str, Any], locals: Dict[str, Any], filename: str | None = ..., sort: str | int = ... + statement: str, globals: dict[str, Any], locals: dict[str, Any], filename: str | None = ..., sort: str | int = ... ) -> None: ... -_SelfT = TypeVar("_SelfT", bound=Profile) _T = TypeVar("_T") -_Label = Tuple[str, int, str] +_Label = tuple[str, int, str] class Profile: bias: int @@ -20,7 +20,7 @@ class Profile: def dump_stats(self, file: Text) -> None: ... def create_stats(self) -> None: ... def snapshot_stats(self) -> None: ... - def run(self: _SelfT, cmd: str) -> _SelfT: ... - def runctx(self: _SelfT, cmd: str, globals: Dict[str, Any], locals: Dict[str, Any]) -> _SelfT: ... + def run(self: Self, cmd: str) -> Self: ... + def runctx(self: Self, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> Self: ... def runcall(self, __func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... def calibrate(self, m: int, verbose: int = ...) -> float: ... diff --git a/mypy/typeshed/stdlib/@python2/pstats.pyi b/mypy/typeshed/stdlib/@python2/pstats.pyi index cecd1e84e305..e2cf6e437826 100644 --- a/mypy/typeshed/stdlib/@python2/pstats.pyi +++ b/mypy/typeshed/stdlib/@python2/pstats.pyi @@ -1,12 +1,13 @@ +from _typeshed import Self from cProfile import Profile as _cProfile from profile import Profile -from typing import IO, Any, Dict, Iterable, List, Text, Tuple, TypeVar, Union, overload +from typing import IO, Any, Iterable, Text, TypeVar, Union, overload _Selector = Union[str, float, int] _T = TypeVar("_T", bound=Stats) class Stats: - sort_arg_dict_default: Dict[str, Tuple[Any, str]] + sort_arg_dict_default: dict[str, tuple[Any, str]] def __init__( self: _T, __arg: None | str | Text | Profile | _cProfile = ..., @@ -16,22 +17,22 @@ class Stats: def init(self, arg: None | str | Text | Profile | _cProfile) -> None: ... def load_stats(self, arg: None | str | Text | Profile | _cProfile) -> None: ... def get_top_level_stats(self) -> None: ... - def add(self: _T, *arg_list: None | str | Text | Profile | _cProfile | _T) -> _T: ... + def add(self: Self, *arg_list: None | str | Text | Profile | _cProfile | Self) -> Self: ... def dump_stats(self, filename: Text) -> None: ... - def get_sort_arg_defs(self) -> Dict[str, Tuple[Tuple[Tuple[int, int], ...], str]]: ... + def get_sort_arg_defs(self) -> dict[str, tuple[tuple[tuple[int, int], ...], str]]: ... @overload - def sort_stats(self: _T, field: int) -> _T: ... + def sort_stats(self: Self, field: int) -> Self: ... @overload - def sort_stats(self: _T, *field: str) -> _T: ... - def reverse_order(self: _T) -> _T: ... - def strip_dirs(self: _T) -> _T: ... + def sort_stats(self: Self, *field: str) -> Self: ... + def reverse_order(self: Self) -> Self: ... + def strip_dirs(self: Self) -> Self: ... def calc_callees(self) -> None: ... - def eval_print_amount(self, sel: _Selector, list: List[str], msg: str) -> Tuple[List[str], str]: ... - def get_print_list(self, sel_list: Iterable[_Selector]) -> Tuple[int, List[str]]: ... - def print_stats(self: _T, *amount: _Selector) -> _T: ... - def print_callees(self: _T, *amount: _Selector) -> _T: ... - def print_callers(self: _T, *amount: _Selector) -> _T: ... + def eval_print_amount(self, sel: _Selector, list: list[str], msg: str) -> tuple[list[str], str]: ... + def get_print_list(self, sel_list: Iterable[_Selector]) -> tuple[int, list[str]]: ... + def print_stats(self: Self, *amount: _Selector) -> Self: ... + def print_callees(self: Self, *amount: _Selector) -> Self: ... + def print_callers(self: Self, *amount: _Selector) -> Self: ... def print_call_heading(self, name_size: int, column_title: str) -> None: ... - def print_call_line(self, name_size: int, source: str, call_dict: Dict[str, Any], arrow: str = ...) -> None: ... + def print_call_line(self, name_size: int, source: str, call_dict: dict[str, Any], arrow: str = ...) -> None: ... def print_title(self) -> None: ... def print_line(self, func: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pty.pyi b/mypy/typeshed/stdlib/@python2/pty.pyi index e8afa2df5166..2c90faf18aa3 100644 --- a/mypy/typeshed/stdlib/@python2/pty.pyi +++ b/mypy/typeshed/stdlib/@python2/pty.pyi @@ -1,15 +1,16 @@ -from typing import Callable, Iterable, Tuple +import sys +from typing import Callable, Iterable -_Reader = Callable[[int], bytes] +if sys.platform != "win32": + _Reader = Callable[[int], bytes] -STDIN_FILENO: int -STDOUT_FILENO: int -STDERR_FILENO: int + STDIN_FILENO: int + STDOUT_FILENO: int + STDERR_FILENO: int -CHILD: int - -def openpty() -> Tuple[int, int]: ... -def master_open() -> Tuple[int, str]: ... -def slave_open(tty_name: str) -> int: ... -def fork() -> Tuple[int, int]: ... -def spawn(argv: str | Iterable[str], master_read: _Reader = ..., stdin_read: _Reader = ...) -> None: ... + CHILD: int + def openpty() -> tuple[int, int]: ... + def master_open() -> tuple[int, str]: ... + def slave_open(tty_name: str) -> int: ... + def fork() -> tuple[int, int]: ... + def spawn(argv: str | Iterable[str], master_read: _Reader = ..., stdin_read: _Reader = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pwd.pyi b/mypy/typeshed/stdlib/@python2/pwd.pyi index 83020c1576dd..e64cbf6a1ac3 100644 --- a/mypy/typeshed/stdlib/@python2/pwd.pyi +++ b/mypy/typeshed/stdlib/@python2/pwd.pyi @@ -1,14 +1,14 @@ -from typing import List, Tuple +import sys -class struct_passwd(Tuple[str, str, int, int, str, str, str]): - pw_name: str - pw_passwd: str - pw_uid: int - pw_gid: int - pw_gecos: str - pw_dir: str - pw_shell: str - -def getpwall() -> List[struct_passwd]: ... -def getpwuid(__uid: int) -> struct_passwd: ... -def getpwnam(__name: str) -> struct_passwd: ... +if sys.platform != "win32": + class struct_passwd(tuple[str, str, int, int, str, str, str]): + pw_name: str + pw_passwd: str + pw_uid: int + pw_gid: int + pw_gecos: str + pw_dir: str + pw_shell: str + def getpwall() -> list[struct_passwd]: ... + def getpwuid(__uid: int) -> struct_passwd: ... + def getpwnam(__name: str) -> struct_passwd: ... diff --git a/mypy/typeshed/stdlib/@python2/py_compile.pyi b/mypy/typeshed/stdlib/@python2/py_compile.pyi index 44905b43da33..3c26f451116e 100644 --- a/mypy/typeshed/stdlib/@python2/py_compile.pyi +++ b/mypy/typeshed/stdlib/@python2/py_compile.pyi @@ -1,4 +1,4 @@ -from typing import List, Text, Type, Union +from typing import Text, Union _EitherStr = Union[bytes, Text] @@ -7,7 +7,7 @@ class PyCompileError(Exception): exc_value: BaseException file: str msg: str - def __init__(self, exc_type: Type[BaseException], exc_value: BaseException, file: str, msg: str = ...) -> None: ... + def __init__(self, exc_type: type[BaseException], exc_value: BaseException, file: str, msg: str = ...) -> None: ... def compile(file: _EitherStr, cfile: _EitherStr | None = ..., dfile: _EitherStr | None = ..., doraise: bool = ...) -> None: ... -def main(args: List[Text] | None = ...) -> int: ... +def main(args: list[Text] | None = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/pyclbr.pyi b/mypy/typeshed/stdlib/@python2/pyclbr.pyi index 893079901665..317e934694c5 100644 --- a/mypy/typeshed/stdlib/@python2/pyclbr.pyi +++ b/mypy/typeshed/stdlib/@python2/pyclbr.pyi @@ -1,13 +1,13 @@ -from typing import Dict, List, Sequence +from typing import Sequence class Class: module: str name: str - super: List[Class | str] | None - methods: Dict[str, int] + super: list[Class | str] | None + methods: dict[str, int] file: int lineno: int - def __init__(self, module: str, name: str, super: List[Class | str] | None, file: str, lineno: int) -> None: ... + def __init__(self, module: str, name: str, super: list[Class | str] | None, file: str, lineno: int) -> None: ... class Function: module: str @@ -16,5 +16,5 @@ class Function: lineno: int def __init__(self, module: str, name: str, file: str, lineno: int) -> None: ... -def readmodule(module: str, path: Sequence[str] | None = ...) -> Dict[str, Class]: ... -def readmodule_ex(module: str, path: Sequence[str] | None = ...) -> Dict[str, Class | Function | List[str]]: ... +def readmodule(module: str, path: Sequence[str] | None = ...) -> dict[str, Class]: ... +def readmodule_ex(module: str, path: Sequence[str] | None = ...) -> dict[str, Class | Function | list[str]]: ... diff --git a/mypy/typeshed/stdlib/@python2/pydoc.pyi b/mypy/typeshed/stdlib/@python2/pydoc.pyi index dee0c4710b39..a43b7333c7b0 100644 --- a/mypy/typeshed/stdlib/@python2/pydoc.pyi +++ b/mypy/typeshed/stdlib/@python2/pydoc.pyi @@ -1,35 +1,20 @@ from _typeshed import SupportsWrite from types import MethodType, ModuleType, TracebackType -from typing import ( - IO, - Any, - AnyStr, - Callable, - Container, - Dict, - List, - Mapping, - MutableMapping, - NoReturn, - Optional, - Text, - Tuple, - Type, -) +from typing import IO, Any, AnyStr, Callable, Container, Mapping, MutableMapping, NoReturn, Optional, Text from repr import Repr # the return type of sys.exc_info(), used by ErrorDuringImport.__init__ -_Exc_Info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_Exc_Info = tuple[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]] __author__: str __date__: str __version__: str __credits__: str -def pathdirs() -> List[str]: ... +def pathdirs() -> list[str]: ... def getdoc(object: object) -> Text: ... -def splitdoc(doc: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def splitdoc(doc: AnyStr) -> tuple[AnyStr, AnyStr]: ... def classname(object: object, modname: str) -> str: ... def isdata(object: object) -> bool: ... def replace(text: AnyStr, *pairs: AnyStr) -> AnyStr: ... @@ -37,14 +22,14 @@ def cram(text: str, maxlen: int) -> str: ... def stripid(text: str) -> str: ... def allmethods(cl: type) -> MutableMapping[str, MethodType]: ... def visiblename(name: str, all: Container[str] | None = ..., obj: object | None = ...) -> bool: ... -def classify_class_attrs(object: object) -> List[Tuple[str, str, type, str]]: ... +def classify_class_attrs(object: object) -> list[tuple[str, str, type, str]]: ... def ispackage(path: str) -> bool: ... def source_synopsis(file: IO[AnyStr]) -> AnyStr | None: ... -def synopsis(filename: str, cache: MutableMapping[str, Tuple[int, str]] = ...) -> str | None: ... +def synopsis(filename: str, cache: MutableMapping[str, tuple[int, str]] = ...) -> str | None: ... class ErrorDuringImport(Exception): filename: str - exc: Type[BaseException] | None + exc: type[BaseException] | None value: BaseException | None tb: TracebackType | None def __init__(self, filename: str, exc_info: _Exc_Info) -> None: ... @@ -97,12 +82,12 @@ class HTMLDoc(Doc): ) -> str: ... def bigsection(self, title: str, *args: Any) -> str: ... def preformat(self, text: str) -> str: ... - def multicolumn(self, list: List[Any], format: Callable[[Any], str], cols: int = ...) -> str: ... + def multicolumn(self, list: list[Any], format: Callable[[Any], str], cols: int = ...) -> str: ... def grey(self, text: str) -> str: ... def namelink(self, name: str, *dicts: MutableMapping[str, str]) -> str: ... def classlink(self, object: object, modname: str) -> str: ... def modulelink(self, object: object) -> str: ... - def modpkglink(self, modpkginfo: Tuple[str, str, bool, bool]) -> str: ... + def modpkglink(self, modpkginfo: tuple[str, str, bool, bool]) -> str: ... def markup( self, text: str, @@ -112,7 +97,7 @@ class HTMLDoc(Doc): methods: Mapping[str, str] = ..., ) -> str: ... def formattree( - self, tree: List[Tuple[type, Tuple[type, ...]] | List[Any]], modname: str, parent: type | None = ... + self, tree: list[tuple[type, tuple[type, ...]] | list[Any]], modname: str, parent: type | None = ... ) -> str: ... def docmodule(self, object: object, name: str | None = ..., mod: str | None = ..., *ignored: Any) -> str: ... def docclass( @@ -164,7 +149,7 @@ class TextDoc(Doc): def indent(self, text: str, prefix: str = ...) -> str: ... def section(self, title: str, contents: str) -> str: ... def formattree( - self, tree: List[Tuple[type, Tuple[type, ...]] | List[Any]], modname: str, parent: type | None = ..., prefix: str = ... + self, tree: list[tuple[type, tuple[type, ...]] | list[Any]], modname: str, parent: type | None = ..., prefix: str = ... ) -> str: ... def docmodule(self, object: object, name: str | None = ..., mod: Any | None = ..., *ignored: Any) -> str: ... def docclass(self, object: object, name: str | None = ..., mod: str | None = ..., *ignored: Any) -> str: ... @@ -204,16 +189,16 @@ html: HTMLDoc class _OldStyleClass: ... -def resolve(thing: str | object, forceload: bool = ...) -> Tuple[object, str] | None: ... +def resolve(thing: str | object, forceload: bool = ...) -> tuple[object, str] | None: ... def render_doc(thing: str | object, title: str = ..., forceload: bool = ..., renderer: Doc | None = ...) -> str: ... def doc(thing: str | object, title: str = ..., forceload: bool = ..., output: SupportsWrite[str] | None = ...) -> None: ... def writedoc(thing: str | object, forceload: bool = ...) -> None: ... def writedocs(dir: str, pkgpath: str = ..., done: Any | None = ...) -> None: ... class Helper: - keywords: Dict[str, str | Tuple[str, str]] - symbols: Dict[str, str] - topics: Dict[str, str | Tuple[str, ...]] + keywords: dict[str, str | tuple[str, str]] + symbols: dict[str, str] + topics: dict[str, str | tuple[str, ...]] def __init__(self, input: IO[str] | None = ..., output: IO[str] | None = ...) -> None: ... input: IO[str] output: IO[str] @@ -222,7 +207,7 @@ class Helper: def getline(self, prompt: str) -> str: ... def help(self, request: Any) -> None: ... def intro(self) -> None: ... - def list(self, items: List[str], columns: int = ..., width: int = ...) -> None: ... + def list(self, items: list[str], columns: int = ..., width: int = ...) -> None: ... def listkeywords(self) -> None: ... def listsymbols(self) -> None: ... def listtopics(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/pydoc_data/topics.pyi b/mypy/typeshed/stdlib/@python2/pydoc_data/topics.pyi index 1c48f4022fd6..091d34300106 100644 --- a/mypy/typeshed/stdlib/@python2/pydoc_data/topics.pyi +++ b/mypy/typeshed/stdlib/@python2/pydoc_data/topics.pyi @@ -1,3 +1 @@ -from typing import Dict - -topics: Dict[str, str] +topics: dict[str, str] diff --git a/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi index bd73f850b559..8faaec294316 100644 --- a/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/pyexpat/__init__.pyi @@ -1,12 +1,12 @@ import pyexpat.errors as errors import pyexpat.model as model from _typeshed import SupportsRead -from typing import Any, Callable, Dict, List, Optional, Text, Tuple +from typing import Any, Callable, Optional, Text EXPAT_VERSION: str # undocumented -version_info: Tuple[int, int, int] # undocumented +version_info: tuple[int, int, int] # undocumented native_encoding: str # undocumented -features: List[Tuple[str, int]] # undocumented +features: list[tuple[str, int]] # undocumented class ExpatError(Exception): code: int @@ -19,7 +19,7 @@ XML_PARAM_ENTITY_PARSING_NEVER: int XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE: int XML_PARAM_ENTITY_PARSING_ALWAYS: int -_Model = Tuple[int, int, Optional[str], Tuple[Any, ...]] +_Model = tuple[int, int, Optional[str], tuple[Any, ...]] class XMLParserType(object): def Parse(self, __data: Text | bytes, __isfinal: bool = ...) -> int: ... @@ -48,8 +48,8 @@ class XMLParserType(object): EndDoctypeDeclHandler: Callable[[], Any] | None ElementDeclHandler: Callable[[str, _Model], Any] | None AttlistDeclHandler: Callable[[str, str, str, str | None, bool], Any] | None - StartElementHandler: Callable[[str, Dict[str, str]], Any] | Callable[[str, List[str]], Any] | Callable[ - [str, Dict[str, str], List[str]], Any + StartElementHandler: Callable[[str, dict[str, str]], Any] | Callable[[str, list[str]], Any] | Callable[ + [str, dict[str, str], list[str]], Any ] | None EndElementHandler: Callable[[str], Any] | None ProcessingInstructionHandler: Callable[[str, str], Any] | None @@ -71,5 +71,5 @@ def ErrorString(__code: int) -> str: ... # intern is undocumented def ParserCreate( - encoding: Text | None = ..., namespace_separator: Text | None = ..., intern: Dict[str, Any] | None = ... + encoding: Text | None = ..., namespace_separator: Text | None = ..., intern: dict[str, Any] | None = ... ) -> XMLParserType: ... diff --git a/mypy/typeshed/stdlib/@python2/random.pyi b/mypy/typeshed/stdlib/@python2/random.pyi index 6fb5d602067c..df279a03c24a 100644 --- a/mypy/typeshed/stdlib/@python2/random.pyi +++ b/mypy/typeshed/stdlib/@python2/random.pyi @@ -1,5 +1,5 @@ import _random -from typing import Any, Callable, Iterator, List, MutableSequence, Protocol, Sequence, TypeVar, overload +from typing import Any, Callable, Iterator, MutableSequence, Protocol, Sequence, TypeVar, overload _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) @@ -22,7 +22,7 @@ class Random(_random.Random): def randint(self, a: int, b: int) -> int: ... def choice(self, seq: Sequence[_T]) -> _T: ... def shuffle(self, x: MutableSequence[Any], random: Callable[[], None] = ...) -> None: ... - def sample(self, population: _Sampleable[_T], k: int) -> List[_T]: ... + def sample(self, population: _Sampleable[_T], k: int) -> list[_T]: ... def random(self) -> float: ... def uniform(self, a: float, b: float) -> float: ... def triangular(self, low: float = ..., high: float = ..., mode: float = ...) -> float: ... @@ -52,7 +52,7 @@ def randrange(start: int, stop: int, step: int = ...) -> int: ... def randint(a: int, b: int) -> int: ... def choice(seq: Sequence[_T]) -> _T: ... def shuffle(x: MutableSequence[Any], random: Callable[[], float] = ...) -> None: ... -def sample(population: _Sampleable[_T], k: int) -> List[_T]: ... +def sample(population: _Sampleable[_T], k: int) -> list[_T]: ... def random() -> float: ... def uniform(a: float, b: float) -> float: ... def triangular(low: float = ..., high: float = ..., mode: float = ...) -> float: ... diff --git a/mypy/typeshed/stdlib/@python2/re.pyi b/mypy/typeshed/stdlib/@python2/re.pyi index fbe021ce67be..ba555968ad4b 100644 --- a/mypy/typeshed/stdlib/@python2/re.pyi +++ b/mypy/typeshed/stdlib/@python2/re.pyi @@ -1,4 +1,4 @@ -from typing import Any, AnyStr, Callable, Iterator, List, Match, Pattern, Tuple, overload +from typing import Any, AnyStr, Callable, Iterator, Match, Pattern, overload # ----- re variables and constants ----- DEBUG: int @@ -32,13 +32,13 @@ def match(pattern: str | unicode, string: AnyStr, flags: int = ...) -> Match[Any @overload def match(pattern: Pattern[str] | Pattern[unicode], string: AnyStr, flags: int = ...) -> Match[AnyStr] | None: ... @overload -def split(pattern: str | unicode, string: AnyStr, maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ... +def split(pattern: str | unicode, string: AnyStr, maxsplit: int = ..., flags: int = ...) -> list[AnyStr]: ... @overload -def split(pattern: Pattern[str] | Pattern[unicode], string: AnyStr, maxsplit: int = ..., flags: int = ...) -> List[AnyStr]: ... +def split(pattern: Pattern[str] | Pattern[unicode], string: AnyStr, maxsplit: int = ..., flags: int = ...) -> list[AnyStr]: ... @overload -def findall(pattern: str | unicode, string: AnyStr, flags: int = ...) -> List[Any]: ... +def findall(pattern: str | unicode, string: AnyStr, flags: int = ...) -> list[Any]: ... @overload -def findall(pattern: Pattern[str] | Pattern[unicode], string: AnyStr, flags: int = ...) -> List[Any]: ... +def findall(pattern: Pattern[str] | Pattern[unicode], string: AnyStr, flags: int = ...) -> list[Any]: ... # Return an iterator yielding match objects over all non-overlapping matches # for the RE pattern in string. The string is scanned left-to-right, and @@ -65,15 +65,15 @@ def sub( flags: int = ..., ) -> AnyStr: ... @overload -def subn(pattern: str | unicode, repl: AnyStr, string: AnyStr, count: int = ..., flags: int = ...) -> Tuple[AnyStr, int]: ... +def subn(pattern: str | unicode, repl: AnyStr, string: AnyStr, count: int = ..., flags: int = ...) -> tuple[AnyStr, int]: ... @overload def subn( pattern: str | unicode, repl: Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = ..., flags: int = ... -) -> Tuple[AnyStr, int]: ... +) -> tuple[AnyStr, int]: ... @overload def subn( pattern: Pattern[str] | Pattern[unicode], repl: AnyStr, string: AnyStr, count: int = ..., flags: int = ... -) -> Tuple[AnyStr, int]: ... +) -> tuple[AnyStr, int]: ... @overload def subn( pattern: Pattern[str] | Pattern[unicode], @@ -81,7 +81,7 @@ def subn( string: AnyStr, count: int = ..., flags: int = ..., -) -> Tuple[AnyStr, int]: ... +) -> tuple[AnyStr, int]: ... def escape(string: AnyStr) -> AnyStr: ... def purge() -> None: ... def template(pattern: AnyStr | Pattern[AnyStr], flags: int = ...) -> Pattern[AnyStr]: ... diff --git a/mypy/typeshed/stdlib/@python2/readline.pyi b/mypy/typeshed/stdlib/@python2/readline.pyi index fb9b12d9a8e9..9b82d9bae636 100644 --- a/mypy/typeshed/stdlib/@python2/readline.pyi +++ b/mypy/typeshed/stdlib/@python2/readline.pyi @@ -1,30 +1,31 @@ +import sys from typing import Callable, Optional, Sequence, Text -_CompleterT = Optional[Callable[[str, int], Optional[str]]] -_CompDispT = Optional[Callable[[str, Sequence[str], int], None]] - -def parse_and_bind(__string: str) -> None: ... -def read_init_file(__filename: Text | None = ...) -> None: ... -def get_line_buffer() -> str: ... -def insert_text(__string: str) -> None: ... -def redisplay() -> None: ... -def read_history_file(__filename: Text | None = ...) -> None: ... -def write_history_file(__filename: Text | None = ...) -> None: ... -def get_history_length() -> int: ... -def set_history_length(__length: int) -> None: ... -def clear_history() -> None: ... -def get_current_history_length() -> int: ... -def get_history_item(__index: int) -> str: ... -def remove_history_item(__pos: int) -> None: ... -def replace_history_item(__pos: int, __line: str) -> None: ... -def add_history(__string: str) -> None: ... -def set_startup_hook(__function: Callable[[], None] | None = ...) -> None: ... -def set_pre_input_hook(__function: Callable[[], None] | None = ...) -> None: ... -def set_completer(__function: _CompleterT = ...) -> None: ... -def get_completer() -> _CompleterT: ... -def get_completion_type() -> int: ... -def get_begidx() -> int: ... -def get_endidx() -> int: ... -def set_completer_delims(__string: str) -> None: ... -def get_completer_delims() -> str: ... -def set_completion_display_matches_hook(__function: _CompDispT = ...) -> None: ... +if sys.platform != "win32": + _CompleterT = Optional[Callable[[str, int], Optional[str]]] + _CompDispT = Optional[Callable[[str, Sequence[str], int], None]] + def parse_and_bind(__string: str) -> None: ... + def read_init_file(__filename: Text | None = ...) -> None: ... + def get_line_buffer() -> str: ... + def insert_text(__string: str) -> None: ... + def redisplay() -> None: ... + def read_history_file(__filename: Text | None = ...) -> None: ... + def write_history_file(__filename: Text | None = ...) -> None: ... + def get_history_length() -> int: ... + def set_history_length(__length: int) -> None: ... + def clear_history() -> None: ... + def get_current_history_length() -> int: ... + def get_history_item(__index: int) -> str: ... + def remove_history_item(__pos: int) -> None: ... + def replace_history_item(__pos: int, __line: str) -> None: ... + def add_history(__string: str) -> None: ... + def set_startup_hook(__function: Callable[[], None] | None = ...) -> None: ... + def set_pre_input_hook(__function: Callable[[], None] | None = ...) -> None: ... + def set_completer(__function: _CompleterT = ...) -> None: ... + def get_completer() -> _CompleterT: ... + def get_completion_type() -> int: ... + def get_begidx() -> int: ... + def get_endidx() -> int: ... + def set_completer_delims(__string: str) -> None: ... + def get_completer_delims() -> str: ... + def set_completion_display_matches_hook(__function: _CompDispT = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/repr.pyi b/mypy/typeshed/stdlib/@python2/repr.pyi index bdb8822ac77d..6b6f5ea9325e 100644 --- a/mypy/typeshed/stdlib/@python2/repr.pyi +++ b/mypy/typeshed/stdlib/@python2/repr.pyi @@ -1,4 +1,4 @@ -from typing import Any, List +from typing import Any class Repr: maxarray: int @@ -27,7 +27,7 @@ class Repr: def repr_str(self, x, level: complex) -> str: ... def repr_tuple(self, x, level: complex) -> str: ... -def _possibly_sorted(x) -> List[Any]: ... +def _possibly_sorted(x) -> list[Any]: ... aRepr: Repr diff --git a/mypy/typeshed/stdlib/@python2/resource.pyi b/mypy/typeshed/stdlib/@python2/resource.pyi index ad9502db1940..1a655604b129 100644 --- a/mypy/typeshed/stdlib/@python2/resource.pyi +++ b/mypy/typeshed/stdlib/@python2/resource.pyi @@ -1,46 +1,42 @@ -from typing import NamedTuple, Tuple +import sys +from typing import NamedTuple -class error(Exception): ... - -RLIM_INFINITY: int - -def getrlimit(resource: int) -> Tuple[int, int]: ... -def setrlimit(resource: int, limits: Tuple[int, int]) -> None: ... - -RLIMIT_CORE: int -RLIMIT_CPU: int -RLIMIT_FSIZE: int -RLIMIT_DATA: int -RLIMIT_STACK: int -RLIMIT_RSS: int -RLIMIT_NPROC: int -RLIMIT_NOFILE: int -RLIMIT_OFILE: int -RLIMIT_MEMLOCK: int -RLIMIT_VMEM: int -RLIMIT_AS: int - -class _RUsage(NamedTuple): - ru_utime: float - ru_stime: float - ru_maxrss: int - ru_ixrss: int - ru_idrss: int - ru_isrss: int - ru_minflt: int - ru_majflt: int - ru_nswap: int - ru_inblock: int - ru_oublock: int - ru_msgsnd: int - ru_msgrcv: int - ru_nsignals: int - ru_nvcsw: int - ru_nivcsw: int - -def getrusage(who: int) -> _RUsage: ... -def getpagesize() -> int: ... - -RUSAGE_SELF: int -RUSAGE_CHILDREN: int -RUSAGE_BOTH: int +if sys.platform != "win32": + class error(Exception): ... + RLIM_INFINITY: int + def getrlimit(resource: int) -> tuple[int, int]: ... + def setrlimit(resource: int, limits: tuple[int, int]) -> None: ... + RLIMIT_CORE: int + RLIMIT_CPU: int + RLIMIT_FSIZE: int + RLIMIT_DATA: int + RLIMIT_STACK: int + RLIMIT_RSS: int + RLIMIT_NPROC: int + RLIMIT_NOFILE: int + RLIMIT_OFILE: int + RLIMIT_MEMLOCK: int + RLIMIT_VMEM: int + RLIMIT_AS: int + class _RUsage(NamedTuple): + ru_utime: float + ru_stime: float + ru_maxrss: int + ru_ixrss: int + ru_idrss: int + ru_isrss: int + ru_minflt: int + ru_majflt: int + ru_nswap: int + ru_inblock: int + ru_oublock: int + ru_msgsnd: int + ru_msgrcv: int + ru_nsignals: int + ru_nvcsw: int + ru_nivcsw: int + def getrusage(who: int) -> _RUsage: ... + def getpagesize() -> int: ... + RUSAGE_SELF: int + RUSAGE_CHILDREN: int + RUSAGE_BOTH: int diff --git a/mypy/typeshed/stdlib/@python2/rlcompleter.pyi b/mypy/typeshed/stdlib/@python2/rlcompleter.pyi index a61c61eb24f2..fcd385f335fb 100644 --- a/mypy/typeshed/stdlib/@python2/rlcompleter.pyi +++ b/mypy/typeshed/stdlib/@python2/rlcompleter.pyi @@ -1,7 +1,7 @@ -from typing import Any, Dict, Union +from typing import Any, Union _Text = Union[str, unicode] class Completer: - def __init__(self, namespace: Dict[str, Any] | None = ...) -> None: ... + def __init__(self, namespace: dict[str, Any] | None = ...) -> None: ... def complete(self, text: _Text, state: int) -> str | None: ... diff --git a/mypy/typeshed/stdlib/@python2/sched.pyi b/mypy/typeshed/stdlib/@python2/sched.pyi index f718dd7a57bd..9247a95da974 100644 --- a/mypy/typeshed/stdlib/@python2/sched.pyi +++ b/mypy/typeshed/stdlib/@python2/sched.pyi @@ -1,18 +1,18 @@ -from typing import Any, Callable, Dict, List, NamedTuple, Text, Tuple +from typing import Any, Callable, NamedTuple, Text class Event(NamedTuple): time: float priority: Any action: Callable[..., Any] - argument: Tuple[Any, ...] - kwargs: Dict[Text, Any] + argument: tuple[Any, ...] + kwargs: dict[Text, Any] class scheduler: def __init__(self, timefunc: Callable[[], float], delayfunc: Callable[[float], None]) -> None: ... - def enterabs(self, time: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...]) -> Event: ... - def enter(self, delay: float, priority: Any, action: Callable[..., Any], argument: Tuple[Any, ...]) -> Event: ... + def enterabs(self, time: float, priority: Any, action: Callable[..., Any], argument: tuple[Any, ...]) -> Event: ... + def enter(self, delay: float, priority: Any, action: Callable[..., Any], argument: tuple[Any, ...]) -> Event: ... def run(self) -> None: ... def cancel(self, event: Event) -> None: ... def empty(self) -> bool: ... @property - def queue(self) -> List[Event]: ... + def queue(self) -> list[Event]: ... diff --git a/mypy/typeshed/stdlib/@python2/select.pyi b/mypy/typeshed/stdlib/@python2/select.pyi index b960fd4e24b5..cd799d75b5b1 100644 --- a/mypy/typeshed/stdlib/@python2/select.pyi +++ b/mypy/typeshed/stdlib/@python2/select.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import FileDescriptorLike -from typing import Any, Iterable, List, Tuple +from typing import Any, Iterable if sys.platform != "win32": PIPE_BUF: int @@ -21,11 +21,11 @@ class poll: def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... def modify(self, fd: FileDescriptorLike, eventmask: int) -> None: ... def unregister(self, fd: FileDescriptorLike) -> None: ... - def poll(self, timeout: float | None = ...) -> List[Tuple[int, int]]: ... + def poll(self, timeout: float | None = ...) -> list[tuple[int, int]]: ... def select( __rlist: Iterable[Any], __wlist: Iterable[Any], __xlist: Iterable[Any], __timeout: float | None = ... -) -> Tuple[List[Any], List[Any], List[Any]]: ... +) -> tuple[list[Any], list[Any], list[Any]]: ... class error(Exception): ... @@ -54,7 +54,7 @@ if sys.platform != "linux" and sys.platform != "win32": def close(self) -> None: ... def control( self, __changelist: Iterable[kevent] | None, __maxevents: int, __timeout: float | None = ... - ) -> List[kevent]: ... + ) -> list[kevent]: ... def fileno(self) -> int: ... @classmethod def fromfd(cls, __fd: FileDescriptorLike) -> kqueue: ... @@ -106,7 +106,7 @@ if sys.platform == "linux": def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ... def modify(self, fd: FileDescriptorLike, eventmask: int) -> None: ... def unregister(self, fd: FileDescriptorLike) -> None: ... - def poll(self, timeout: float | None = ..., maxevents: int = ...) -> List[Tuple[int, int]]: ... + def poll(self, timeout: float | None = ..., maxevents: int = ...) -> list[tuple[int, int]]: ... @classmethod def fromfd(cls, __fd: FileDescriptorLike) -> epoll: ... EPOLLERR: int diff --git a/mypy/typeshed/stdlib/@python2/sets.pyi b/mypy/typeshed/stdlib/@python2/sets.pyi index d2b94ea44bbc..916cb3defdc6 100644 --- a/mypy/typeshed/stdlib/@python2/sets.pyi +++ b/mypy/typeshed/stdlib/@python2/sets.pyi @@ -1,29 +1,27 @@ +from _typeshed import Self from typing import Any, Hashable, Iterable, Iterator, MutableMapping, TypeVar, Union _T = TypeVar("_T") _Setlike = Union[BaseSet[_T], Iterable[_T]] -_SelfT = TypeVar("_SelfT") class BaseSet(Iterable[_T]): def __init__(self) -> None: ... def __len__(self) -> int: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... def __iter__(self) -> Iterator[_T]: ... def __cmp__(self, other: Any) -> int: ... def __eq__(self, other: Any) -> bool: ... def __ne__(self, other: Any) -> bool: ... - def copy(self: _SelfT) -> _SelfT: ... - def __copy__(self: _SelfT) -> _SelfT: ... - def __deepcopy__(self: _SelfT, memo: MutableMapping[int, BaseSet[_T]]) -> _SelfT: ... - def __or__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def union(self: _SelfT, other: _Setlike[_T]) -> _SelfT: ... - def __and__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def intersection(self: _SelfT, other: _Setlike[Any]) -> _SelfT: ... - def __xor__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def symmetric_difference(self: _SelfT, other: _Setlike[_T]) -> _SelfT: ... - def __sub__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... - def difference(self: _SelfT, other: _Setlike[Any]) -> _SelfT: ... + def copy(self: Self) -> Self: ... + def __copy__(self: Self) -> Self: ... + def __deepcopy__(self: Self, memo: MutableMapping[int, BaseSet[_T]]) -> Self: ... + def __or__(self: Self, other: BaseSet[_T]) -> Self: ... + def union(self: Self, other: _Setlike[_T]) -> Self: ... + def __and__(self: Self, other: BaseSet[_T]) -> Self: ... + def intersection(self: Self, other: _Setlike[Any]) -> Self: ... + def __xor__(self: Self, other: BaseSet[_T]) -> Self: ... + def symmetric_difference(self: Self, other: _Setlike[_T]) -> Self: ... + def __sub__(self: Self, other: BaseSet[_T]) -> Self: ... + def difference(self: Self, other: _Setlike[Any]) -> Self: ... def __contains__(self, element: Any) -> bool: ... def issubset(self, other: BaseSet[_T]) -> bool: ... def issuperset(self, other: BaseSet[_T]) -> bool: ... @@ -38,13 +36,13 @@ class ImmutableSet(BaseSet[_T], Hashable): class Set(BaseSet[_T]): def __init__(self, iterable: _Setlike[_T] | None = ...) -> None: ... - def __ior__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def __ior__(self: Self, other: BaseSet[_T]) -> Self: ... def union_update(self, other: _Setlike[_T]) -> None: ... - def __iand__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def __iand__(self: Self, other: BaseSet[_T]) -> Self: ... def intersection_update(self, other: _Setlike[Any]) -> None: ... - def __ixor__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def __ixor__(self: Self, other: BaseSet[_T]) -> Self: ... def symmetric_difference_update(self, other: _Setlike[_T]) -> None: ... - def __isub__(self: _SelfT, other: BaseSet[_T]) -> _SelfT: ... + def __isub__(self: Self, other: BaseSet[_T]) -> Self: ... def difference_update(self, other: _Setlike[Any]) -> None: ... def update(self, iterable: _Setlike[_T]) -> None: ... def clear(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/shelve.pyi b/mypy/typeshed/stdlib/@python2/shelve.pyi index d9b1a00e58df..0e795c4148a7 100644 --- a/mypy/typeshed/stdlib/@python2/shelve.pyi +++ b/mypy/typeshed/stdlib/@python2/shelve.pyi @@ -1,12 +1,12 @@ import collections -from typing import Any, Dict, Iterator, List, Tuple +from typing import Any, Iterator class Shelf(collections.MutableMapping[Any, Any]): def __init__( - self, dict: Dict[Any, Any], protocol: int | None = ..., writeback: bool = ..., keyencoding: str = ... + self, dict: dict[Any, Any], protocol: int | None = ..., writeback: bool = ..., keyencoding: str = ... ) -> None: ... def __iter__(self) -> Iterator[str]: ... - def keys(self) -> List[Any]: ... + def keys(self) -> list[Any]: ... def __len__(self) -> int: ... def has_key(self, key: Any) -> bool: ... def __contains__(self, key: Any) -> bool: ... @@ -22,13 +22,13 @@ class Shelf(collections.MutableMapping[Any, Any]): class BsdDbShelf(Shelf): def __init__( - self, dict: Dict[Any, Any], protocol: int | None = ..., writeback: bool = ..., keyencoding: str = ... + self, dict: dict[Any, Any], protocol: int | None = ..., writeback: bool = ..., keyencoding: str = ... ) -> None: ... - def set_location(self, key: Any) -> Tuple[str, Any]: ... - def next(self) -> Tuple[str, Any]: ... - def previous(self) -> Tuple[str, Any]: ... - def first(self) -> Tuple[str, Any]: ... - def last(self) -> Tuple[str, Any]: ... + def set_location(self, key: Any) -> tuple[str, Any]: ... + def next(self) -> tuple[str, Any]: ... + def previous(self) -> tuple[str, Any]: ... + def first(self) -> tuple[str, Any]: ... + def last(self) -> tuple[str, Any]: ... class DbfilenameShelf(Shelf): def __init__(self, filename: str, flag: str = ..., protocol: int | None = ..., writeback: bool = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/shlex.pyi b/mypy/typeshed/stdlib/@python2/shlex.pyi index 89c28fc9be7f..6c4557a98036 100644 --- a/mypy/typeshed/stdlib/@python2/shlex.pyi +++ b/mypy/typeshed/stdlib/@python2/shlex.pyi @@ -1,12 +1,11 @@ -from typing import IO, Any, List, Text, TypeVar +from _typeshed import Self +from typing import IO, Any, Text -def split(s: str | None, comments: bool = ..., posix: bool = ...) -> List[str]: ... - -_SLT = TypeVar("_SLT", bound=shlex) +def split(s: str | None, comments: bool = ..., posix: bool = ...) -> list[str]: ... class shlex: def __init__(self, instream: IO[Any] | Text = ..., infile: IO[Any] = ..., posix: bool = ...) -> None: ... - def __iter__(self: _SLT) -> _SLT: ... + def __iter__(self: Self) -> Self: ... def next(self) -> str: ... def get_token(self) -> str | None: ... def push_token(self, _str: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/shutil.pyi b/mypy/typeshed/stdlib/@python2/shutil.pyi index 4805c8e4cdb7..f92cf1c9f1a0 100644 --- a/mypy/typeshed/stdlib/@python2/shutil.pyi +++ b/mypy/typeshed/stdlib/@python2/shutil.pyi @@ -1,9 +1,9 @@ from _typeshed import SupportsRead, SupportsWrite -from typing import Any, AnyStr, Callable, Iterable, List, Sequence, Set, Text, Tuple, Type, TypeVar, Union +from typing import Any, AnyStr, Callable, Iterable, Sequence, Text, TypeVar, Union _AnyStr = TypeVar("_AnyStr", str, unicode) _AnyPath = TypeVar("_AnyPath", str, unicode) -_PathReturn = Type[None] +_PathReturn = type[None] class Error(EnvironmentError): ... class SpecialFileError(EnvironmentError): ... @@ -15,9 +15,9 @@ def copymode(src: Text, dst: Text) -> None: ... def copystat(src: Text, dst: Text) -> None: ... def copy(src: Text, dst: Text) -> _PathReturn: ... def copy2(src: Text, dst: Text) -> _PathReturn: ... -def ignore_patterns(*patterns: Text) -> Callable[[Any, List[_AnyStr]], Set[_AnyStr]]: ... +def ignore_patterns(*patterns: Text) -> Callable[[Any, list[_AnyStr]], set[_AnyStr]]: ... def copytree( - src: AnyStr, dst: AnyStr, symlinks: bool = ..., ignore: None | Callable[[AnyStr, List[AnyStr]], Iterable[AnyStr]] = ... + src: AnyStr, dst: AnyStr, symlinks: bool = ..., ignore: None | Callable[[AnyStr, list[AnyStr]], Iterable[AnyStr]] = ... ) -> _PathReturn: ... def rmtree(path: _AnyPath, ignore_errors: bool = ..., onerror: Callable[[Any, _AnyPath, Any], Any] | None = ...) -> None: ... @@ -35,11 +35,11 @@ def make_archive( group: str | None = ..., logger: Any | None = ..., ) -> _AnyStr: ... -def get_archive_formats() -> List[Tuple[str, str]]: ... +def get_archive_formats() -> list[tuple[str, str]]: ... def register_archive_format( name: str, function: Callable[..., Any], - extra_args: Sequence[Tuple[str, Any] | List[Any]] | None = ..., + extra_args: Sequence[tuple[str, Any] | list[Any]] | None = ..., description: str = ..., ) -> None: ... def unregister_archive_format(name: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/signal.pyi b/mypy/typeshed/stdlib/@python2/signal.pyi index 16a8f2d1cb8b..7f86f03e638a 100644 --- a/mypy/typeshed/stdlib/@python2/signal.pyi +++ b/mypy/typeshed/stdlib/@python2/signal.pyi @@ -1,57 +1,57 @@ from types import FrameType -from typing import Callable, Tuple, Union +from typing import Callable, Union -SIG_DFL: int = ... -SIG_IGN: int = ... +SIG_DFL: int +SIG_IGN: int -ITIMER_REAL: int = ... -ITIMER_VIRTUAL: int = ... -ITIMER_PROF: int = ... +ITIMER_REAL: int +ITIMER_VIRTUAL: int +ITIMER_PROF: int -NSIG: int = ... +NSIG: int -SIGABRT: int = ... -SIGALRM: int = ... -SIGBREAK: int = ... # Windows -SIGBUS: int = ... -SIGCHLD: int = ... -SIGCLD: int = ... -SIGCONT: int = ... -SIGEMT: int = ... -SIGFPE: int = ... -SIGHUP: int = ... -SIGILL: int = ... -SIGINFO: int = ... -SIGINT: int = ... -SIGIO: int = ... -SIGIOT: int = ... -SIGKILL: int = ... -SIGPIPE: int = ... -SIGPOLL: int = ... -SIGPROF: int = ... -SIGPWR: int = ... -SIGQUIT: int = ... -SIGRTMAX: int = ... -SIGRTMIN: int = ... -SIGSEGV: int = ... -SIGSTOP: int = ... -SIGSYS: int = ... -SIGTERM: int = ... -SIGTRAP: int = ... -SIGTSTP: int = ... -SIGTTIN: int = ... -SIGTTOU: int = ... -SIGURG: int = ... -SIGUSR1: int = ... -SIGUSR2: int = ... -SIGVTALRM: int = ... -SIGWINCH: int = ... -SIGXCPU: int = ... -SIGXFSZ: int = ... +SIGABRT: int +SIGALRM: int +SIGBREAK: int # Windows +SIGBUS: int +SIGCHLD: int +SIGCLD: int +SIGCONT: int +SIGEMT: int +SIGFPE: int +SIGHUP: int +SIGILL: int +SIGINFO: int +SIGINT: int +SIGIO: int +SIGIOT: int +SIGKILL: int +SIGPIPE: int +SIGPOLL: int +SIGPROF: int +SIGPWR: int +SIGQUIT: int +SIGRTMAX: int +SIGRTMIN: int +SIGSEGV: int +SIGSTOP: int +SIGSYS: int +SIGTERM: int +SIGTRAP: int +SIGTSTP: int +SIGTTIN: int +SIGTTOU: int +SIGURG: int +SIGUSR1: int +SIGUSR2: int +SIGVTALRM: int +SIGWINCH: int +SIGXCPU: int +SIGXFSZ: int # Windows -CTRL_C_EVENT: int = ... -CTRL_BREAK_EVENT: int = ... +CTRL_C_EVENT: int +CTRL_BREAK_EVENT: int class ItimerError(IOError): ... @@ -60,8 +60,8 @@ _HANDLER = Union[Callable[[int, FrameType], None], int, None] def alarm(time: int) -> int: ... def getsignal(signalnum: int) -> _HANDLER: ... def pause() -> None: ... -def setitimer(which: int, seconds: float, interval: float = ...) -> Tuple[float, float]: ... -def getitimer(which: int) -> Tuple[float, float]: ... +def setitimer(which: int, seconds: float, interval: float = ...) -> tuple[float, float]: ... +def getitimer(which: int) -> tuple[float, float]: ... def set_wakeup_fd(fd: int) -> int: ... def siginterrupt(signalnum: int, flag: bool) -> None: ... def signal(signalnum: int, handler: _HANDLER) -> _HANDLER: ... diff --git a/mypy/typeshed/stdlib/@python2/site.pyi b/mypy/typeshed/stdlib/@python2/site.pyi index c77c9397f612..fc331c113163 100644 --- a/mypy/typeshed/stdlib/@python2/site.pyi +++ b/mypy/typeshed/stdlib/@python2/site.pyi @@ -1,12 +1,12 @@ -from typing import Iterable, List +from typing import Iterable -PREFIXES: List[str] +PREFIXES: list[str] ENABLE_USER_SITE: bool | None USER_SITE: str | None USER_BASE: str | None def main() -> None: ... def addsitedir(sitedir: str, known_paths: Iterable[str] | None = ...) -> None: ... -def getsitepackages(prefixes: Iterable[str] | None = ...) -> List[str]: ... +def getsitepackages(prefixes: Iterable[str] | None = ...) -> list[str]: ... def getuserbase() -> str: ... def getusersitepackages() -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/smtpd.pyi b/mypy/typeshed/stdlib/@python2/smtpd.pyi index 1c17b82d8ab5..6778611a56d9 100644 --- a/mypy/typeshed/stdlib/@python2/smtpd.pyi +++ b/mypy/typeshed/stdlib/@python2/smtpd.pyi @@ -1,9 +1,9 @@ import asynchat import asyncore import socket -from typing import Any, List, Text, Tuple, Type +from typing import Any, Text -_Address = Tuple[str, int] # (host, port) +_Address = tuple[str, int] # (host, port) class SMTPChannel(asynchat.async_chat): COMMAND: int @@ -22,24 +22,24 @@ class SMTPChannel(asynchat.async_chat): def smtp_DATA(self, arg: str) -> None: ... class SMTPServer(asyncore.dispatcher): - channel_class: Type[SMTPChannel] + channel_class: type[SMTPChannel] data_size_limit: int enable_SMTPUTF8: bool def __init__(self, localaddr: _Address, remoteaddr: _Address, data_size_limit: int = ...) -> None: ... def handle_accepted(self, conn: socket.socket, addr: Any) -> None: ... def process_message( - self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: bytes | str, **kwargs: Any + self, peer: _Address, mailfrom: str, rcpttos: list[Text], data: bytes | str, **kwargs: Any ) -> str | None: ... class DebuggingServer(SMTPServer): ... class PureProxy(SMTPServer): def process_message( # type: ignore - self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: bytes | str + self, peer: _Address, mailfrom: str, rcpttos: list[Text], data: bytes | str ) -> str | None: ... class MailmanProxy(PureProxy): def process_message( # type: ignore - self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: bytes | str + self, peer: _Address, mailfrom: str, rcpttos: list[Text], data: bytes | str ) -> str | None: ... diff --git a/mypy/typeshed/stdlib/@python2/sndhdr.pyi b/mypy/typeshed/stdlib/@python2/sndhdr.pyi index 189529fd21d6..0213a5d0cbb3 100644 --- a/mypy/typeshed/stdlib/@python2/sndhdr.pyi +++ b/mypy/typeshed/stdlib/@python2/sndhdr.pyi @@ -1,6 +1,6 @@ -from typing import Text, Tuple, Union +from typing import Text, Union -_SndHeaders = Tuple[str, int, int, int, Union[int, str]] +_SndHeaders = tuple[str, int, int, int, Union[int, str]] def what(filename: Text) -> _SndHeaders | None: ... def whathdr(filename: Text) -> _SndHeaders | None: ... diff --git a/mypy/typeshed/stdlib/@python2/socket.pyi b/mypy/typeshed/stdlib/@python2/socket.pyi index 2bf719dd9faa..3a69a3239d32 100644 --- a/mypy/typeshed/stdlib/@python2/socket.pyi +++ b/mypy/typeshed/stdlib/@python2/socket.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, BinaryIO, Iterable, List, Text, Tuple, TypeVar, Union, overload +from typing import Any, BinaryIO, Iterable, Text, Union, overload # ----- Constants ----- # Some socket families are listed in the "Socket families" section of the docs, @@ -373,14 +373,13 @@ class timeout(error): # Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, # AF_NETLINK, AF_TIPC) or strings (AF_UNIX). -_Address = Union[Tuple[Any, ...], str] +_Address = Union[tuple[Any, ...], str] _RetAddress = Any # TODO Most methods allow bytes as address objects _WriteBuffer = Union[bytearray, memoryview] -_CMSG = Tuple[int, int, bytes] -_SelfT = TypeVar("_SelfT", bound=socket) +_CMSG = tuple[int, int, bytes] class socket: family: int @@ -388,7 +387,7 @@ class socket: proto: int def __init__(self, family: int = ..., type: int = ..., proto: int = ...) -> None: ... # --- methods --- - def accept(self) -> Tuple[socket, _RetAddress]: ... + def accept(self) -> tuple[socket, _RetAddress]: ... def bind(self, address: _Address | bytes) -> None: ... def close(self) -> None: ... def connect(self, address: _Address | bytes) -> None: ... @@ -404,13 +403,13 @@ class socket: def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... def gettimeout(self) -> float | None: ... if sys.platform == "win32": - def ioctl(self, control: int, option: int | Tuple[int, int, int]) -> None: ... + def ioctl(self, control: int, option: int | tuple[int, int, int]) -> None: ... def listen(self, __backlog: int) -> None: ... # Note that the makefile's documented windows-specific behavior is not represented def makefile(self, mode: unicode = ..., buffering: int = ...) -> BinaryIO: ... def recv(self, bufsize: int, flags: int = ...) -> bytes: ... - def recvfrom(self, bufsize: int, flags: int = ...) -> Tuple[bytes, _RetAddress]: ... - def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> Tuple[int, _RetAddress]: ... + def recvfrom(self, bufsize: int, flags: int = ...) -> tuple[bytes, _RetAddress]: ... + def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ... def recv_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> int: ... def send(self, data: bytes, flags: int = ...) -> int: ... def sendall(self, data: bytes, flags: int = ...) -> None: ... # return type: None on success @@ -428,9 +427,9 @@ class socket: # ----- Functions ----- def create_connection( - address: Tuple[str | None, int], + address: tuple[str | None, int], timeout: float | None = ..., - source_address: Tuple[bytearray | bytes | Text, int] | None = ..., + source_address: tuple[bytearray | bytes | Text, int] | None = ..., ) -> socket: ... def fromfd(fd: int, family: int, type: int, proto: int = ...) -> socket: ... @@ -442,22 +441,22 @@ def getaddrinfo( socktype: int = ..., proto: int = ..., flags: int = ..., -) -> List[Tuple[AddressFamily, SocketKind, int, str, Tuple[Any, ...]]]: ... +) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[Any, ...]]]: ... def getfqdn(name: str = ...) -> str: ... def gethostbyname(hostname: str) -> str: ... -def gethostbyname_ex(hostname: str) -> Tuple[str, List[str], List[str]]: ... +def gethostbyname_ex(hostname: str) -> tuple[str, list[str], list[str]]: ... def gethostname() -> str: ... -def gethostbyaddr(ip_address: str) -> Tuple[str, List[str], List[str]]: ... -def getnameinfo(sockaddr: Tuple[str, int] | Tuple[str, int, int, int], flags: int) -> Tuple[str, str]: ... +def gethostbyaddr(ip_address: str) -> tuple[str, list[str], list[str]]: ... +def getnameinfo(sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int) -> tuple[str, str]: ... def getprotobyname(protocolname: str) -> int: ... def getservbyname(servicename: str, protocolname: str = ...) -> int: ... def getservbyport(port: int, protocolname: str = ...) -> str: ... if sys.platform == "win32": - def socketpair(family: int = ..., type: int = ..., proto: int = ...) -> Tuple[socket, socket]: ... + def socketpair(family: int = ..., type: int = ..., proto: int = ...) -> tuple[socket, socket]: ... else: - def socketpair(family: int | None = ..., type: int = ..., proto: int = ...) -> Tuple[socket, socket]: ... + def socketpair(family: int | None = ..., type: int = ..., proto: int = ...) -> tuple[socket, socket]: ... def ntohl(x: int) -> int: ... # param & ret val are 32-bit ints def ntohs(x: int) -> int: ... # param & ret val are 16-bit ints diff --git a/mypy/typeshed/stdlib/@python2/spwd.pyi b/mypy/typeshed/stdlib/@python2/spwd.pyi index 756c142a61da..b21242fc49e4 100644 --- a/mypy/typeshed/stdlib/@python2/spwd.pyi +++ b/mypy/typeshed/stdlib/@python2/spwd.pyi @@ -1,15 +1,16 @@ -from typing import List, NamedTuple +import sys +from typing import NamedTuple -class struct_spwd(NamedTuple): - sp_nam: str - sp_pwd: str - sp_lstchg: int - sp_min: int - sp_max: int - sp_warn: int - sp_inact: int - sp_expire: int - sp_flag: int - -def getspall() -> List[struct_spwd]: ... -def getspnam(name: str) -> struct_spwd: ... +if sys.platform != "win32": + class struct_spwd(NamedTuple): + sp_nam: str + sp_pwd: str + sp_lstchg: int + sp_min: int + sp_max: int + sp_warn: int + sp_inact: int + sp_expire: int + sp_flag: int + def getspall() -> list[struct_spwd]: ... + def getspnam(name: str) -> struct_spwd: ... diff --git a/mypy/typeshed/stdlib/@python2/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/@python2/sqlite3/dbapi2.pyi index 023a0506f4aa..37b3b6df71b0 100644 --- a/mypy/typeshed/stdlib/@python2/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/@python2/sqlite3/dbapi2.pyi @@ -1,5 +1,5 @@ from datetime import date, datetime, time -from typing import Any, Callable, Generator, Iterable, Iterator, List, Protocol, Text, Tuple, Type, TypeVar +from typing import Any, Callable, Generator, Iterable, Iterator, Protocol, Text, TypeVar _T = TypeVar("_T") @@ -14,8 +14,8 @@ def DateFromTicks(ticks: float) -> Date: ... def TimeFromTicks(ticks: float) -> Time: ... def TimestampFromTicks(ticks: float) -> Timestamp: ... -version_info: Tuple[int, int, int] -sqlite_version_info: Tuple[int, int, int] +version_info: tuple[int, int, int] +sqlite_version_info: tuple[int, int, int] Binary = buffer # The remaining definitions are imported from _sqlite3. @@ -67,12 +67,12 @@ def connect( detect_types: int = ..., isolation_level: str | None = ..., check_same_thread: bool = ..., - factory: Type[Connection] | None = ..., + factory: type[Connection] | None = ..., cached_statements: int = ..., ) -> Connection: ... def enable_callback_tracebacks(__enable: bool) -> None: ... def enable_shared_cache(enable: int) -> None: ... -def register_adapter(__type: Type[_T], __caster: Callable[[_T], int | float | str | bytes]) -> None: ... +def register_adapter(__type: type[_T], __caster: Callable[[_T], int | float | str | bytes]) -> None: ... def register_converter(__name: str, __converter: Callable[[bytes], Any]) -> None: ... class Cache(object): @@ -144,8 +144,8 @@ class Cursor(Iterator[Any]): def execute(self, __sql: str, __parameters: Iterable[Any] = ...) -> Cursor: ... def executemany(self, __sql: str, __seq_of_parameters: Iterable[Iterable[Any]]) -> Cursor: ... def executescript(self, __sql_script: bytes | Text) -> Cursor: ... - def fetchall(self) -> List[Any]: ... - def fetchmany(self, size: int | None = ...) -> List[Any]: ... + def fetchall(self) -> list[Any]: ... + def fetchmany(self, size: int | None = ...) -> list[Any]: ... def fetchone(self) -> Any: ... def setinputsizes(self, *args: Any, **kwargs: Any) -> None: ... def setoutputsize(self, *args: Any, **kwargs: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/sre_compile.pyi b/mypy/typeshed/stdlib/@python2/sre_compile.pyi index efc3e568a07c..30b4d2cb628c 100644 --- a/mypy/typeshed/stdlib/@python2/sre_compile.pyi +++ b/mypy/typeshed/stdlib/@python2/sre_compile.pyi @@ -12,10 +12,10 @@ from sre_constants import ( SRE_INFO_PREFIX as SRE_INFO_PREFIX, ) from sre_parse import SubPattern -from typing import Any, List, Pattern, Tuple, Type +from typing import Any, Pattern MAXCODE: int -STRING_TYPES: Tuple[Type[str], Type[unicode]] +STRING_TYPES: tuple[type[str], type[unicode]] _IsStringType = int def isstring(obj: Any) -> _IsStringType: ... diff --git a/mypy/typeshed/stdlib/@python2/sre_constants.pyi b/mypy/typeshed/stdlib/@python2/sre_constants.pyi index bc15754d6fa1..09280512a7f4 100644 --- a/mypy/typeshed/stdlib/@python2/sre_constants.pyi +++ b/mypy/typeshed/stdlib/@python2/sre_constants.pyi @@ -1,4 +1,4 @@ -from typing import Dict, List, TypeVar +from typing import TypeVar MAGIC: int MAXREPEAT: int @@ -72,14 +72,14 @@ CATEGORY_UNI_NOT_LINEBREAK: str _T = TypeVar("_T") -def makedict(list: List[_T]) -> Dict[_T, int]: ... +def makedict(list: list[_T]) -> dict[_T, int]: ... -OP_IGNORE: Dict[str, str] -AT_MULTILINE: Dict[str, str] -AT_LOCALE: Dict[str, str] -AT_UNICODE: Dict[str, str] -CH_LOCALE: Dict[str, str] -CH_UNICODE: Dict[str, str] +OP_IGNORE: dict[str, str] +AT_MULTILINE: dict[str, str] +AT_LOCALE: dict[str, str] +AT_UNICODE: dict[str, str] +CH_LOCALE: dict[str, str] +CH_UNICODE: dict[str, str] SRE_FLAG_TEMPLATE: int SRE_FLAG_IGNORECASE: int SRE_FLAG_LOCALE: int diff --git a/mypy/typeshed/stdlib/@python2/sre_parse.pyi b/mypy/typeshed/stdlib/@python2/sre_parse.pyi index 35f6d4d32ae2..c4307bb9bb53 100644 --- a/mypy/typeshed/stdlib/@python2/sre_parse.pyi +++ b/mypy/typeshed/stdlib/@python2/sre_parse.pyi @@ -1,38 +1,38 @@ -from typing import Any, Dict, Iterable, List, Match, Optional, Pattern as _Pattern, Set, Tuple, Union +from typing import Any, Iterable, Match, Optional, Pattern as _Pattern, Union SPECIAL_CHARS: str REPEAT_CHARS: str -DIGITS: Set[Any] -OCTDIGITS: Set[Any] -HEXDIGITS: Set[Any] -WHITESPACE: Set[Any] -ESCAPES: Dict[str, Tuple[str, int]] -CATEGORIES: Dict[str, Tuple[str, str] | Tuple[str, List[Tuple[str, str]]]] -FLAGS: Dict[str, int] +DIGITS: set[Any] +OCTDIGITS: set[Any] +HEXDIGITS: set[Any] +WHITESPACE: set[Any] +ESCAPES: dict[str, tuple[str, int]] +CATEGORIES: dict[str, tuple[str, str] | tuple[str, list[tuple[str, str]]]] +FLAGS: dict[str, int] class Pattern: flags: int - open: List[int] + open: list[int] groups: int - groupdict: Dict[str, int] + groupdict: dict[str, int] lookbehind: int def __init__(self) -> None: ... def opengroup(self, name: str = ...) -> int: ... def closegroup(self, gid: int) -> None: ... def checkgroup(self, gid: int) -> bool: ... -_OpSubpatternType = Tuple[Optional[int], int, int, SubPattern] -_OpGroupRefExistsType = Tuple[int, SubPattern, SubPattern] -_OpInType = List[Tuple[str, int]] -_OpBranchType = Tuple[None, List[SubPattern]] +_OpSubpatternType = tuple[Optional[int], int, int, SubPattern] +_OpGroupRefExistsType = tuple[int, SubPattern, SubPattern] +_OpInType = list[tuple[str, int]] +_OpBranchType = tuple[None, list[SubPattern]] _AvType = Union[_OpInType, _OpBranchType, Iterable[SubPattern], _OpGroupRefExistsType, _OpSubpatternType] _CodeType = Union[str, _AvType] class SubPattern: pattern: str - data: List[_CodeType] + data: list[_CodeType] width: int | None - def __init__(self, pattern, data: List[_CodeType] = ...) -> None: ... + def __init__(self, pattern, data: list[_CodeType] = ...) -> None: ... def dump(self, level: int = ...) -> None: ... def __len__(self) -> int: ... def __delitem__(self, index: int | slice) -> None: ... @@ -48,7 +48,7 @@ class Tokenizer: def __init__(self, string: str) -> None: ... def match(self, char: str, skip: int = ...) -> int: ... def get(self) -> str | None: ... - def tell(self) -> Tuple[int, str | None]: ... + def tell(self) -> tuple[int, str | None]: ... def seek(self, index: int) -> None: ... def isident(char: str) -> bool: ... @@ -56,7 +56,7 @@ def isdigit(char: str) -> bool: ... def isname(name: str) -> bool: ... def parse(str: str, flags: int = ..., pattern: Pattern = ...) -> SubPattern: ... -_Template = Tuple[List[Tuple[int, int]], List[Optional[int]]] +_Template = tuple[list[tuple[int, int]], list[Optional[int]]] def parse_template(source: str, pattern: _Pattern[Any]) -> _Template: ... def expand_template(template: _Template, match: Match[Any]) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/ssl.pyi b/mypy/typeshed/stdlib/@python2/ssl.pyi index aabecaaba87a..67ba3bb18bdd 100644 --- a/mypy/typeshed/stdlib/@python2/ssl.pyi +++ b/mypy/typeshed/stdlib/@python2/ssl.pyi @@ -1,14 +1,14 @@ import socket import sys from _typeshed import StrPath -from typing import Any, Callable, ClassVar, Dict, Iterable, List, NamedTuple, Optional, Set, Text, Tuple, Union, overload +from typing import Any, Callable, ClassVar, Iterable, NamedTuple, Optional, Text, Union, overload from typing_extensions import Literal -_PCTRTT = Tuple[Tuple[str, str], ...] -_PCTRTTT = Tuple[_PCTRTT, ...] -_PeerCertRetDictType = Dict[str, Union[str, _PCTRTTT, _PCTRTT]] +_PCTRTT = tuple[tuple[str, str], ...] +_PCTRTTT = tuple[_PCTRTT, ...] +_PeerCertRetDictType = dict[str, Union[str, _PCTRTTT, _PCTRTT]] _PeerCertRetType = Union[_PeerCertRetDictType, bytes, None] -_EnumRetType = List[Tuple[bytes, str, Union[Set[str], bool]]] +_EnumRetType = list[tuple[bytes, str, Union[set[str], bool]]] _PasswordType = Union[Callable[[], Union[str, bytes]], str, bytes] _SC1ArgT = SSLSocket @@ -60,7 +60,7 @@ def RAND_egd(path: str) -> None: ... def RAND_add(__s: bytes, __entropy: float) -> None: ... def match_hostname(cert: _PeerCertRetType, hostname: str) -> None: ... def cert_time_to_seconds(cert_time: str) -> int: ... -def get_server_certificate(addr: Tuple[str, int], ssl_version: int = ..., ca_certs: str | None = ...) -> str: ... +def get_server_certificate(addr: tuple[str, int], ssl_version: int = ..., ca_certs: str | None = ...) -> str: ... def DER_cert_to_PEM_cert(der_cert_bytes: bytes) -> str: ... def PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: ... @@ -110,10 +110,10 @@ HAS_ALPN: bool HAS_ECDH: bool HAS_SNI: bool HAS_NPN: bool -CHANNEL_BINDING_TYPES: List[str] +CHANNEL_BINDING_TYPES: list[str] OPENSSL_VERSION: str -OPENSSL_VERSION_INFO: Tuple[int, int, int, int, int] +OPENSSL_VERSION_INFO: tuple[int, int, int, int, int] OPENSSL_VERSION_NUMBER: int ALERT_DESCRIPTION_HANDSHAKE_FAILURE: int @@ -200,12 +200,12 @@ class SSLSocket(socket.socket): def getpeercert(self, binary_form: Literal[True]) -> bytes | None: ... @overload def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ... - def cipher(self) -> Tuple[str, str, int] | None: ... + def cipher(self) -> tuple[str, str, int] | None: ... def compression(self) -> str | None: ... def get_channel_binding(self, cb_type: str = ...) -> bytes | None: ... def selected_alpn_protocol(self) -> str | None: ... def selected_npn_protocol(self) -> str | None: ... - def accept(self) -> Tuple[SSLSocket, socket._RetAddress]: ... + def accept(self) -> tuple[SSLSocket, socket._RetAddress]: ... def unwrap(self) -> socket.socket: ... def version(self) -> str | None: ... def pending(self) -> int: ... @@ -219,13 +219,13 @@ class SSLContext: verify_flags: int verify_mode: int def __init__(self, protocol: int) -> None: ... - def cert_store_stats(self) -> Dict[str, int]: ... + def cert_store_stats(self) -> dict[str, int]: ... def load_cert_chain(self, certfile: StrPath, keyfile: StrPath | None = ..., password: _PasswordType | None = ...) -> None: ... def load_default_certs(self, purpose: Purpose = ...) -> None: ... def load_verify_locations( self, cafile: StrPath | None = ..., capath: StrPath | None = ..., cadata: Text | bytes | None = ... ) -> None: ... - def get_ca_certs(self, binary_form: bool = ...) -> List[_PeerCertRetDictType] | List[bytes]: ... + def get_ca_certs(self, binary_form: bool = ...) -> list[_PeerCertRetDictType] | list[bytes]: ... def set_default_verify_paths(self) -> None: ... def set_ciphers(self, __cipherlist: str) -> None: ... def set_alpn_protocols(self, alpn_protocols: Iterable[str]) -> None: ... @@ -241,7 +241,7 @@ class SSLContext: suppress_ragged_eofs: bool = ..., server_hostname: str | None = ..., ) -> SSLSocket: ... - def session_stats(self) -> Dict[str, int]: ... + def session_stats(self) -> dict[str, int]: ... # TODO below documented in cpython but not in docs.python.org # taken from python 3.4 diff --git a/mypy/typeshed/stdlib/@python2/string.pyi b/mypy/typeshed/stdlib/@python2/string.pyi index fe028dab39bd..79fce4f893c7 100644 --- a/mypy/typeshed/stdlib/@python2/string.pyi +++ b/mypy/typeshed/stdlib/@python2/string.pyi @@ -1,4 +1,4 @@ -from typing import Any, AnyStr, Iterable, List, Mapping, Sequence, Text, Tuple, overload +from typing import Any, AnyStr, Iterable, Mapping, Sequence, Text, overload ascii_letters: str ascii_lowercase: str @@ -27,9 +27,9 @@ def index(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: .. def rindex(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... def count(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... def lower(s: AnyStr) -> AnyStr: ... -def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... -def rsplit(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... -def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> list[AnyStr]: ... +def rsplit(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> list[AnyStr]: ... +def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> list[AnyStr]: ... def join(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... def joinfields(word: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... def lstrip(s: AnyStr, chars: AnyStr = ...) -> AnyStr: ... @@ -60,7 +60,7 @@ class Template: class Formatter(object): def format(self, format_string: str, *args, **kwargs) -> str: ... def vformat(self, format_string: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> str: ... - def parse(self, format_string: str) -> Iterable[Tuple[str, str, str, str]]: ... + def parse(self, format_string: str) -> Iterable[tuple[str, str, str, str]]: ... def get_field(self, field_name: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... def get_value(self, key: int | str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ... def check_unused_args(self, used_args: Sequence[int | str], args: Sequence[Any], kwargs: Mapping[str, Any]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/stringold.pyi b/mypy/typeshed/stdlib/@python2/stringold.pyi index d221547f1c07..80402b0069e3 100644 --- a/mypy/typeshed/stdlib/@python2/stringold.pyi +++ b/mypy/typeshed/stdlib/@python2/stringold.pyi @@ -1,4 +1,4 @@ -from typing import AnyStr, Iterable, List +from typing import AnyStr, Iterable whitespace: str lowercase: str @@ -8,7 +8,7 @@ digits: str hexdigits: str octdigits: str _idmap: str -_idmapL: List[str] | None +_idmapL: list[str] | None index_error = ValueError atoi_error = ValueError atof_error = ValueError @@ -20,8 +20,8 @@ def swapcase(s: AnyStr) -> AnyStr: ... def strip(s: AnyStr) -> AnyStr: ... def lstrip(s: AnyStr) -> AnyStr: ... def rstrip(s: AnyStr) -> AnyStr: ... -def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... -def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> List[AnyStr]: ... +def split(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> list[AnyStr]: ... +def splitfields(s: AnyStr, sep: AnyStr = ..., maxsplit: int = ...) -> list[AnyStr]: ... def join(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... def joinfields(words: Iterable[AnyStr], sep: AnyStr = ...) -> AnyStr: ... def index(s: unicode, sub: unicode, start: int = ..., end: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/strop.pyi b/mypy/typeshed/stdlib/@python2/strop.pyi index 81035eaabe79..9321bbe5bf5e 100644 --- a/mypy/typeshed/stdlib/@python2/strop.pyi +++ b/mypy/typeshed/stdlib/@python2/strop.pyi @@ -1,4 +1,4 @@ -from typing import List, Sequence +from typing import Sequence lowercase: str uppercase: str @@ -19,8 +19,8 @@ def maketrans(frm: str, to: str) -> str: ... def replace(s: str, old: str, new: str, maxsplit: int = ...) -> str: ... def rfind(s: str, sub: str, start: int = ..., end: int = ...) -> int: ... def rstrip(s: str) -> str: ... -def split(s: str, sep: str, maxsplit: int = ...) -> List[str]: ... -def splitfields(s: str, sep: str, maxsplit: int = ...) -> List[str]: ... +def split(s: str, sep: str, maxsplit: int = ...) -> list[str]: ... +def splitfields(s: str, sep: str, maxsplit: int = ...) -> list[str]: ... def strip(s: str) -> str: ... def swapcase(s: str) -> str: ... def translate(s: str, table: str, deletechars: str = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/struct.pyi b/mypy/typeshed/stdlib/@python2/struct.pyi index bf27d12783da..7129fbc4cfb6 100644 --- a/mypy/typeshed/stdlib/@python2/struct.pyi +++ b/mypy/typeshed/stdlib/@python2/struct.pyi @@ -1,6 +1,6 @@ from array import array from mmap import mmap -from typing import Any, Text, Tuple, Union +from typing import Any, Text, Union class error(Exception): ... @@ -10,8 +10,8 @@ _WriteBufferType = Union[array[Any], bytearray, buffer, memoryview, mmap] def pack(fmt: _FmtType, *v: Any) -> bytes: ... def pack_into(fmt: _FmtType, buffer: _WriteBufferType, offset: int, *v: Any) -> None: ... -def unpack(__format: _FmtType, __buffer: _BufferType) -> Tuple[Any, ...]: ... -def unpack_from(__format: _FmtType, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... +def unpack(__format: _FmtType, __buffer: _BufferType) -> tuple[Any, ...]: ... +def unpack_from(__format: _FmtType, buffer: _BufferType, offset: int = ...) -> tuple[Any, ...]: ... def calcsize(__format: _FmtType) -> int: ... class Struct: @@ -20,5 +20,5 @@ class Struct: def __init__(self, format: _FmtType) -> None: ... def pack(self, *v: Any) -> bytes: ... def pack_into(self, buffer: _WriteBufferType, offset: int, *v: Any) -> None: ... - def unpack(self, __buffer: _BufferType) -> Tuple[Any, ...]: ... - def unpack_from(self, buffer: _BufferType, offset: int = ...) -> Tuple[Any, ...]: ... + def unpack(self, __buffer: _BufferType) -> tuple[Any, ...]: ... + def unpack_from(self, buffer: _BufferType, offset: int = ...) -> tuple[Any, ...]: ... diff --git a/mypy/typeshed/stdlib/@python2/subprocess.pyi b/mypy/typeshed/stdlib/@python2/subprocess.pyi index 8c101272322a..d2149c81aaaf 100644 --- a/mypy/typeshed/stdlib/@python2/subprocess.pyi +++ b/mypy/typeshed/stdlib/@python2/subprocess.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Callable, Generic, Mapping, Optional, Sequence, Text, Tuple, TypeVar, Union +from typing import IO, Any, Callable, Generic, Mapping, Optional, Sequence, Text, TypeVar, Union _FILE = Union[None, int, IO[Any]] _TXT = Union[bytes, Text] @@ -96,7 +96,7 @@ class Popen(Generic[_T]): def poll(self) -> int | None: ... def wait(self) -> int: ... # morally: -> Tuple[Optional[bytes], Optional[bytes]] - def communicate(self, input: _TXT | None = ...) -> Tuple[bytes, bytes]: ... + def communicate(self, input: _TXT | None = ...) -> tuple[bytes, bytes]: ... def send_signal(self, signal: int) -> None: ... def terminate(self) -> None: ... def kill(self) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/sunau.pyi b/mypy/typeshed/stdlib/@python2/sunau.pyi index 3ee4b9651346..6d5caee7b199 100644 --- a/mypy/typeshed/stdlib/@python2/sunau.pyi +++ b/mypy/typeshed/stdlib/@python2/sunau.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, NoReturn, Text, Tuple, Union +from typing import IO, Any, NoReturn, Text, Union _File = Union[Text, IO[bytes]] @@ -19,7 +19,7 @@ AUDIO_FILE_ENCODING_ADPCM_G723_5: int AUDIO_FILE_ENCODING_ALAW_8: int AUDIO_UNKNOWN_SIZE: int -_sunau_params = Tuple[int, int, int, int, str, str] +_sunau_params = tuple[int, int, int, int, str, str] class Au_read: def __init__(self, f: _File) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/symbol.pyi b/mypy/typeshed/stdlib/@python2/symbol.pyi index a3561fe6b26f..052e3f1f8f42 100644 --- a/mypy/typeshed/stdlib/@python2/symbol.pyi +++ b/mypy/typeshed/stdlib/@python2/symbol.pyi @@ -1,5 +1,3 @@ -from typing import Dict - single_input: int file_input: int eval_input: int @@ -86,4 +84,4 @@ testlist1: int encoding_decl: int yield_expr: int -sym_name: Dict[int, str] +sym_name: dict[int, str] diff --git a/mypy/typeshed/stdlib/@python2/symtable.pyi b/mypy/typeshed/stdlib/@python2/symtable.pyi index bd3f25c7cb63..c0b701cc1df5 100644 --- a/mypy/typeshed/stdlib/@python2/symtable.pyi +++ b/mypy/typeshed/stdlib/@python2/symtable.pyi @@ -1,4 +1,4 @@ -from typing import Any, List, Sequence, Text, Tuple +from typing import Any, Sequence, Text def symtable(code: Text, filename: Text, compile_type: Text) -> SymbolTable: ... @@ -15,17 +15,17 @@ class SymbolTable(object): def has_import_star(self) -> bool: ... def get_identifiers(self) -> Sequence[str]: ... def lookup(self, name: str) -> Symbol: ... - def get_symbols(self) -> List[Symbol]: ... - def get_children(self) -> List[SymbolTable]: ... + def get_symbols(self) -> list[Symbol]: ... + def get_children(self) -> list[SymbolTable]: ... class Function(SymbolTable): - def get_parameters(self) -> Tuple[str, ...]: ... - def get_locals(self) -> Tuple[str, ...]: ... - def get_globals(self) -> Tuple[str, ...]: ... - def get_frees(self) -> Tuple[str, ...]: ... + def get_parameters(self) -> tuple[str, ...]: ... + def get_locals(self) -> tuple[str, ...]: ... + def get_globals(self) -> tuple[str, ...]: ... + def get_frees(self) -> tuple[str, ...]: ... class Class(SymbolTable): - def get_methods(self) -> Tuple[str, ...]: ... + def get_methods(self) -> tuple[str, ...]: ... class Symbol(object): def __init__(self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/sys.pyi b/mypy/typeshed/stdlib/@python2/sys.pyi index d4858ec251fa..409b776cdcb0 100644 --- a/mypy/typeshed/stdlib/@python2/sys.pyi +++ b/mypy/typeshed/stdlib/@python2/sys.pyi @@ -1,9 +1,9 @@ from types import ClassType, FrameType, TracebackType -from typing import IO, Any, Callable, Dict, List, NoReturn, Text, Tuple, Type, Union +from typing import IO, Any, Callable, NoReturn, Text, Union # The following type alias are stub-only and do not exist during runtime -_ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] -_OptExcInfo = Union[_ExcInfo, Tuple[None, None, None]] +_ExcInfo = tuple[type[BaseException], BaseException, TracebackType] +_OptExcInfo = Union[_ExcInfo, tuple[None, None, None]] class _flags: bytes_warning: int @@ -36,17 +36,17 @@ class _float_info: radix: int rounds: int -class _version_info(Tuple[int, int, int, str, int]): +class _version_info(tuple[int, int, int, str, int]): major: int minor: int micro: int releaselevel: str serial: int -_mercurial: Tuple[str, str, str] +_mercurial: tuple[str, str, str] api_version: int -argv: List[str] -builtin_module_names: Tuple[str, ...] +argv: list[str] +builtin_module_names: tuple[str, ...] byteorder: str copyright: str dont_write_bytecode: bool @@ -59,8 +59,8 @@ long_info: object maxint: int maxsize: int maxunicode: int -modules: Dict[str, Any] -path: List[str] +modules: dict[str, Any] +path: list[str] platform: str prefix: str py3kwarning: bool @@ -70,7 +70,7 @@ __stdout__: IO[str] stderr: IO[str] stdin: IO[str] stdout: IO[str] -subversion: Tuple[str, str, str] +subversion: tuple[str, str, str] version: str warnoptions: object float_info: _float_info @@ -81,11 +81,11 @@ last_type: type last_value: BaseException last_traceback: TracebackType # TODO precise types -meta_path: List[Any] -path_hooks: List[Any] -path_importer_cache: Dict[str, Any] +meta_path: list[Any] +path_hooks: list[Any] +path_importer_cache: dict[str, Any] displayhook: Callable[[object], Any] -excepthook: Callable[[Type[BaseException], BaseException, TracebackType], Any] +excepthook: Callable[[type[BaseException], BaseException, TracebackType], Any] exc_type: type | None exc_value: BaseException | ClassType exc_traceback: TracebackType @@ -103,7 +103,7 @@ class _WindowsVersionType: def getwindowsversion() -> _WindowsVersionType: ... def _clear_type_cache() -> None: ... -def _current_frames() -> Dict[int, FrameType]: ... +def _current_frames() -> dict[int, FrameType]: ... def _getframe(depth: int = ...) -> FrameType: ... def call_tracing(fn: Any, args: Any) -> Any: ... def __displayhook__(value: object) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/sysconfig.pyi b/mypy/typeshed/stdlib/@python2/sysconfig.pyi index 2bef9e467bc9..17077144f6e9 100644 --- a/mypy/typeshed/stdlib/@python2/sysconfig.pyi +++ b/mypy/typeshed/stdlib/@python2/sysconfig.pyi @@ -1,17 +1,17 @@ -from typing import IO, Any, Dict, List, Tuple, overload +from typing import IO, Any, overload def get_config_var(name: str) -> str | None: ... @overload -def get_config_vars() -> Dict[str, Any]: ... +def get_config_vars() -> dict[str, Any]: ... @overload -def get_config_vars(arg: str, *args: str) -> List[Any]: ... -def get_scheme_names() -> Tuple[str, ...]: ... -def get_path_names() -> Tuple[str, ...]: ... -def get_path(name: str, scheme: str = ..., vars: Dict[str, Any] | None = ..., expand: bool = ...) -> str: ... -def get_paths(scheme: str = ..., vars: Dict[str, Any] | None = ..., expand: bool = ...) -> Dict[str, str]: ... +def get_config_vars(arg: str, *args: str) -> list[Any]: ... +def get_scheme_names() -> tuple[str, ...]: ... +def get_path_names() -> tuple[str, ...]: ... +def get_path(name: str, scheme: str = ..., vars: dict[str, Any] | None = ..., expand: bool = ...) -> str: ... +def get_paths(scheme: str = ..., vars: dict[str, Any] | None = ..., expand: bool = ...) -> dict[str, str]: ... def get_python_version() -> str: ... def get_platform() -> str: ... def is_python_build(check_home: bool = ...) -> bool: ... -def parse_config_h(fp: IO[Any], vars: Dict[str, Any] | None = ...) -> Dict[str, Any]: ... +def parse_config_h(fp: IO[Any], vars: dict[str, Any] | None = ...) -> dict[str, Any]: ... def get_config_h_filename() -> str: ... def get_makefile_filename() -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/syslog.pyi b/mypy/typeshed/stdlib/@python2/syslog.pyi index 49169f40db5c..eaeeb7715e48 100644 --- a/mypy/typeshed/stdlib/@python2/syslog.pyi +++ b/mypy/typeshed/stdlib/@python2/syslog.pyi @@ -1,43 +1,44 @@ +import sys from typing import overload -LOG_ALERT: int -LOG_AUTH: int -LOG_CONS: int -LOG_CRIT: int -LOG_CRON: int -LOG_DAEMON: int -LOG_DEBUG: int -LOG_EMERG: int -LOG_ERR: int -LOG_INFO: int -LOG_KERN: int -LOG_LOCAL0: int -LOG_LOCAL1: int -LOG_LOCAL2: int -LOG_LOCAL3: int -LOG_LOCAL4: int -LOG_LOCAL5: int -LOG_LOCAL6: int -LOG_LOCAL7: int -LOG_LPR: int -LOG_MAIL: int -LOG_NDELAY: int -LOG_NEWS: int -LOG_NOTICE: int -LOG_NOWAIT: int -LOG_PERROR: int -LOG_PID: int -LOG_SYSLOG: int -LOG_USER: int -LOG_UUCP: int -LOG_WARNING: int - -def LOG_MASK(a: int) -> int: ... -def LOG_UPTO(a: int) -> int: ... -def closelog() -> None: ... -def openlog(ident: str = ..., logoption: int = ..., facility: int = ...) -> None: ... -def setlogmask(x: int) -> int: ... -@overload -def syslog(priority: int, message: str) -> None: ... -@overload -def syslog(message: str) -> None: ... +if sys.platform != "win32": + LOG_ALERT: int + LOG_AUTH: int + LOG_CONS: int + LOG_CRIT: int + LOG_CRON: int + LOG_DAEMON: int + LOG_DEBUG: int + LOG_EMERG: int + LOG_ERR: int + LOG_INFO: int + LOG_KERN: int + LOG_LOCAL0: int + LOG_LOCAL1: int + LOG_LOCAL2: int + LOG_LOCAL3: int + LOG_LOCAL4: int + LOG_LOCAL5: int + LOG_LOCAL6: int + LOG_LOCAL7: int + LOG_LPR: int + LOG_MAIL: int + LOG_NDELAY: int + LOG_NEWS: int + LOG_NOTICE: int + LOG_NOWAIT: int + LOG_PERROR: int + LOG_PID: int + LOG_SYSLOG: int + LOG_USER: int + LOG_UUCP: int + LOG_WARNING: int + def LOG_MASK(a: int) -> int: ... + def LOG_UPTO(a: int) -> int: ... + def closelog() -> None: ... + def openlog(ident: str = ..., logoption: int = ..., facility: int = ...) -> None: ... + def setlogmask(x: int) -> int: ... + @overload + def syslog(priority: int, message: str) -> None: ... + @overload + def syslog(message: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/tabnanny.pyi b/mypy/typeshed/stdlib/@python2/tabnanny.pyi index 95873761ee75..cf6eefc2e15f 100644 --- a/mypy/typeshed/stdlib/@python2/tabnanny.pyi +++ b/mypy/typeshed/stdlib/@python2/tabnanny.pyi @@ -1,4 +1,4 @@ -from typing import Iterable, Text, Tuple +from typing import Iterable, Text verbose: int filename_only: int @@ -10,4 +10,4 @@ class NannyNag(Exception): def get_line(self) -> str: ... def check(file: Text) -> None: ... -def process_tokens(tokens: Iterable[Tuple[int, str, Tuple[int, int], Tuple[int, int], str]]) -> None: ... +def process_tokens(tokens: Iterable[tuple[int, str, tuple[int, int], tuple[int, int], str]]) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/tarfile.pyi b/mypy/typeshed/stdlib/@python2/tarfile.pyi index c08c96b6f0d5..4f1efe5e4070 100644 --- a/mypy/typeshed/stdlib/@python2/tarfile.pyi +++ b/mypy/typeshed/stdlib/@python2/tarfile.pyi @@ -1,6 +1,6 @@ import io from types import TracebackType -from typing import IO, Callable, Dict, Iterable, Iterator, List, Mapping, Text, Tuple, Type +from typing import IO, Callable, Iterable, Iterator, Mapping, Text # tar constants NUL: bytes @@ -38,11 +38,11 @@ DEFAULT_FORMAT: int # tarfile constants -SUPPORTED_TYPES: Tuple[bytes, ...] -REGULAR_TYPES: Tuple[bytes, ...] -GNU_TYPES: Tuple[bytes, ...] -PAX_FIELDS: Tuple[str, ...] -PAX_NUMBER_FIELDS: Dict[str, type] +SUPPORTED_TYPES: tuple[bytes, ...] +REGULAR_TYPES: tuple[bytes, ...] +GNU_TYPES: tuple[bytes, ...] +PAX_FIELDS: tuple[str, ...] +PAX_NUMBER_FIELDS: dict[str, type] ENCODING: str @@ -56,7 +56,7 @@ def open( bufsize: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -76,12 +76,12 @@ class TarFile(Iterable[TarInfo]): mode: str fileobj: IO[bytes] | None format: int | None - tarinfo: Type[TarInfo] + tarinfo: type[TarInfo] dereference: bool | None ignore_zeros: bool | None encoding: str | None errors: str - fileobject: Type[ExFileObject] + fileobject: type[ExFileObject] pax_headers: Mapping[str, str] | None debug: int | None errorlevel: int | None @@ -93,7 +93,7 @@ class TarFile(Iterable[TarInfo]): mode: str = ..., fileobj: IO[bytes] | None = ..., format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -105,7 +105,7 @@ class TarFile(Iterable[TarInfo]): ) -> None: ... def __enter__(self) -> TarFile: ... 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 __iter__(self) -> Iterator[TarInfo]: ... @classmethod @@ -117,7 +117,7 @@ class TarFile(Iterable[TarInfo]): bufsize: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -135,7 +135,7 @@ class TarFile(Iterable[TarInfo]): *, compresslevel: int = ..., format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -152,7 +152,7 @@ class TarFile(Iterable[TarInfo]): compresslevel: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -169,7 +169,7 @@ class TarFile(Iterable[TarInfo]): compresslevel: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -186,7 +186,7 @@ class TarFile(Iterable[TarInfo]): preset: int | None = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -195,8 +195,8 @@ class TarFile(Iterable[TarInfo]): errorlevel: int | None = ..., ) -> TarFile: ... def getmember(self, name: str) -> TarInfo: ... - def getmembers(self) -> List[TarInfo]: ... - def getnames(self) -> List[str]: ... + def getmembers(self) -> list[TarInfo]: ... + def getnames(self) -> list[str]: ... def list(self, verbose: bool = ...) -> None: ... def next(self) -> TarInfo | None: ... def extractall(self, path: Text = ..., members: Iterable[TarInfo] | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/telnetlib.pyi b/mypy/typeshed/stdlib/@python2/telnetlib.pyi index dfb01f26398e..5cd47e28a95c 100644 --- a/mypy/typeshed/stdlib/@python2/telnetlib.pyi +++ b/mypy/typeshed/stdlib/@python2/telnetlib.pyi @@ -1,5 +1,5 @@ import socket -from typing import Any, Callable, Match, Pattern, Sequence, Tuple +from typing import Any, Callable, Match, Pattern, Sequence DEBUGLEVEL: int TELNET_PORT: int @@ -108,4 +108,4 @@ class Telnet: def listener(self) -> None: ... def expect( self, list: Sequence[Pattern[bytes] | bytes], timeout: float | None = ... - ) -> Tuple[int, Match[bytes] | None, bytes]: ... + ) -> tuple[int, Match[bytes] | None, bytes]: ... diff --git a/mypy/typeshed/stdlib/@python2/tempfile.pyi b/mypy/typeshed/stdlib/@python2/tempfile.pyi index c5f67d243ac8..25397d130165 100644 --- a/mypy/typeshed/stdlib/@python2/tempfile.pyi +++ b/mypy/typeshed/stdlib/@python2/tempfile.pyi @@ -1,6 +1,6 @@ from random import Random from thread import LockType -from typing import IO, Any, AnyStr, Iterable, Iterator, List, Text, Tuple, overload +from typing import IO, Any, AnyStr, Iterable, Iterator, Text, overload TMP_MAX: int tempdir: str @@ -39,7 +39,7 @@ class _TemporaryFileWrapper(IO[str]): def read(self, n: int = ...) -> str: ... def readable(self) -> bool: ... def readline(self, limit: int = ...) -> str: ... - def readlines(self, hint: int = ...) -> List[str]: ... + def readlines(self, hint: int = ...) -> list[str]: ... def seek(self, offset: int, whence: int = ...) -> int: ... def seekable(self) -> bool: ... def tell(self) -> int: ... @@ -82,9 +82,9 @@ class TemporaryDirectory: def __exit__(self, type, value, traceback) -> None: ... @overload -def mkstemp() -> Tuple[int, str]: ... +def mkstemp() -> tuple[int, str]: ... @overload -def mkstemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: AnyStr | None = ..., text: bool = ...) -> Tuple[int, AnyStr]: ... +def mkstemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: AnyStr | None = ..., text: bool = ...) -> tuple[int, AnyStr]: ... @overload def mkdtemp() -> str: ... @overload @@ -95,6 +95,6 @@ def mktemp() -> str: ... def mktemp(suffix: AnyStr = ..., prefix: AnyStr = ..., dir: AnyStr | None = ...) -> AnyStr: ... def gettempdir() -> str: ... def gettempprefix() -> str: ... -def _candidate_tempdir_list() -> List[str]: ... +def _candidate_tempdir_list() -> list[str]: ... def _get_candidate_names() -> _RandomNameSequence | None: ... def _get_default_tempdir() -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/termios.pyi b/mypy/typeshed/stdlib/@python2/termios.pyi index 0c627f4b72bd..7142df15715d 100644 --- a/mypy/typeshed/stdlib/@python2/termios.pyi +++ b/mypy/typeshed/stdlib/@python2/termios.pyi @@ -1,246 +1,246 @@ +import sys from _typeshed import FileDescriptorLike -from typing import Any, List, Union +from typing import Any, Union -_Attr = List[Union[int, List[Union[bytes, int]]]] +if sys.platform != "win32": + _Attr = list[Union[int, list[Union[bytes, int]]]] -# TODO constants not really documented -B0: int -B1000000: int -B110: int -B115200: int -B1152000: int -B1200: int -B134: int -B150: int -B1500000: int -B1800: int -B19200: int -B200: int -B2000000: int -B230400: int -B2400: int -B2500000: int -B300: int -B3000000: int -B3500000: int -B38400: int -B4000000: int -B460800: int -B4800: int -B50: int -B500000: int -B57600: int -B576000: int -B600: int -B75: int -B921600: int -B9600: int -BRKINT: int -BS0: int -BS1: int -BSDLY: int -CBAUD: int -CBAUDEX: int -CDSUSP: int -CEOF: int -CEOL: int -CEOT: int -CERASE: int -CFLUSH: int -CIBAUD: int -CINTR: int -CKILL: int -CLNEXT: int -CLOCAL: int -CQUIT: int -CR0: int -CR1: int -CR2: int -CR3: int -CRDLY: int -CREAD: int -CRPRNT: int -CRTSCTS: int -CS5: int -CS6: int -CS7: int -CS8: int -CSIZE: int -CSTART: int -CSTOP: int -CSTOPB: int -CSUSP: int -CWERASE: int -ECHO: int -ECHOCTL: int -ECHOE: int -ECHOK: int -ECHOKE: int -ECHONL: int -ECHOPRT: int -EXTA: int -EXTB: int -FF0: int -FF1: int -FFDLY: int -FIOASYNC: int -FIOCLEX: int -FIONBIO: int -FIONCLEX: int -FIONREAD: int -FLUSHO: int -HUPCL: int -ICANON: int -ICRNL: int -IEXTEN: int -IGNBRK: int -IGNCR: int -IGNPAR: int -IMAXBEL: int -INLCR: int -INPCK: int -IOCSIZE_MASK: int -IOCSIZE_SHIFT: int -ISIG: int -ISTRIP: int -IUCLC: int -IXANY: int -IXOFF: int -IXON: int -NCC: int -NCCS: int -NL0: int -NL1: int -NLDLY: int -NOFLSH: int -N_MOUSE: int -N_PPP: int -N_SLIP: int -N_STRIP: int -N_TTY: int -OCRNL: int -OFDEL: int -OFILL: int -OLCUC: int -ONLCR: int -ONLRET: int -ONOCR: int -OPOST: int -PARENB: int -PARMRK: int -PARODD: int -PENDIN: int -TAB0: int -TAB1: int -TAB2: int -TAB3: int -TABDLY: int -TCFLSH: int -TCGETA: int -TCGETS: int -TCIFLUSH: int -TCIOFF: int -TCIOFLUSH: int -TCION: int -TCOFLUSH: int -TCOOFF: int -TCOON: int -TCSADRAIN: int -TCSAFLUSH: int -TCSANOW: int -TCSBRK: int -TCSBRKP: int -TCSETA: int -TCSETAF: int -TCSETAW: int -TCSETS: int -TCSETSF: int -TCSETSW: int -TCXONC: int -TIOCCONS: int -TIOCEXCL: int -TIOCGETD: int -TIOCGICOUNT: int -TIOCGLCKTRMIOS: int -TIOCGPGRP: int -TIOCGSERIAL: int -TIOCGSOFTCAR: int -TIOCGWINSZ: int -TIOCINQ: int -TIOCLINUX: int -TIOCMBIC: int -TIOCMBIS: int -TIOCMGET: int -TIOCMIWAIT: int -TIOCMSET: int -TIOCM_CAR: int -TIOCM_CD: int -TIOCM_CTS: int -TIOCM_DSR: int -TIOCM_DTR: int -TIOCM_LE: int -TIOCM_RI: int -TIOCM_RNG: int -TIOCM_RTS: int -TIOCM_SR: int -TIOCM_ST: int -TIOCNOTTY: int -TIOCNXCL: int -TIOCOUTQ: int -TIOCPKT: int -TIOCPKT_DATA: int -TIOCPKT_DOSTOP: int -TIOCPKT_FLUSHREAD: int -TIOCPKT_FLUSHWRITE: int -TIOCPKT_NOSTOP: int -TIOCPKT_START: int -TIOCPKT_STOP: int -TIOCSCTTY: int -TIOCSERCONFIG: int -TIOCSERGETLSR: int -TIOCSERGETMULTI: int -TIOCSERGSTRUCT: int -TIOCSERGWILD: int -TIOCSERSETMULTI: int -TIOCSERSWILD: int -TIOCSER_TEMT: int -TIOCSETD: int -TIOCSLCKTRMIOS: int -TIOCSPGRP: int -TIOCSSERIAL: int -TIOCSSOFTCAR: int -TIOCSTI: int -TIOCSWINSZ: int -TOSTOP: int -VDISCARD: int -VEOF: int -VEOL: int -VEOL2: int -VERASE: int -VINTR: int -VKILL: int -VLNEXT: int -VMIN: int -VQUIT: int -VREPRINT: int -VSTART: int -VSTOP: int -VSUSP: int -VSWTC: int -VSWTCH: int -VT0: int -VT1: int -VTDLY: int -VTIME: int -VWERASE: int -XCASE: int -XTABS: int - -def tcgetattr(__fd: FileDescriptorLike) -> List[Any]: ... -def tcsetattr(__fd: FileDescriptorLike, __when: int, __attributes: _Attr) -> None: ... -def tcsendbreak(__fd: FileDescriptorLike, __duration: int) -> None: ... -def tcdrain(__fd: FileDescriptorLike) -> None: ... -def tcflush(__fd: FileDescriptorLike, __queue: int) -> None: ... -def tcflow(__fd: FileDescriptorLike, __action: int) -> None: ... - -class error(Exception): ... + # TODO constants not really documented + B0: int + B1000000: int + B110: int + B115200: int + B1152000: int + B1200: int + B134: int + B150: int + B1500000: int + B1800: int + B19200: int + B200: int + B2000000: int + B230400: int + B2400: int + B2500000: int + B300: int + B3000000: int + B3500000: int + B38400: int + B4000000: int + B460800: int + B4800: int + B50: int + B500000: int + B57600: int + B576000: int + B600: int + B75: int + B921600: int + B9600: int + BRKINT: int + BS0: int + BS1: int + BSDLY: int + CBAUD: int + CBAUDEX: int + CDSUSP: int + CEOF: int + CEOL: int + CEOT: int + CERASE: int + CFLUSH: int + CIBAUD: int + CINTR: int + CKILL: int + CLNEXT: int + CLOCAL: int + CQUIT: int + CR0: int + CR1: int + CR2: int + CR3: int + CRDLY: int + CREAD: int + CRPRNT: int + CRTSCTS: int + CS5: int + CS6: int + CS7: int + CS8: int + CSIZE: int + CSTART: int + CSTOP: int + CSTOPB: int + CSUSP: int + CWERASE: int + ECHO: int + ECHOCTL: int + ECHOE: int + ECHOK: int + ECHOKE: int + ECHONL: int + ECHOPRT: int + EXTA: int + EXTB: int + FF0: int + FF1: int + FFDLY: int + FIOASYNC: int + FIOCLEX: int + FIONBIO: int + FIONCLEX: int + FIONREAD: int + FLUSHO: int + HUPCL: int + ICANON: int + ICRNL: int + IEXTEN: int + IGNBRK: int + IGNCR: int + IGNPAR: int + IMAXBEL: int + INLCR: int + INPCK: int + IOCSIZE_MASK: int + IOCSIZE_SHIFT: int + ISIG: int + ISTRIP: int + IUCLC: int + IXANY: int + IXOFF: int + IXON: int + NCC: int + NCCS: int + NL0: int + NL1: int + NLDLY: int + NOFLSH: int + N_MOUSE: int + N_PPP: int + N_SLIP: int + N_STRIP: int + N_TTY: int + OCRNL: int + OFDEL: int + OFILL: int + OLCUC: int + ONLCR: int + ONLRET: int + ONOCR: int + OPOST: int + PARENB: int + PARMRK: int + PARODD: int + PENDIN: int + TAB0: int + TAB1: int + TAB2: int + TAB3: int + TABDLY: int + TCFLSH: int + TCGETA: int + TCGETS: int + TCIFLUSH: int + TCIOFF: int + TCIOFLUSH: int + TCION: int + TCOFLUSH: int + TCOOFF: int + TCOON: int + TCSADRAIN: int + TCSAFLUSH: int + TCSANOW: int + TCSBRK: int + TCSBRKP: int + TCSETA: int + TCSETAF: int + TCSETAW: int + TCSETS: int + TCSETSF: int + TCSETSW: int + TCXONC: int + TIOCCONS: int + TIOCEXCL: int + TIOCGETD: int + TIOCGICOUNT: int + TIOCGLCKTRMIOS: int + TIOCGPGRP: int + TIOCGSERIAL: int + TIOCGSOFTCAR: int + TIOCGWINSZ: int + TIOCINQ: int + TIOCLINUX: int + TIOCMBIC: int + TIOCMBIS: int + TIOCMGET: int + TIOCMIWAIT: int + TIOCMSET: int + TIOCM_CAR: int + TIOCM_CD: int + TIOCM_CTS: int + TIOCM_DSR: int + TIOCM_DTR: int + TIOCM_LE: int + TIOCM_RI: int + TIOCM_RNG: int + TIOCM_RTS: int + TIOCM_SR: int + TIOCM_ST: int + TIOCNOTTY: int + TIOCNXCL: int + TIOCOUTQ: int + TIOCPKT: int + TIOCPKT_DATA: int + TIOCPKT_DOSTOP: int + TIOCPKT_FLUSHREAD: int + TIOCPKT_FLUSHWRITE: int + TIOCPKT_NOSTOP: int + TIOCPKT_START: int + TIOCPKT_STOP: int + TIOCSCTTY: int + TIOCSERCONFIG: int + TIOCSERGETLSR: int + TIOCSERGETMULTI: int + TIOCSERGSTRUCT: int + TIOCSERGWILD: int + TIOCSERSETMULTI: int + TIOCSERSWILD: int + TIOCSER_TEMT: int + TIOCSETD: int + TIOCSLCKTRMIOS: int + TIOCSPGRP: int + TIOCSSERIAL: int + TIOCSSOFTCAR: int + TIOCSTI: int + TIOCSWINSZ: int + TOSTOP: int + VDISCARD: int + VEOF: int + VEOL: int + VEOL2: int + VERASE: int + VINTR: int + VKILL: int + VLNEXT: int + VMIN: int + VQUIT: int + VREPRINT: int + VSTART: int + VSTOP: int + VSUSP: int + VSWTC: int + VSWTCH: int + VT0: int + VT1: int + VTDLY: int + VTIME: int + VWERASE: int + XCASE: int + XTABS: int + def tcgetattr(__fd: FileDescriptorLike) -> list[Any]: ... + def tcsetattr(__fd: FileDescriptorLike, __when: int, __attributes: _Attr) -> None: ... + def tcsendbreak(__fd: FileDescriptorLike, __duration: int) -> None: ... + def tcdrain(__fd: FileDescriptorLike) -> None: ... + def tcflush(__fd: FileDescriptorLike, __queue: int) -> None: ... + def tcflow(__fd: FileDescriptorLike, __action: int) -> None: ... + class error(Exception): ... diff --git a/mypy/typeshed/stdlib/@python2/textwrap.pyi b/mypy/typeshed/stdlib/@python2/textwrap.pyi index c4147b4bd538..cb9c034cc4ba 100644 --- a/mypy/typeshed/stdlib/@python2/textwrap.pyi +++ b/mypy/typeshed/stdlib/@python2/textwrap.pyi @@ -1,4 +1,4 @@ -from typing import AnyStr, Dict, List, Pattern +from typing import AnyStr, Pattern class TextWrapper(object): width: int = ... @@ -16,7 +16,7 @@ class TextWrapper(object): wordsep_re: Pattern[str] = ... wordsep_simple_re: Pattern[str] = ... whitespace_trans: str = ... - unicode_whitespace_trans: Dict[int, int] = ... + unicode_whitespace_trans: dict[int, int] = ... uspace: int = ... x: int = ... def __init__( @@ -31,7 +31,7 @@ class TextWrapper(object): drop_whitespace: bool = ..., break_on_hyphens: bool = ..., ) -> None: ... - def wrap(self, text: AnyStr) -> List[AnyStr]: ... + def wrap(self, text: AnyStr) -> list[AnyStr]: ... def fill(self, text: AnyStr) -> AnyStr: ... def wrap( @@ -45,7 +45,7 @@ def wrap( break_long_words: bool = ..., drop_whitespace: bool = ..., break_on_hyphens: bool = ..., -) -> List[AnyStr]: ... +) -> list[AnyStr]: ... def fill( text: AnyStr, width: int = ..., diff --git a/mypy/typeshed/stdlib/@python2/this.pyi b/mypy/typeshed/stdlib/@python2/this.pyi index 0687a6675cca..8de996b04aec 100644 --- a/mypy/typeshed/stdlib/@python2/this.pyi +++ b/mypy/typeshed/stdlib/@python2/this.pyi @@ -1,4 +1,2 @@ -from typing import Dict - s: str -d: Dict[str, str] +d: dict[str, str] diff --git a/mypy/typeshed/stdlib/@python2/threading.pyi b/mypy/typeshed/stdlib/@python2/threading.pyi index e45a1b5c4a89..5f66360bff6c 100644 --- a/mypy/typeshed/stdlib/@python2/threading.pyi +++ b/mypy/typeshed/stdlib/@python2/threading.pyi @@ -1,19 +1,18 @@ from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, List, Mapping, Optional, Text, Type, TypeVar +from typing import Any, Callable, Iterable, Mapping, Optional, Text, TypeVar # TODO recursive type _TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] _PF = Callable[[FrameType, str, Any], None] -_T = TypeVar("_T") -__all__: List[str] +__all__: list[str] def active_count() -> int: ... def activeCount() -> int: ... def current_thread() -> Thread: ... def currentThread() -> Thread: ... -def enumerate() -> List[Thread]: ... +def enumerate() -> list[Thread]: ... def settrace(func: _TF) -> None: ... def setprofile(func: _PF | None) -> None: ... def stack_size(size: int = ...) -> int: ... @@ -53,7 +52,7 @@ class Lock: def __init__(self) -> None: ... def __enter__(self) -> bool: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def release(self) -> None: ... @@ -63,7 +62,7 @@ class _RLock: def __init__(self) -> None: ... def __enter__(self) -> bool: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def release(self) -> None: ... @@ -74,7 +73,7 @@ class Condition: def __init__(self, lock: Lock | _RLock | None = ...) -> None: ... def __enter__(self) -> bool: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def release(self) -> None: ... @@ -86,7 +85,7 @@ class Condition: class Semaphore: def __init__(self, value: int = ...) -> None: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ...) -> bool: ... def __enter__(self, blocking: bool = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/time.pyi b/mypy/typeshed/stdlib/@python2/time.pyi index 48ae9da9c65e..cbe5d63017b0 100644 --- a/mypy/typeshed/stdlib/@python2/time.pyi +++ b/mypy/typeshed/stdlib/@python2/time.pyi @@ -1,13 +1,13 @@ import sys -from typing import Any, NamedTuple, Tuple +from typing import Any, NamedTuple -_TimeTuple = Tuple[int, int, int, int, int, int, int, int, int] +_TimeTuple = tuple[int, int, int, int, int, int, int, int, int] accept2dyear: bool altzone: int daylight: int timezone: int -tzname: Tuple[str, str] +tzname: tuple[str, str] class _struct_time(NamedTuple): tm_year: int diff --git a/mypy/typeshed/stdlib/@python2/timeit.pyi b/mypy/typeshed/stdlib/@python2/timeit.pyi index ecb528725a9c..3a7f6e0e0841 100644 --- a/mypy/typeshed/stdlib/@python2/timeit.pyi +++ b/mypy/typeshed/stdlib/@python2/timeit.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, Callable, List, Sequence, Text, Union +from typing import IO, Any, Callable, Sequence, Text, Union _str = Union[str, Text] _Timer = Callable[[], float] @@ -10,10 +10,10 @@ class Timer: def __init__(self, stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ...) -> None: ... def print_exc(self, file: IO[str] | None = ...) -> None: ... def timeit(self, number: int = ...) -> float: ... - def repeat(self, repeat: int = ..., number: int = ...) -> List[float]: ... + def repeat(self, repeat: int = ..., number: int = ...) -> list[float]: ... def timeit(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., number: int = ...) -> float: ... -def repeat(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., repeat: int = ..., number: int = ...) -> List[float]: ... +def repeat(stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., repeat: int = ..., number: int = ...) -> list[float]: ... _timerFunc = Callable[[], float] diff --git a/mypy/typeshed/stdlib/@python2/toaiff.pyi b/mypy/typeshed/stdlib/@python2/toaiff.pyi index b70e026d6d8e..d4b86f9bb756 100644 --- a/mypy/typeshed/stdlib/@python2/toaiff.pyi +++ b/mypy/typeshed/stdlib/@python2/toaiff.pyi @@ -1,11 +1,10 @@ from pipes import Template -from typing import Dict, List -table: Dict[str, Template] +table: dict[str, Template] t: Template uncompress: Template class error(Exception): ... def toaiff(filename: str) -> str: ... -def _toaiff(filename: str, temps: List[str]) -> str: ... +def _toaiff(filename: str, temps: list[str]) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/token.pyi b/mypy/typeshed/stdlib/@python2/token.pyi index 4ba710470624..d88aba8678a0 100644 --- a/mypy/typeshed/stdlib/@python2/token.pyi +++ b/mypy/typeshed/stdlib/@python2/token.pyi @@ -1,5 +1,3 @@ -from typing import Dict - ENDMARKER: int NAME: int NUMBER: int @@ -55,7 +53,7 @@ OP: int ERRORTOKEN: int N_TOKENS: int NT_OFFSET: int -tok_name: Dict[int, str] +tok_name: dict[int, str] def ISTERMINAL(x: int) -> bool: ... def ISNONTERMINAL(x: int) -> bool: ... diff --git a/mypy/typeshed/stdlib/@python2/tokenize.pyi b/mypy/typeshed/stdlib/@python2/tokenize.pyi index 98ec01a6cb75..f045f76cc39e 100644 --- a/mypy/typeshed/stdlib/@python2/tokenize.pyi +++ b/mypy/typeshed/stdlib/@python2/tokenize.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Dict, Generator, Iterable, Iterator, List, Tuple +from typing import Any, Callable, Generator, Iterable, Iterator __author__: str __credits__: str @@ -97,27 +97,27 @@ VBAREQUAL: int Whitespace: str chain: type double3prog: type -endprogs: Dict[str, Any] +endprogs: dict[str, Any] pseudoprog: type single3prog: type -single_quoted: Dict[str, str] +single_quoted: dict[str, str] t: str tabsize: int -tok_name: Dict[int, str] +tok_name: dict[int, str] tokenprog: type -triple_quoted: Dict[str, str] +triple_quoted: dict[str, str] x: str -_Pos = Tuple[int, int] -_TokenType = Tuple[int, str, _Pos, _Pos, str] +_Pos = tuple[int, int] +_TokenType = tuple[int, str, _Pos, _Pos, str] def any(*args, **kwargs) -> str: ... def generate_tokens(readline: Callable[[], str]) -> Generator[_TokenType, None, None]: ... def group(*args: str) -> str: ... def maybe(*args: str) -> str: ... def printtoken(type: int, token: str, srow_scol: _Pos, erow_ecol: _Pos, line: str) -> None: ... -def tokenize(readline: Callable[[], str], tokeneater: Callable[[Tuple[int, str, _Pos, _Pos, str]], None]) -> None: ... -def tokenize_loop(readline: Callable[[], str], tokeneater: Callable[[Tuple[int, str, _Pos, _Pos, str]], None]) -> None: ... +def tokenize(readline: Callable[[], str], tokeneater: Callable[[tuple[int, str, _Pos, _Pos, str]], None]) -> None: ... +def tokenize_loop(readline: Callable[[], str], tokeneater: Callable[[tuple[int, str, _Pos, _Pos, str]], None]) -> None: ... def untokenize(iterable: Iterable[_TokenType]) -> str: ... class StopTokenizing(Exception): ... @@ -126,8 +126,8 @@ class TokenError(Exception): ... class Untokenizer: prev_col: int prev_row: int - tokens: List[str] + tokens: list[str] def __init__(self) -> None: ... def add_whitespace(self, _Pos) -> None: ... - def compat(self, token: Tuple[int, Any], iterable: Iterator[_TokenType]) -> None: ... + def compat(self, token: tuple[int, Any], iterable: Iterator[_TokenType]) -> None: ... def untokenize(self, iterable: Iterable[_TokenType]) -> str: ... diff --git a/mypy/typeshed/stdlib/@python2/trace.pyi b/mypy/typeshed/stdlib/@python2/trace.pyi index 62f228673a55..82777cd6a5ea 100644 --- a/mypy/typeshed/stdlib/@python2/trace.pyi +++ b/mypy/typeshed/stdlib/@python2/trace.pyi @@ -1,25 +1,25 @@ import types from _typeshed import StrPath -from typing import Any, Callable, Dict, Mapping, Optional, Sequence, Tuple, TypeVar +from typing import Any, Callable, Mapping, Optional, Sequence, TypeVar _T = TypeVar("_T") _localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] -_fileModuleFunction = Tuple[str, Optional[str], str] +_fileModuleFunction = tuple[str, Optional[str], str] class CoverageResults: def __init__( self, - counts: Dict[Tuple[str, int], int] | None = ..., - calledfuncs: Dict[_fileModuleFunction, int] | None = ..., + counts: dict[tuple[str, int], int] | None = ..., + calledfuncs: dict[_fileModuleFunction, int] | None = ..., infile: StrPath | None = ..., - callers: Dict[Tuple[_fileModuleFunction, _fileModuleFunction], int] | None = ..., + callers: dict[tuple[_fileModuleFunction, _fileModuleFunction], int] | None = ..., outfile: StrPath | None = ..., ) -> None: ... # undocumented def update(self, other: CoverageResults) -> None: ... def write_results(self, show_missing: bool = ..., summary: bool = ..., coverdir: StrPath | None = ...) -> None: ... def write_results_file( self, path: StrPath, lines: Sequence[str], lnotab: Any, lines_hit: Mapping[int, int], encoding: str | None = ... - ) -> Tuple[int, int]: ... + ) -> tuple[int, int]: ... class Trace: def __init__( diff --git a/mypy/typeshed/stdlib/@python2/traceback.pyi b/mypy/typeshed/stdlib/@python2/traceback.pyi index 2152ab255942..94c75e5ef6b1 100644 --- a/mypy/typeshed/stdlib/@python2/traceback.pyi +++ b/mypy/typeshed/stdlib/@python2/traceback.pyi @@ -1,11 +1,11 @@ from types import FrameType, TracebackType -from typing import IO, List, Optional, Tuple, Type +from typing import IO, Optional -_PT = Tuple[str, int, str, Optional[str]] +_PT = tuple[str, int, str, Optional[str]] def print_tb(tb: TracebackType | None, limit: int | None = ..., file: IO[str] | None = ...) -> None: ... def print_exception( - etype: Type[BaseException] | None, + etype: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None, limit: int | None = ..., @@ -14,14 +14,14 @@ def print_exception( def print_exc(limit: int | None = ..., file: IO[str] | None = ...) -> None: ... def print_last(limit: int | None = ..., file: IO[str] | None = ...) -> None: ... def print_stack(f: FrameType | None = ..., limit: int | None = ..., file: IO[str] | None = ...) -> None: ... -def extract_tb(tb: TracebackType | None, limit: int | None = ...) -> List[_PT]: ... -def extract_stack(f: FrameType | None = ..., limit: int | None = ...) -> List[_PT]: ... -def format_list(extracted_list: List[_PT]) -> List[str]: ... -def format_exception_only(etype: Type[BaseException] | None, value: BaseException | None) -> List[str]: ... +def extract_tb(tb: TracebackType | None, limit: int | None = ...) -> list[_PT]: ... +def extract_stack(f: FrameType | None = ..., limit: int | None = ...) -> list[_PT]: ... +def format_list(extracted_list: list[_PT]) -> list[str]: ... +def format_exception_only(etype: type[BaseException] | None, value: BaseException | None) -> list[str]: ... def format_exception( - etype: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None, limit: int | None = ... -) -> List[str]: ... + etype: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None, limit: int | None = ... +) -> list[str]: ... def format_exc(limit: int | None = ...) -> str: ... -def format_tb(tb: TracebackType | None, limit: int | None = ...) -> List[str]: ... -def format_stack(f: FrameType | None = ..., limit: int | None = ...) -> List[str]: ... +def format_tb(tb: TracebackType | None, limit: int | None = ...) -> list[str]: ... +def format_stack(f: FrameType | None = ..., limit: int | None = ...) -> list[str]: ... def tb_lineno(tb: TracebackType) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/tty.pyi b/mypy/typeshed/stdlib/@python2/tty.pyi index c0dc418e9933..56e85108c75e 100644 --- a/mypy/typeshed/stdlib/@python2/tty.pyi +++ b/mypy/typeshed/stdlib/@python2/tty.pyi @@ -1,15 +1,16 @@ +import sys from typing import IO, Union _FD = Union[int, IO[str]] -# XXX: Undocumented integer constants -IFLAG: int -OFLAG: int -CFLAG: int -LFLAG: int -ISPEED: int -OSPEED: int -CC: int - -def setraw(fd: _FD, when: int = ...) -> None: ... -def setcbreak(fd: _FD, when: int = ...) -> None: ... +if sys.platform != "win32": + # XXX: Undocumented integer constants + IFLAG: int + OFLAG: int + CFLAG: int + LFLAG: int + ISPEED: int + OSPEED: int + CC: int + def setraw(fd: _FD, when: int = ...) -> None: ... + def setcbreak(fd: _FD, when: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/turtle.pyi b/mypy/typeshed/stdlib/@python2/turtle.pyi index 659dfd31b161..cb52479864a2 100644 --- a/mypy/typeshed/stdlib/@python2/turtle.pyi +++ b/mypy/typeshed/stdlib/@python2/turtle.pyi @@ -1,4 +1,5 @@ -from typing import Any, Callable, Dict, List, Sequence, Text, Tuple, TypeVar, Union, overload +from _typeshed import Self +from typing import Any, Callable, Sequence, Text, Union, overload # TODO: Replace these aliases once we have Python 2 stubs for the Tkinter module. Canvas = Any @@ -8,18 +9,18 @@ PhotoImage = Any # alias we use for return types. Really, these two aliases should be the # same, but as per the "no union returns" typeshed policy, we'll return # Any instead. -_Color = Union[Text, Tuple[float, float, float]] +_Color = Union[Text, tuple[float, float, float]] _AnyColor = Any # TODO: Replace this with a TypedDict once it becomes standardized. -_PenState = Dict[str, Any] +_PenState = dict[str, Any] _Speed = Union[str, float] -_PolygonCoords = Sequence[Tuple[float, float]] +_PolygonCoords = Sequence[tuple[float, float]] # TODO: Type this more accurately # Vec2D is actually a custom subclass of 'tuple'. -Vec2D = Tuple[float, float] +Vec2D = tuple[float, float] class TurtleScreenBase(object): cv: Canvas = ... @@ -50,7 +51,7 @@ class TurtleScreen(TurtleScreenBase): @overload def colormode(self, cmode: float) -> None: ... def reset(self) -> None: ... - def turtles(self) -> List[Turtle]: ... + def turtles(self) -> list[Turtle]: ... @overload def bgcolor(self) -> _AnyColor: ... @overload @@ -69,7 +70,7 @@ class TurtleScreen(TurtleScreenBase): def window_width(self) -> int: ... def window_height(self) -> int: ... def getcanvas(self) -> Canvas: ... - def getshapes(self) -> List[str]: ... + def getshapes(self) -> list[str]: ... def onclick(self, fun: Callable[[float, float], Any], btn: int = ..., add: Any | None = ...) -> None: ... def onkey(self, fun: Callable[[], Any], key: str) -> None: ... def listen(self, xdummy: float | None = ..., ydummy: float | None = ...) -> None: ... @@ -79,7 +80,7 @@ class TurtleScreen(TurtleScreenBase): @overload def bgpic(self, picname: str) -> None: ... @overload - def screensize(self, canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> Tuple[int, int]: ... + def screensize(self, canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> tuple[int, int]: ... # Looks like if self.cv is not a ScrolledCanvas, this could return a tuple as well @overload def screensize(self, canvwidth: int, canvheight: int, bg: _Color | None = ...) -> None: ... @@ -89,7 +90,7 @@ class TurtleScreen(TurtleScreenBase): addshape = register_shape class TNavigator(object): - START_ORIENTATION: Dict[str, Vec2D] = ... + START_ORIENTATION: dict[str, Vec2D] = ... DEFAULT_MODE: str = ... DEFAULT_ANGLEOFFSET: int = ... DEFAULT_ANGLEORIENT: int = ... @@ -105,18 +106,18 @@ class TNavigator(object): def xcor(self) -> float: ... def ycor(self) -> float: ... @overload - def goto(self, x: Tuple[float, float], y: None = ...) -> None: ... + def goto(self, x: tuple[float, float], y: None = ...) -> None: ... @overload def goto(self, x: float, y: float) -> None: ... def home(self) -> None: ... def setx(self, x: float) -> None: ... def sety(self, y: float) -> None: ... @overload - def distance(self, x: TNavigator | Tuple[float, float], y: None = ...) -> float: ... + def distance(self, x: TNavigator | tuple[float, float], y: None = ...) -> float: ... @overload def distance(self, x: float, y: float) -> float: ... @overload - def towards(self, x: TNavigator | Tuple[float, float], y: None = ...) -> float: ... + def towards(self, x: TNavigator | tuple[float, float], y: None = ...) -> float: ... @overload def towards(self, x: float, y: float) -> float: ... def heading(self) -> float: ... @@ -162,7 +163,7 @@ class TPen(object): @overload def fillcolor(self, r: float, g: float, b: float) -> None: ... @overload - def color(self) -> Tuple[_AnyColor, _AnyColor]: ... + def color(self) -> tuple[_AnyColor, _AnyColor]: ... @overload def color(self, color: _Color) -> None: ... @overload @@ -187,7 +188,7 @@ class TPen(object): pensize: int = ..., speed: int = ..., resizemode: str = ..., - stretchfactor: Tuple[float, float] = ..., + stretchfactor: tuple[float, float] = ..., outline: int = ..., tilt: float = ..., ) -> None: ... @@ -199,8 +200,6 @@ class TPen(object): st = showturtle ht = hideturtle -_T = TypeVar("_T") - class RawTurtle(TPen, TNavigator): def __init__( self, canvas: Canvas | TurtleScreen | None = ..., shape: str = ..., undobuffersize: int = ..., visible: bool = ... @@ -209,14 +208,14 @@ class RawTurtle(TPen, TNavigator): def setundobuffer(self, size: int | None) -> None: ... def undobufferentries(self) -> int: ... def clear(self) -> None: ... - def clone(self: _T) -> _T: ... + def clone(self: Self) -> Self: ... @overload def shape(self, name: None = ...) -> str: ... @overload def shape(self, name: str) -> None: ... # Unsafely overlaps when no arguments are provided @overload - def shapesize(self) -> Tuple[float, float, float]: ... # type: ignore + def shapesize(self) -> tuple[float, float, float]: ... # type: ignore @overload def shapesize( self, stretch_wid: float | None = ..., stretch_len: float | None = ..., outline: float | None = ... @@ -231,18 +230,18 @@ class RawTurtle(TPen, TNavigator): # a compound stamp or not. So, as per the "no Union return" policy, # we return Any. def stamp(self) -> Any: ... - def clearstamp(self, stampid: int | Tuple[int, ...]) -> None: ... + def clearstamp(self, stampid: int | tuple[int, ...]) -> None: ... def clearstamps(self, n: int | None = ...) -> None: ... def filling(self) -> bool: ... def begin_fill(self) -> None: ... def end_fill(self) -> None: ... def dot(self, size: int | None = ..., *color: _Color) -> None: ... - def write(self, arg: object, move: bool = ..., align: str = ..., font: Tuple[str, int, str] = ...) -> None: ... + def write(self, arg: object, move: bool = ..., align: str = ..., font: tuple[str, int, str] = ...) -> None: ... def begin_poly(self) -> None: ... def end_poly(self) -> None: ... def get_poly(self) -> _PolygonCoords | None: ... def getscreen(self) -> TurtleScreen: ... - def getturtle(self: _T) -> _T: ... + def getturtle(self: Self) -> Self: ... getpen = getturtle def onclick(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... def onrelease(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... @@ -297,7 +296,7 @@ def colormode(cmode: None = ...) -> float: ... @overload def colormode(cmode: float) -> None: ... def reset() -> None: ... -def turtles() -> List[Turtle]: ... +def turtles() -> list[Turtle]: ... @overload def bgcolor() -> _AnyColor: ... @overload @@ -316,7 +315,7 @@ def update() -> None: ... def window_width() -> int: ... def window_height() -> int: ... def getcanvas() -> Canvas: ... -def getshapes() -> List[str]: ... +def getshapes() -> list[str]: ... def onclick(fun: Callable[[float, float], Any], btn: int = ..., add: Any | None = ...) -> None: ... def onkey(fun: Callable[[], Any], key: str) -> None: ... def listen(xdummy: float | None = ..., ydummy: float | None = ...) -> None: ... @@ -326,7 +325,7 @@ def bgpic(picname: None = ...) -> str: ... @overload def bgpic(picname: str) -> None: ... @overload -def screensize(canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> Tuple[int, int]: ... +def screensize(canvwidth: None = ..., canvheight: None = ..., bg: None = ...) -> tuple[int, int]: ... @overload def screensize(canvwidth: int, canvheight: int, bg: _Color | None = ...) -> None: ... @@ -354,18 +353,18 @@ def pos() -> Vec2D: ... def xcor() -> float: ... def ycor() -> float: ... @overload -def goto(x: Tuple[float, float], y: None = ...) -> None: ... +def goto(x: tuple[float, float], y: None = ...) -> None: ... @overload def goto(x: float, y: float) -> None: ... def home() -> None: ... def setx(x: float) -> None: ... def sety(y: float) -> None: ... @overload -def distance(x: TNavigator | Tuple[float, float], y: None = ...) -> float: ... +def distance(x: TNavigator | tuple[float, float], y: None = ...) -> float: ... @overload def distance(x: float, y: float) -> float: ... @overload -def towards(x: TNavigator | Tuple[float, float], y: None = ...) -> float: ... +def towards(x: TNavigator | tuple[float, float], y: None = ...) -> float: ... @overload def towards(x: float, y: float) -> float: ... def heading() -> float: ... @@ -411,7 +410,7 @@ def fillcolor(color: _Color) -> None: ... @overload def fillcolor(r: float, g: float, b: float) -> None: ... @overload -def color() -> Tuple[_AnyColor, _AnyColor]: ... +def color() -> tuple[_AnyColor, _AnyColor]: ... @overload def color(color: _Color) -> None: ... @overload @@ -436,7 +435,7 @@ def pen( pensize: int = ..., speed: int = ..., resizemode: str = ..., - stretchfactor: Tuple[float, float] = ..., + stretchfactor: tuple[float, float] = ..., outline: int = ..., tilt: float = ..., ) -> None: ... @@ -460,7 +459,7 @@ def shape(name: str) -> None: ... # Unsafely overlaps when no arguments are provided @overload -def shapesize() -> Tuple[float, float, float]: ... # type: ignore +def shapesize() -> tuple[float, float, float]: ... # type: ignore @overload def shapesize(stretch_wid: float | None = ..., stretch_len: float | None = ..., outline: float | None = ...) -> None: ... def settiltangle(angle: float) -> None: ... @@ -474,13 +473,13 @@ def tilt(angle: float) -> None: ... # a compound stamp or not. So, as per the "no Union return" policy, # we return Any. def stamp() -> Any: ... -def clearstamp(stampid: int | Tuple[int, ...]) -> None: ... +def clearstamp(stampid: int | tuple[int, ...]) -> None: ... def clearstamps(n: int | None = ...) -> None: ... def filling() -> bool: ... def begin_fill() -> None: ... def end_fill() -> None: ... def dot(size: int | None = ..., *color: _Color) -> None: ... -def write(arg: object, move: bool = ..., align: str = ..., font: Tuple[str, int, str] = ...) -> None: ... +def write(arg: object, move: bool = ..., align: str = ..., font: tuple[str, int, str] = ...) -> None: ... def begin_poly() -> None: ... def end_poly() -> None: ... def get_poly() -> _PolygonCoords | None: ... diff --git a/mypy/typeshed/stdlib/@python2/types.pyi b/mypy/typeshed/stdlib/@python2/types.pyi index 72b9321a860f..d2194296aa17 100644 --- a/mypy/typeshed/stdlib/@python2/types.pyi +++ b/mypy/typeshed/stdlib/@python2/types.pyi @@ -1,4 +1,4 @@ -from typing import Any, Callable, Dict, Iterable, Iterator, List, Tuple, Type, TypeVar, overload +from typing import Any, Callable, Iterable, Iterator, TypeVar, overload _T = TypeVar("_T") @@ -16,7 +16,7 @@ BooleanType = bool ComplexType = complex StringType = str UnicodeType = unicode -StringTypes: Tuple[Type[StringType], Type[UnicodeType]] +StringTypes: tuple[type[StringType], type[UnicodeType]] BufferType = buffer TupleType = tuple ListType = list @@ -27,12 +27,12 @@ class _Cell: cell_contents: Any class FunctionType: - func_closure: Tuple[_Cell, ...] | None = ... + func_closure: tuple[_Cell, ...] | None = ... func_code: CodeType = ... - func_defaults: Tuple[Any, ...] | None = ... - func_dict: Dict[str, Any] = ... + func_defaults: tuple[Any, ...] | None = ... + func_dict: dict[str, Any] = ... func_doc: str | None = ... - func_globals: Dict[str, Any] = ... + func_globals: dict[str, Any] = ... func_name: str = ... __closure__ = func_closure __code__ = func_code @@ -43,10 +43,10 @@ class FunctionType: def __init__( self, code: CodeType, - globals: Dict[str, Any], + globals: dict[str, Any], name: str | None = ..., - argdefs: Tuple[object, ...] | None = ..., - closure: Tuple[_Cell, ...] | None = ..., + argdefs: tuple[object, ...] | None = ..., + closure: tuple[_Cell, ...] | None = ..., ) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... def __get__(self, obj: object | None, type: type | None) -> UnboundMethodType: ... @@ -55,19 +55,19 @@ LambdaType = FunctionType class CodeType: co_argcount: int - co_cellvars: Tuple[str, ...] + co_cellvars: tuple[str, ...] co_code: str - co_consts: Tuple[Any, ...] + co_consts: tuple[Any, ...] co_filename: str co_firstlineno: int co_flags: int - co_freevars: Tuple[str, ...] + co_freevars: tuple[str, ...] co_lnotab: str co_name: str - co_names: Tuple[str, ...] + co_names: tuple[str, ...] co_nlocals: int co_stacksize: int - co_varnames: Tuple[str, ...] + co_varnames: tuple[str, ...] def __init__( self, argcount: int, @@ -75,15 +75,15 @@ class CodeType: stacksize: int, flags: int, codestring: str, - constants: Tuple[Any, ...], - names: Tuple[str, ...], - varnames: Tuple[str, ...], + constants: tuple[Any, ...], + names: tuple[str, ...], + varnames: tuple[str, ...], filename: str, name: str, firstlineno: int, lnotab: str, - freevars: Tuple[str, ...] = ..., - cellvars: Tuple[str, ...] = ..., + freevars: tuple[str, ...] = ..., + cellvars: tuple[str, ...] = ..., ) -> None: ... class GeneratorType: @@ -95,7 +95,7 @@ class GeneratorType: def next(self) -> Any: ... def send(self, __arg: Any) -> Any: ... @overload - def throw(self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ...) -> Any: ... + def throw(self, __typ: type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ...) -> Any: ... @overload def throw(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> Any: ... @@ -127,7 +127,7 @@ class ModuleType: __name__: str __package__: str | None __path__: Iterable[str] | None - __dict__: Dict[str, Any] + __dict__: dict[str, Any] def __init__(self, name: str, doc: str | None = ...) -> None: ... FileType = file @@ -141,15 +141,15 @@ class TracebackType: class FrameType: f_back: FrameType - f_builtins: Dict[str, Any] + f_builtins: dict[str, Any] f_code: CodeType f_exc_type: None f_exc_value: None f_exc_traceback: None - f_globals: Dict[str, Any] + f_globals: dict[str, Any] f_lasti: int - f_lineno: int - f_locals: Dict[str, Any] + f_lineno: int | None + f_locals: dict[str, Any] f_restricted: bool f_trace: Callable[[], None] def clear(self) -> None: ... @@ -161,15 +161,15 @@ class EllipsisType: ... class DictProxyType: # TODO is it possible to have non-string keys? # no __init__ - def copy(self) -> Dict[Any, Any]: ... + def copy(self) -> dict[Any, Any]: ... def get(self, key: str, default: _T = ...) -> Any | _T: ... def has_key(self, key: str) -> bool: ... - def items(self) -> List[Tuple[str, Any]]: ... - def iteritems(self) -> Iterator[Tuple[str, Any]]: ... + def items(self) -> list[tuple[str, Any]]: ... + def iteritems(self) -> Iterator[tuple[str, Any]]: ... def iterkeys(self) -> Iterator[str]: ... def itervalues(self) -> Iterator[Any]: ... - def keys(self) -> List[str]: ... - def values(self) -> List[Any]: ... + def keys(self) -> list[str]: ... + def values(self) -> list[Any]: ... def __contains__(self, key: str) -> bool: ... def __getitem__(self, key: str) -> Any: ... def __iter__(self) -> Iterator[str]: ... diff --git a/mypy/typeshed/stdlib/@python2/typing.pyi b/mypy/typeshed/stdlib/@python2/typing.pyi index a1b02e81990c..b209f7cfd344 100644 --- a/mypy/typeshed/stdlib/@python2/typing.pyi +++ b/mypy/typeshed/stdlib/@python2/typing.pyi @@ -1,4 +1,5 @@ import collections # Needed by aliases like DefaultDict, see mypy issue 2986 +from _typeshed import Self from abc import ABCMeta, abstractmethod from types import CodeType, FrameType, TracebackType @@ -77,7 +78,7 @@ Counter = _Alias() Deque = _Alias() # Predefined type variables. -AnyStr = TypeVar("AnyStr", str, unicode) +AnyStr = TypeVar("AnyStr", str, unicode) # noqa: Y001 # Abstract base classes. @@ -462,11 +463,11 @@ class NamedTuple(Tuple[Any, ...]): @classmethod def _make(cls: Type[_T], iterable: Iterable[Any]) -> _T: ... def _asdict(self) -> Dict[str, Any]: ... - def _replace(self: _T, **kwargs: Any) -> _T: ... + def _replace(self: Self, **kwargs: Any) -> Self: ... # Internal mypy fallback type for all typed dicts (does not exist at runtime) class _TypedDict(Mapping[str, object], metaclass=ABCMeta): - def copy(self: _T) -> _T: ... + def copy(self: Self) -> Self: ... # Using NoReturn so that only calls using mypy plugin hook that specialize the signature # can go through. def setdefault(self, k: NoReturn, default: object) -> object: ... diff --git a/mypy/typeshed/stdlib/@python2/typing_extensions.pyi b/mypy/typeshed/stdlib/@python2/typing_extensions.pyi index d946cc278d32..245463896f26 100644 --- a/mypy/typeshed/stdlib/@python2/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/@python2/typing_extensions.pyi @@ -1,5 +1,6 @@ import abc -from typing import ( +from _typeshed import Self +from typing import ( # noqa Y022 TYPE_CHECKING as TYPE_CHECKING, Any, Callable, @@ -8,14 +9,12 @@ from typing import ( Counter as Counter, DefaultDict as DefaultDict, Deque as Deque, - Dict, ItemsView, KeysView, Mapping, NewType as NewType, NoReturn as NoReturn, Text as Text, - Tuple, Type as Type, TypeVar, ValuesView, @@ -25,7 +24,7 @@ from typing import ( _T = TypeVar("_T") _F = TypeVar("_F", bound=Callable[..., Any]) -_TC = TypeVar("_TC", bound=Type[object]) +_TC = TypeVar("_TC", bound=type[object]) class _SpecialForm: def __getitem__(self, typeargs: Any) -> Any: ... @@ -45,7 +44,7 @@ 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): - def copy(self: _T) -> _T: ... + def copy(self: Self) -> Self: ... # Using NoReturn so that only calls using mypy plugin hook that specialize the signature # can go through. def setdefault(self, k: NoReturn, default: object) -> object: ... @@ -65,10 +64,10 @@ OrderedDict = _Alias() def get_type_hints( obj: Callable[..., Any], - globalns: Dict[str, Any] | None = ..., - localns: Dict[str, Any] | None = ..., + globalns: dict[str, Any] | None = ..., + localns: dict[str, Any] | None = ..., include_extras: bool = ..., -) -> Dict[str, Any]: ... +) -> dict[str, Any]: ... Annotated: _SpecialForm = ... _AnnotatedAlias: Any = ... # undocumented @@ -89,11 +88,11 @@ class ParamSpecKwargs: class ParamSpec: __name__: str - __bound__: Type[Any] | None + __bound__: type[Any] | None __covariant__: bool __contravariant__: bool def __init__( - self, name: str, *, bound: None | Type[Any] | str = ..., contravariant: bool = ..., covariant: bool = ... + self, name: str, *, bound: None | type[Any] | str = ..., contravariant: bool = ..., covariant: bool = ... ) -> None: ... @property def args(self) -> ParamSpecArgs: ... diff --git a/mypy/typeshed/stdlib/@python2/unittest.pyi b/mypy/typeshed/stdlib/@python2/unittest.pyi index 65a5a7878de6..d5ca2de7e9b1 100644 --- a/mypy/typeshed/stdlib/@python2/unittest.pyi +++ b/mypy/typeshed/stdlib/@python2/unittest.pyi @@ -1,35 +1,15 @@ import datetime import types from abc import ABCMeta, abstractmethod -from typing import ( - Any, - Callable, - Dict, - FrozenSet, - Iterable, - Iterator, - List, - Mapping, - NoReturn, - Pattern, - Sequence, - Set, - Text, - TextIO, - Tuple, - Type, - TypeVar, - Union, - overload, -) +from typing import Any, Callable, Iterable, Iterator, Mapping, NoReturn, Pattern, Sequence, Text, TextIO, TypeVar, Union, overload _T = TypeVar("_T") _FT = TypeVar("_FT") -_ExceptionType = Union[Type[BaseException], Tuple[Type[BaseException], ...]] +_ExceptionType = Union[type[BaseException], tuple[type[BaseException], ...]] _Regexp = Union[Text, Pattern[Text]] -_SysExcInfoType = Union[Tuple[Type[BaseException], BaseException, types.TracebackType], Tuple[None, None, None]] +_SysExcInfoType = Union[tuple[type[BaseException], BaseException, types.TracebackType], tuple[None, None, None]] class Testable(metaclass=ABCMeta): @abstractmethod @@ -42,11 +22,11 @@ class Testable(metaclass=ABCMeta): # TODO ABC for test runners? class TestResult: - errors: List[Tuple[TestCase, str]] - failures: List[Tuple[TestCase, str]] - skipped: List[Tuple[TestCase, str]] - expectedFailures: List[Tuple[TestCase, str]] - unexpectedSuccesses: List[TestCase] + errors: list[tuple[TestCase, str]] + failures: list[tuple[TestCase, str]] + skipped: list[tuple[TestCase, str]] + expectedFailures: list[tuple[TestCase, str]] + unexpectedSuccesses: list[TestCase] shouldStop: bool testsRun: int buffer: bool @@ -66,7 +46,7 @@ class TestResult: class _AssertRaisesBaseContext: expected: Any - failureException: Type[BaseException] + failureException: type[BaseException] obj_name: str expected_regex: Pattern[str] @@ -76,7 +56,7 @@ class _AssertRaisesContext(_AssertRaisesBaseContext): def __exit__(self, exc_type, exc_value, tb) -> bool: ... class TestCase(Testable): - failureException: Type[BaseException] + failureException: type[BaseException] longMessage: bool maxDiff: int | None # undocumented @@ -141,10 +121,10 @@ class TestCase(Testable): def assertSequenceEqual( self, first: Sequence[Any], second: Sequence[Any], msg: object = ..., seq_type: type = ... ) -> None: ... - def assertListEqual(self, first: List[Any], second: List[Any], msg: object = ...) -> None: ... - def assertTupleEqual(self, first: Tuple[Any, ...], second: Tuple[Any, ...], msg: object = ...) -> None: ... - def assertSetEqual(self, first: Set[Any] | FrozenSet[Any], second: Set[Any] | FrozenSet[Any], msg: object = ...) -> None: ... - def assertDictEqual(self, first: Dict[Any, Any], second: Dict[Any, Any], msg: object = ...) -> None: ... + def assertListEqual(self, first: list[Any], second: list[Any], msg: object = ...) -> None: ... + def assertTupleEqual(self, first: tuple[Any, ...], second: tuple[Any, ...], msg: object = ...) -> None: ... + def assertSetEqual(self, first: set[Any] | frozenset[Any], second: set[Any] | frozenset[Any], msg: object = ...) -> None: ... + def assertDictEqual(self, first: dict[Any, Any], second: dict[Any, Any], msg: object = ...) -> None: ... def assertLess(self, first: Any, second: Any, msg: object = ...) -> None: ... def assertLessEqual(self, first: Any, second: Any, msg: object = ...) -> None: ... @overload @@ -174,8 +154,8 @@ class TestCase(Testable): def assertIsNotNone(self, expr: Any, msg: object = ...) -> None: ... def assertIn(self, first: _T, second: Iterable[_T], msg: object = ...) -> None: ... def assertNotIn(self, first: _T, second: Iterable[_T], msg: object = ...) -> None: ... - def assertIsInstance(self, obj: Any, cls: type | Tuple[type, ...], msg: object = ...) -> None: ... - def assertNotIsInstance(self, obj: Any, cls: type | Tuple[type, ...], msg: object = ...) -> None: ... + def assertIsInstance(self, obj: Any, cls: type | tuple[type, ...], msg: object = ...) -> None: ... + def assertNotIsInstance(self, obj: Any, cls: type | tuple[type, ...], msg: object = ...) -> None: ... def fail(self, msg: object = ...) -> NoReturn: ... def countTestCases(self) -> int: ... def defaultTestResult(self) -> TestResult: ... @@ -210,13 +190,13 @@ class TestSuite(Testable): class TestLoader: testMethodPrefix: str sortTestMethodsUsing: Callable[[str, str], int] | None - suiteClass: Callable[[List[TestCase]], TestSuite] - def loadTestsFromTestCase(self, testCaseClass: Type[TestCase]) -> TestSuite: ... + suiteClass: Callable[[list[TestCase]], TestSuite] + def loadTestsFromTestCase(self, testCaseClass: type[TestCase]) -> TestSuite: ... def loadTestsFromModule(self, module: types.ModuleType = ..., use_load_tests: bool = ...) -> TestSuite: ... def loadTestsFromName(self, name: str = ..., module: types.ModuleType | None = ...) -> TestSuite: ... - def loadTestsFromNames(self, names: List[str] = ..., module: types.ModuleType | None = ...) -> TestSuite: ... + def loadTestsFromNames(self, names: list[str] = ..., module: types.ModuleType | None = ...) -> TestSuite: ... def discover(self, start_dir: str, pattern: str = ..., top_level_dir: str | None = ...) -> TestSuite: ... - def getTestCaseNames(self, testCaseClass: Type[TestCase] = ...) -> List[str]: ... + def getTestCaseNames(self, testCaseClass: type[TestCase] = ...) -> list[str]: ... defaultTestLoader: TestLoader @@ -224,7 +204,7 @@ class TextTestResult(TestResult): def __init__(self, stream: TextIO, descriptions: bool, verbosity: int) -> None: ... def getDescription(self, test: TestCase) -> str: ... # undocumented def printErrors(self) -> None: ... # undocumented - def printErrorList(self, flavour: str, errors: List[Tuple[TestCase, str]]) -> None: ... # undocumented + def printErrorList(self, flavour: str, errors: list[tuple[TestCase, str]]) -> None: ... # undocumented class TextTestRunner: def __init__( @@ -234,7 +214,7 @@ class TextTestRunner: verbosity: int = ..., failfast: bool = ..., buffer: bool = ..., - resultclass: Type[TestResult] | None = ..., + resultclass: type[TestResult] | None = ..., ) -> None: ... def _makeResult(self) -> TestResult: ... def run(self, test: Testable) -> TestResult: ... # undocumented @@ -256,7 +236,7 @@ def main( module: None | Text | types.ModuleType = ..., defaultTest: str | None = ..., argv: Sequence[str] | None = ..., - testRunner: Type[TextTestRunner] | TextTestRunner | None = ..., + testRunner: type[TextTestRunner] | TextTestRunner | None = ..., testLoader: TestLoader = ..., exit: bool = ..., verbosity: int = ..., diff --git a/mypy/typeshed/stdlib/@python2/urllib.pyi b/mypy/typeshed/stdlib/@python2/urllib.pyi index f6bb555b9581..56a75af74bb3 100644 --- a/mypy/typeshed/stdlib/@python2/urllib.pyi +++ b/mypy/typeshed/stdlib/@python2/urllib.pyi @@ -1,4 +1,5 @@ -from typing import IO, Any, AnyStr, List, Mapping, Sequence, Text, Tuple, TypeVar +from _typeshed import Self +from typing import IO, Any, AnyStr, Mapping, Sequence, Text def url2pathname(pathname: AnyStr) -> AnyStr: ... def pathname2url(pathname: AnyStr) -> AnyStr: ... @@ -77,15 +78,13 @@ class ftpwrapper: def file_close(self): ... def real_close(self): ... -_AIUT = TypeVar("_AIUT", bound=addbase) - class addbase: fp: Any def read(self, n: int = ...) -> bytes: ... def readline(self, limit: int = ...) -> bytes: ... - def readlines(self, hint: int = ...) -> List[bytes]: ... + def readlines(self, hint: int = ...) -> list[bytes]: ... def fileno(self) -> int: ... # Optional[int], but that is rare - def __iter__(self: _AIUT) -> _AIUT: ... + def __iter__(self: Self) -> Self: ... def next(self) -> bytes: ... def __init__(self, fp) -> None: ... def close(self) -> None: ... @@ -125,7 +124,7 @@ def unquote(s: AnyStr) -> AnyStr: ... def unquote_plus(s: AnyStr) -> AnyStr: ... def quote(s: AnyStr, safe: Text = ...) -> AnyStr: ... def quote_plus(s: AnyStr, safe: Text = ...) -> AnyStr: ... -def urlencode(query: Sequence[Tuple[Any, Any]] | Mapping[Any, Any], doseq=...) -> str: ... +def urlencode(query: Sequence[tuple[Any, Any]] | Mapping[Any, Any], doseq=...) -> str: ... def getproxies() -> Mapping[str, str]: ... def proxy_bypass(host: str) -> Any: ... # undocumented diff --git a/mypy/typeshed/stdlib/@python2/urllib2.pyi b/mypy/typeshed/stdlib/@python2/urllib2.pyi index bf6157b8428b..990384ebdcd1 100644 --- a/mypy/typeshed/stdlib/@python2/urllib2.pyi +++ b/mypy/typeshed/stdlib/@python2/urllib2.pyi @@ -1,6 +1,6 @@ import ssl from httplib import HTTPConnectionProtocol, HTTPResponse -from typing import Any, AnyStr, Callable, Dict, List, Mapping, Sequence, Text, Tuple, Type, Union +from typing import Any, AnyStr, Callable, Mapping, Sequence, Text, Union from urllib import addinfourl _string = Union[str, unicode] @@ -17,17 +17,17 @@ class Request(object): host: str port: str data: str - headers: Dict[str, str] + headers: dict[str, str] unverifiable: bool type: str | None origin_req_host = ... - unredirected_hdrs: Dict[str, str] + unredirected_hdrs: dict[str, str] timeout: float | None # Undocumented, only set after __init__() by OpenerDirector.open() def __init__( self, url: str, data: str | None = ..., - headers: Dict[str, str] = ..., + headers: dict[str, str] = ..., origin_req_host: str | None = ..., unverifiable: bool = ..., ) -> None: ... @@ -51,7 +51,7 @@ class Request(object): def header_items(self): ... class OpenerDirector(object): - addheaders: List[Tuple[str, str]] + addheaders: list[tuple[str, str]] def add_handler(self, handler: BaseHandler) -> None: ... def open(self, fullurl: Request | _string, data: _string | None = ..., timeout: float | None = ...) -> addinfourl | None: ... def error(self, proto: _string, *args: Any): ... @@ -68,7 +68,7 @@ def urlopen( context: ssl.SSLContext | None = ..., ) -> addinfourl: ... def install_opener(opener: OpenerDirector) -> None: ... -def build_opener(*handlers: BaseHandler | Type[BaseHandler]) -> OpenerDirector: ... +def build_opener(*handlers: BaseHandler | type[BaseHandler]) -> OpenerDirector: ... class BaseHandler: handler_order: int @@ -101,8 +101,8 @@ class ProxyHandler(BaseHandler): class HTTPPasswordMgr: def __init__(self) -> None: ... def add_password(self, realm: Text | None, uri: Text | Sequence[Text], user: Text, passwd: Text) -> None: ... - def find_user_password(self, realm: Text | None, authuri: Text) -> Tuple[Any, Any]: ... - def reduce_uri(self, uri: _string, default_port: bool = ...) -> Tuple[Any, Any]: ... + def find_user_password(self, realm: Text | None, authuri: Text) -> tuple[Any, Any]: ... + def reduce_uri(self, uri: _string, default_port: bool = ...) -> tuple[Any, Any]: ... def is_suburi(self, base: _string, test: _string) -> bool: ... class HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr): ... @@ -129,7 +129,7 @@ class AbstractDigestAuthHandler: def retry_http_digest_auth(self, req: Request, auth: str) -> HTTPResponse | None: ... def get_cnonce(self, nonce: str) -> str: ... def get_authorization(self, req: Request, chal: Mapping[str, str]) -> str: ... - def get_algorithm_impls(self, algorithm: str) -> Tuple[Callable[[str], str], Callable[[str, str], str]]: ... + def get_algorithm_impls(self, algorithm: str) -> tuple[Callable[[str], str], Callable[[str, str], str]]: ... def get_entity_digest(self, data: bytes | None, chal: Mapping[str, str]) -> str | None: ... class HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): @@ -181,5 +181,5 @@ class CacheFTPHandler(FTPHandler): def check_cache(self): ... def clear_cache(self): ... -def parse_http_list(s: AnyStr) -> List[AnyStr]: ... -def parse_keqv_list(l: List[AnyStr]) -> Dict[AnyStr, AnyStr]: ... +def parse_http_list(s: AnyStr) -> list[AnyStr]: ... +def parse_keqv_list(l: list[AnyStr]) -> dict[AnyStr, AnyStr]: ... diff --git a/mypy/typeshed/stdlib/@python2/urlparse.pyi b/mypy/typeshed/stdlib/@python2/urlparse.pyi index 6668c743373a..625928a74135 100644 --- a/mypy/typeshed/stdlib/@python2/urlparse.pyi +++ b/mypy/typeshed/stdlib/@python2/urlparse.pyi @@ -1,13 +1,13 @@ -from typing import AnyStr, Dict, List, NamedTuple, Sequence, Tuple, Union, overload +from typing import AnyStr, NamedTuple, Sequence, Union, overload _String = Union[str, unicode] -uses_relative: List[str] -uses_netloc: List[str] -uses_params: List[str] -non_hierarchical: List[str] -uses_query: List[str] -uses_fragment: List[str] +uses_relative: list[str] +uses_netloc: list[str] +uses_params: list[str] +non_hierarchical: list[str] +uses_query: list[str] +uses_fragment: list[str] scheme_chars: str MAX_CACHE_SIZE: int @@ -47,15 +47,15 @@ class ParseResult(_ParseResult, ResultMixin): def urlparse(url: _String, scheme: _String = ..., allow_fragments: bool = ...) -> ParseResult: ... def urlsplit(url: _String, scheme: _String = ..., allow_fragments: bool = ...) -> SplitResult: ... @overload -def urlunparse(data: Tuple[AnyStr, AnyStr, AnyStr, AnyStr, AnyStr, AnyStr]) -> AnyStr: ... +def urlunparse(data: tuple[AnyStr, AnyStr, AnyStr, AnyStr, AnyStr, AnyStr]) -> AnyStr: ... @overload def urlunparse(data: Sequence[AnyStr]) -> AnyStr: ... @overload -def urlunsplit(data: Tuple[AnyStr, AnyStr, AnyStr, AnyStr, AnyStr]) -> AnyStr: ... +def urlunsplit(data: tuple[AnyStr, AnyStr, AnyStr, AnyStr, AnyStr]) -> AnyStr: ... @overload def urlunsplit(data: Sequence[AnyStr]) -> AnyStr: ... def urljoin(base: AnyStr, url: AnyStr, allow_fragments: bool = ...) -> AnyStr: ... -def urldefrag(url: AnyStr) -> Tuple[AnyStr, AnyStr]: ... +def urldefrag(url: AnyStr) -> tuple[AnyStr, AnyStr]: ... def unquote(s: AnyStr) -> AnyStr: ... -def parse_qs(qs: AnyStr, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> Dict[AnyStr, List[AnyStr]]: ... -def parse_qsl(qs: AnyStr, keep_blank_values: int = ..., strict_parsing: bool = ...) -> List[Tuple[AnyStr, AnyStr]]: ... +def parse_qs(qs: AnyStr, keep_blank_values: bool = ..., strict_parsing: bool = ...) -> dict[AnyStr, list[AnyStr]]: ... +def parse_qsl(qs: AnyStr, keep_blank_values: int = ..., strict_parsing: bool = ...) -> list[tuple[AnyStr, AnyStr]]: ... diff --git a/mypy/typeshed/stdlib/@python2/uuid.pyi b/mypy/typeshed/stdlib/@python2/uuid.pyi index 2c8a9fb1c097..8ba2d7e5aa24 100644 --- a/mypy/typeshed/stdlib/@python2/uuid.pyi +++ b/mypy/typeshed/stdlib/@python2/uuid.pyi @@ -1,9 +1,9 @@ -from typing import Any, Text, Tuple +from typing import Any, Text # Because UUID has properties called int and bytes we need to rename these temporarily. _Int = int _Bytes = bytes -_FieldsType = Tuple[int, int, int, int, int, int] +_FieldsType = tuple[int, int, int, int, int, int] class UUID: def __init__( diff --git a/mypy/typeshed/stdlib/@python2/warnings.pyi b/mypy/typeshed/stdlib/@python2/warnings.pyi index 0d187bf70c33..2e872a4fb28e 100644 --- a/mypy/typeshed/stdlib/@python2/warnings.pyi +++ b/mypy/typeshed/stdlib/@python2/warnings.pyi @@ -1,23 +1,23 @@ 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 import TextIO, overload from typing_extensions import Literal def showwarning( - message: Warning | str, category: Type[Warning], filename: str, lineno: int, file: TextIO | None = ..., line: str | None = ... + message: Warning | str, category: type[Warning], filename: str, lineno: int, file: TextIO | None = ..., line: str | None = ... ) -> None: ... -def formatwarning(message: Warning | str, category: Type[Warning], filename: str, lineno: int, line: str | None = ...) -> str: ... +def formatwarning(message: Warning | str, category: type[Warning], filename: str, lineno: int, line: str | None = ...) -> str: ... def filterwarnings( - action: str, message: str = ..., category: Type[Warning] = ..., module: str = ..., lineno: int = ..., append: bool = ... + action: str, message: str = ..., category: type[Warning] = ..., module: str = ..., lineno: int = ..., append: bool = ... ) -> None: ... -def simplefilter(action: str, category: Type[Warning] = ..., lineno: int = ..., append: bool = ...) -> None: ... +def simplefilter(action: str, category: type[Warning] = ..., lineno: int = ..., append: bool = ...) -> None: ... def resetwarnings() -> None: ... class _OptionError(Exception): ... class WarningMessage: message: Warning | str - category: Type[Warning] + category: type[Warning] filename: str lineno: int file: TextIO | None @@ -25,7 +25,7 @@ class WarningMessage: def __init__( self, message: Warning | str, - category: Type[Warning], + category: type[Warning], filename: str, lineno: int, file: TextIO | None = ..., @@ -39,13 +39,13 @@ class catch_warnings: def __new__(cls, *, record: Literal[True], module: ModuleType | None = ...) -> _catch_warnings_with_records: ... @overload def __new__(cls, *, record: bool, module: ModuleType | None = ...) -> catch_warnings: ... - def __enter__(self) -> List[WarningMessage] | None: ... + def __enter__(self) -> list[WarningMessage] | None: ... 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: ... class _catch_warnings_without_records(catch_warnings): def __enter__(self) -> None: ... class _catch_warnings_with_records(catch_warnings): - def __enter__(self) -> List[WarningMessage]: ... + def __enter__(self) -> list[WarningMessage]: ... diff --git a/mypy/typeshed/stdlib/@python2/wave.pyi b/mypy/typeshed/stdlib/@python2/wave.pyi index 0e9fe612cd24..ceae301145d8 100644 --- a/mypy/typeshed/stdlib/@python2/wave.pyi +++ b/mypy/typeshed/stdlib/@python2/wave.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, BinaryIO, NoReturn, Text, Tuple, Union +from typing import IO, Any, BinaryIO, NoReturn, Text, Union _File = Union[Text, IO[bytes]] @@ -6,7 +6,7 @@ class Error(Exception): ... WAVE_FORMAT_PCM: int -_wave_params = Tuple[int, int, int, int, str, str] +_wave_params = tuple[int, int, int, int, str, str] class Wave_read: def __init__(self, f: _File) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/weakref.pyi b/mypy/typeshed/stdlib/@python2/weakref.pyi index 6467f3a7517f..8c65ab21a568 100644 --- a/mypy/typeshed/stdlib/@python2/weakref.pyi +++ b/mypy/typeshed/stdlib/@python2/weakref.pyi @@ -1,5 +1,5 @@ from _weakrefset import WeakSet as WeakSet -from typing import Any, Callable, Generic, Iterable, Iterator, List, Mapping, MutableMapping, Tuple, Type, TypeVar, overload +from typing import Any, Callable, Generic, Iterable, Iterator, Mapping, MutableMapping, TypeVar, overload from _weakref import ( CallableProxyType as CallableProxyType, @@ -12,18 +12,17 @@ from _weakref import ( ) from exceptions import ReferenceError as ReferenceError -_S = TypeVar("_S") _T = TypeVar("_T") _KT = TypeVar("_KT") _VT = TypeVar("_VT") -ProxyTypes: Tuple[Type[Any], ...] +ProxyTypes: tuple[type[Any], ...] class WeakValueDictionary(MutableMapping[_KT, _VT]): @overload def __init__(self) -> None: ... @overload - def __init__(self, __other: Mapping[_KT, _VT] | Iterable[Tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __init__(self, __other: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... def __len__(self) -> int: ... def __getitem__(self, k: _KT) -> _VT: ... def __setitem__(self, k: _KT, v: _VT) -> None: ... @@ -31,16 +30,15 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): def has_key(self, key: object) -> bool: ... def __contains__(self, o: object) -> bool: ... def __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... def copy(self) -> WeakValueDictionary[_KT, _VT]: ... - def keys(self) -> List[_KT]: ... - def values(self) -> List[_VT]: ... - def items(self) -> List[Tuple[_KT, _VT]]: ... + def keys(self) -> list[_KT]: ... + def values(self) -> list[_VT]: ... + def items(self) -> list[tuple[_KT, _VT]]: ... def iterkeys(self) -> Iterator[_KT]: ... def itervalues(self) -> Iterator[_VT]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def iteritems(self) -> Iterator[tuple[_KT, _VT]]: ... def itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: ... - def valuerefs(self) -> List[KeyedRef[_KT, _VT]]: ... + def valuerefs(self) -> list[KeyedRef[_KT, _VT]]: ... class KeyedRef(ref[_T], Generic[_KT, _T]): key: _KT @@ -52,7 +50,7 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): @overload def __init__(self, dict: None = ...) -> None: ... @overload - def __init__(self, dict: Mapping[_KT, _VT] | Iterable[Tuple[_KT, _VT]]) -> None: ... + def __init__(self, dict: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]]) -> None: ... def __len__(self) -> int: ... def __getitem__(self, k: _KT) -> _VT: ... def __setitem__(self, k: _KT, v: _VT) -> None: ... @@ -60,13 +58,12 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def has_key(self, key: object) -> bool: ... def __contains__(self, o: object) -> bool: ... def __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... def copy(self) -> WeakKeyDictionary[_KT, _VT]: ... - def keys(self) -> List[_KT]: ... - def values(self) -> List[_VT]: ... - def items(self) -> List[Tuple[_KT, _VT]]: ... + def keys(self) -> list[_KT]: ... + def values(self) -> list[_VT]: ... + def items(self) -> list[tuple[_KT, _VT]]: ... def iterkeys(self) -> Iterator[_KT]: ... def itervalues(self) -> Iterator[_VT]: ... - def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... + def iteritems(self) -> Iterator[tuple[_KT, _VT]]: ... def iterkeyrefs(self) -> Iterator[ref[_KT]]: ... - def keyrefs(self) -> List[ref[_KT]]: ... + def keyrefs(self) -> list[ref[_KT]]: ... diff --git a/mypy/typeshed/stdlib/@python2/webbrowser.pyi b/mypy/typeshed/stdlib/@python2/webbrowser.pyi index f634bc11ca7d..8f1c8b060b4c 100644 --- a/mypy/typeshed/stdlib/@python2/webbrowser.pyi +++ b/mypy/typeshed/stdlib/@python2/webbrowser.pyi @@ -1,5 +1,5 @@ import sys -from typing import Callable, List, Sequence, Text +from typing import Callable, Sequence, Text class Error(Exception): ... @@ -12,7 +12,7 @@ def open_new(url: Text) -> bool: ... def open_new_tab(url: Text) -> bool: ... class BaseBrowser: - args: List[str] + args: list[str] name: str basename: str def __init__(self, name: Text = ...) -> None: ... @@ -21,7 +21,7 @@ class BaseBrowser: def open_new_tab(self, url: Text) -> bool: ... class GenericBrowser(BaseBrowser): - args: List[str] + args: list[str] name: str basename: str def __init__(self, name: Text | Sequence[Text]) -> None: ... @@ -31,45 +31,45 @@ class BackgroundBrowser(GenericBrowser): def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... class UnixBrowser(BaseBrowser): - raise_opts: List[str] | None + raise_opts: list[str] | None background: bool redirect_stdout: bool - remote_args: List[str] + remote_args: list[str] remote_action: str remote_action_newwin: str remote_action_newtab: str def open(self, url: Text, new: int = ..., autoraise: bool = ...) -> bool: ... class Mozilla(UnixBrowser): - remote_args: List[str] + remote_args: list[str] remote_action: str remote_action_newwin: str remote_action_newtab: str background: bool class Galeon(UnixBrowser): - raise_opts: List[str] - remote_args: List[str] + raise_opts: list[str] + remote_args: list[str] remote_action: str remote_action_newwin: str background: bool class Chrome(UnixBrowser): - remote_args: List[str] + remote_args: list[str] remote_action: str remote_action_newwin: str remote_action_newtab: str background: bool class Opera(UnixBrowser): - remote_args: List[str] + remote_args: list[str] remote_action: str remote_action_newwin: str remote_action_newtab: str background: bool class Elinks(UnixBrowser): - remote_args: List[str] + remote_args: list[str] remote_action: str remote_action_newwin: str remote_action_newtab: str diff --git a/mypy/typeshed/stdlib/@python2/wsgiref/handlers.pyi b/mypy/typeshed/stdlib/@python2/wsgiref/handlers.pyi index d7e35ba8aff6..4dd63ac75035 100644 --- a/mypy/typeshed/stdlib/@python2/wsgiref/handlers.pyi +++ b/mypy/typeshed/stdlib/@python2/wsgiref/handlers.pyi @@ -1,17 +1,17 @@ from abc import abstractmethod from types import TracebackType -from typing import IO, Callable, List, MutableMapping, Optional, Text, Tuple, Type +from typing import IO, Callable, MutableMapping, Optional, Text from .headers import Headers from .types import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment from .util import FileWrapper -_exc_info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_exc_info = tuple[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]] def format_date_time(timestamp: float | None) -> str: ... # undocumented class BaseHandler: - wsgi_version: Tuple[int, int] # undocumented + wsgi_version: tuple[int, int] # undocumented wsgi_multithread: bool wsgi_multiprocess: bool wsgi_run_once: bool @@ -22,12 +22,12 @@ class BaseHandler: os_environ: MutableMapping[str, str] - wsgi_file_wrapper: Type[FileWrapper] | None - headers_class: Type[Headers] # undocumented + wsgi_file_wrapper: type[FileWrapper] | None + headers_class: type[Headers] # undocumented traceback_limit: int | None error_status: str - error_headers: List[Tuple[Text, Text]] + error_headers: list[tuple[Text, Text]] error_body: bytes def run(self, application: WSGIApplication) -> None: ... def setup_environ(self) -> None: ... @@ -36,7 +36,7 @@ class BaseHandler: def set_content_length(self) -> None: ... def cleanup_headers(self) -> None: ... def start_response( - self, status: Text, headers: List[Tuple[Text, Text]], exc_info: _exc_info | None = ... + self, status: Text, headers: list[tuple[Text, Text]], exc_info: _exc_info | None = ... ) -> Callable[[bytes], None]: ... def send_preamble(self) -> None: ... def write(self, data: bytes) -> None: ... @@ -48,7 +48,7 @@ class BaseHandler: def client_is_modern(self) -> bool: ... def log_exception(self, exc_info: _exc_info) -> None: ... def handle_error(self) -> None: ... - def error_output(self, environ: WSGIEnvironment, start_response: StartResponse) -> List[bytes]: ... + def error_output(self, environ: WSGIEnvironment, start_response: StartResponse) -> list[bytes]: ... @abstractmethod def _write(self, data: bytes) -> None: ... @abstractmethod diff --git a/mypy/typeshed/stdlib/@python2/wsgiref/headers.pyi b/mypy/typeshed/stdlib/@python2/wsgiref/headers.pyi index 08061fee7664..5c939a342510 100644 --- a/mypy/typeshed/stdlib/@python2/wsgiref/headers.pyi +++ b/mypy/typeshed/stdlib/@python2/wsgiref/headers.pyi @@ -1,6 +1,6 @@ -from typing import List, Pattern, Tuple, overload +from typing import Pattern, overload -_HeaderList = List[Tuple[str, str]] +_HeaderList = list[tuple[str, str]] tspecials: Pattern[str] # undocumented @@ -12,13 +12,13 @@ class Headers: def __getitem__(self, name: str) -> str | None: ... def has_key(self, name: str) -> bool: ... def __contains__(self, name: str) -> bool: ... - def get_all(self, name: str) -> List[str]: ... + def get_all(self, name: str) -> list[str]: ... @overload def get(self, name: str, default: str) -> str: ... @overload def get(self, name: str, default: str | None = ...) -> str | None: ... - def keys(self) -> List[str]: ... - def values(self) -> List[str]: ... + def keys(self) -> list[str]: ... + def values(self) -> list[str]: ... def items(self) -> _HeaderList: ... def setdefault(self, name: str, value: str) -> str: ... def add_header(self, _name: str, _value: str | None, **_params: str | None) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/wsgiref/simple_server.pyi b/mypy/typeshed/stdlib/@python2/wsgiref/simple_server.pyi index a74a26fed935..6faba328f935 100644 --- a/mypy/typeshed/stdlib/@python2/wsgiref/simple_server.pyi +++ b/mypy/typeshed/stdlib/@python2/wsgiref/simple_server.pyi @@ -1,5 +1,5 @@ from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer -from typing import List, Type, TypeVar, overload +from typing import TypeVar, overload from .handlers import SimpleHandler from .types import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment @@ -25,13 +25,13 @@ class WSGIRequestHandler(BaseHTTPRequestHandler): def get_stderr(self) -> ErrorStream: ... def handle(self) -> None: ... -def demo_app(environ: WSGIEnvironment, start_response: StartResponse) -> List[bytes]: ... +def demo_app(environ: WSGIEnvironment, start_response: StartResponse) -> list[bytes]: ... _S = TypeVar("_S", bound=WSGIServer) @overload -def make_server(host: str, port: int, app: WSGIApplication, *, handler_class: Type[WSGIRequestHandler] = ...) -> WSGIServer: ... +def make_server(host: str, port: int, app: WSGIApplication, *, handler_class: type[WSGIRequestHandler] = ...) -> WSGIServer: ... @overload def make_server( - host: str, port: int, app: WSGIApplication, server_class: Type[_S], handler_class: Type[WSGIRequestHandler] = ... + host: str, port: int, app: WSGIApplication, server_class: type[_S], handler_class: type[WSGIRequestHandler] = ... ) -> _S: ... diff --git a/mypy/typeshed/stdlib/@python2/xdrlib.pyi b/mypy/typeshed/stdlib/@python2/xdrlib.pyi index 378504c37227..f59843f8ee9d 100644 --- a/mypy/typeshed/stdlib/@python2/xdrlib.pyi +++ b/mypy/typeshed/stdlib/@python2/xdrlib.pyi @@ -1,4 +1,4 @@ -from typing import Callable, List, Sequence, TypeVar +from typing import Callable, Sequence, TypeVar _T = TypeVar("_T") @@ -50,6 +50,6 @@ class Unpacker: def unpack_string(self) -> bytes: ... def unpack_opaque(self) -> bytes: ... def unpack_bytes(self) -> bytes: ... - def unpack_list(self, unpack_item: Callable[[], _T]) -> List[_T]: ... - def unpack_farray(self, n: int, unpack_item: Callable[[], _T]) -> List[_T]: ... - def unpack_array(self, unpack_item: Callable[[], _T]) -> List[_T]: ... + def unpack_list(self, unpack_item: Callable[[], _T]) -> list[_T]: ... + def unpack_farray(self, n: int, unpack_item: Callable[[], _T]) -> list[_T]: ... + def unpack_array(self, unpack_item: Callable[[], _T]) -> list[_T]: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/domreg.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/domreg.pyi index 2496b3884ea1..b9e2dd9eb263 100644 --- a/mypy/typeshed/stdlib/@python2/xml/dom/domreg.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/dom/domreg.pyi @@ -1,8 +1,8 @@ from _typeshed.xml import DOMImplementation -from typing import Callable, Dict, Iterable, Tuple +from typing import Callable, Iterable -well_known_implementations: Dict[str, str] -registered: Dict[str, Callable[[], DOMImplementation]] +well_known_implementations: dict[str, str] +registered: dict[str, Callable[[], DOMImplementation]] def registerDOMImplementation(name: str, factory: Callable[[], DOMImplementation]) -> None: ... -def getDOMImplementation(name: str | None = ..., features: str | Iterable[Tuple[str, str | None]] = ...) -> DOMImplementation: ... +def getDOMImplementation(name: str | None = ..., features: str | Iterable[tuple[str, str | None]] = ...) -> DOMImplementation: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi index e9b0395ab50d..254f8a0c1657 100644 --- a/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/dom/minicompat.pyi @@ -1,17 +1,17 @@ -from typing import Any, Iterable, List, Tuple, Type, TypeVar +from typing import Any, Iterable, TypeVar _T = TypeVar("_T") -StringTypes: Tuple[Type[str]] +StringTypes: tuple[type[str]] -class NodeList(List[_T]): +class NodeList(list[_T]): length: int def item(self, index: int) -> _T | None: ... -class EmptyNodeList(Tuple[Any, ...]): +class EmptyNodeList(tuple[Any, ...]): length: int def item(self, index: int) -> None: ... def __add__(self, other: Iterable[_T]) -> NodeList[_T]: ... # type: ignore def __radd__(self, other: Iterable[_T]) -> NodeList[_T]: ... -def defproperty(klass: Type[Any], name: str, doc: str) -> None: ... +def defproperty(klass: type[Any], name: str, doc: str) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/dom/minidom.pyi b/mypy/typeshed/stdlib/@python2/xml/dom/minidom.pyi index ed46ac4561ec..10a0ddd0375b 100644 --- a/mypy/typeshed/stdlib/@python2/xml/dom/minidom.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/dom/minidom.pyi @@ -1,10 +1,9 @@ import xml.dom -from typing import IO, Any, Text as _Text, TypeVar +from _typeshed import Self +from typing import IO, Any, Text as _Text from xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS from xml.sax.xmlreader import XMLReader -_T = TypeVar("_T") - def parse(file: str | IO[Any], parser: XMLReader | None = ..., bufsize: int | None = ...): ... def parseString(string: bytes | _Text, parser: XMLReader | None = ...): ... def getDOMImplementation(features=...): ... @@ -32,7 +31,7 @@ class Node(xml.dom.Node): def setUserData(self, key, data, handler): ... childNodes: Any def unlink(self) -> None: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, et, ev, tb) -> None: ... class DocumentFragment(Node): diff --git a/mypy/typeshed/stdlib/@python2/xml/etree/ElementPath.pyi b/mypy/typeshed/stdlib/@python2/xml/etree/ElementPath.pyi index 02fe84567543..5a2dd69c1bee 100644 --- a/mypy/typeshed/stdlib/@python2/xml/etree/ElementPath.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/etree/ElementPath.pyi @@ -1,14 +1,14 @@ -from typing import Callable, Dict, Generator, List, Pattern, Tuple, TypeVar +from typing import Callable, Generator, Pattern, TypeVar from xml.etree.ElementTree import Element xpath_tokenizer_re: Pattern[str] -_token = Tuple[str, str] +_token = tuple[str, str] _next = Callable[[], _token] -_callback = Callable[[_SelectorContext, List[Element]], Generator[Element, None, None]] +_callback = Callable[[_SelectorContext, list[Element]], Generator[Element, None, None]] -def xpath_tokenizer(pattern: str, namespaces: Dict[str, str] | None = ...) -> Generator[_token, None, None]: ... -def get_parent_map(context: _SelectorContext) -> Dict[Element, Element]: ... +def xpath_tokenizer(pattern: str, namespaces: dict[str, str] | None = ...) -> Generator[_token, None, None]: ... +def get_parent_map(context: _SelectorContext) -> dict[Element, Element]: ... def prepare_child(next: _next, token: _token) -> _callback: ... def prepare_star(next: _next, token: _token) -> _callback: ... def prepare_self(next: _next, token: _token) -> _callback: ... @@ -16,16 +16,16 @@ def prepare_descendant(next: _next, token: _token) -> _callback: ... def prepare_parent(next: _next, token: _token) -> _callback: ... def prepare_predicate(next: _next, token: _token) -> _callback: ... -ops: Dict[str, Callable[[_next, _token], _callback]] +ops: dict[str, Callable[[_next, _token], _callback]] class _SelectorContext: - parent_map: Dict[Element, Element] | None + parent_map: dict[Element, Element] | None root: Element def __init__(self, root: Element) -> None: ... _T = TypeVar("_T") -def iterfind(elem: Element, path: str, namespaces: Dict[str, str] | None = ...) -> Generator[Element, None, None]: ... -def find(elem: Element, path: str, namespaces: Dict[str, str] | None = ...) -> Element | None: ... -def findall(elem: Element, path: str, namespaces: Dict[str, str] | None = ...) -> List[Element]: ... -def findtext(elem: Element, path: str, default: _T | None = ..., namespaces: Dict[str, str] | None = ...) -> _T | str: ... +def iterfind(elem: Element, path: str, namespaces: dict[str, str] | None = ...) -> Generator[Element, None, None]: ... +def find(elem: Element, path: str, namespaces: dict[str, str] | None = ...) -> Element | None: ... +def findall(elem: Element, path: str, namespaces: dict[str, str] | None = ...) -> list[Element]: ... +def findtext(elem: Element, path: str, default: _T | None = ..., namespaces: dict[str, str] | None = ...) -> _T | str: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi index a7a0a1c65f46..a6cbae35d04f 100644 --- a/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/etree/ElementTree.pyi @@ -3,17 +3,14 @@ from typing import ( IO, Any, Callable, - Dict, Generator, ItemsView, Iterable, Iterator, KeysView, - List, MutableSequence, Sequence, Text, - Tuple, TypeVar, Union, overload, @@ -23,7 +20,7 @@ VERSION: str class ParseError(SyntaxError): code: int - position: Tuple[int, int] + position: tuple[int, int] def iselement(element: object) -> bool: ... @@ -53,31 +50,31 @@ _file_or_filename = Union[Text, FileDescriptor, IO[Any]] class Element(MutableSequence[Element]): tag: _str_result_type - attrib: Dict[_str_result_type, _str_result_type] + attrib: dict[_str_result_type, _str_result_type] text: _str_result_type | None tail: _str_result_type | None def __init__( self, tag: _str_argument_type | Callable[..., Element], - attrib: Dict[_str_argument_type, _str_argument_type] = ..., + attrib: dict[_str_argument_type, _str_argument_type] = ..., **extra: _str_argument_type, ) -> None: ... def append(self, __subelement: Element) -> None: ... def clear(self) -> None: ... def extend(self, __elements: Iterable[Element]) -> None: ... def find( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> Element | None: ... def findall( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... - ) -> List[Element]: ... + self, path: _str_argument_type, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... + ) -> list[Element]: ... @overload def findtext( - self, path: _str_argument_type, default: None = ..., namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, default: None = ..., namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> _str_result_type | None: ... @overload def findtext( - self, path: _str_argument_type, default: _T, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, default: _T, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> _T | _str_result_type: ... @overload def get(self, key: _str_argument_type, default: None = ...) -> _str_result_type | None: ... @@ -87,11 +84,11 @@ class Element(MutableSequence[Element]): def items(self) -> ItemsView[_str_result_type, _str_result_type]: ... def iter(self, tag: _str_argument_type | None = ...) -> Generator[Element, None, None]: ... def iterfind( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> Generator[Element, None, None]: ... def itertext(self) -> Generator[_str_result_type, None, None]: ... def keys(self) -> KeysView[_str_result_type]: ... - def makeelement(self, __tag: _str_argument_type, __attrib: Dict[_str_argument_type, _str_argument_type]) -> Element: ... + def makeelement(self, __tag: _str_argument_type, __attrib: dict[_str_argument_type, _str_argument_type]) -> Element: ... def remove(self, __subelement: Element) -> None: ... def set(self, __key: _str_argument_type, __value: _str_argument_type) -> None: ... def __delitem__(self, i: int | slice) -> None: ... @@ -104,13 +101,13 @@ class Element(MutableSequence[Element]): def __setitem__(self, i: int, o: Element) -> None: ... @overload def __setitem__(self, s: slice, o: Iterable[Element]) -> None: ... - def getchildren(self) -> List[Element]: ... - def getiterator(self, tag: _str_argument_type | None = ...) -> List[Element]: ... + def getchildren(self) -> list[Element]: ... + def getiterator(self, tag: _str_argument_type | None = ...) -> list[Element]: ... def SubElement( parent: Element, tag: _str_argument_type, - attrib: Dict[_str_argument_type, _str_argument_type] = ..., + attrib: dict[_str_argument_type, _str_argument_type] = ..., **extra: _str_argument_type, ) -> Element: ... def Comment(text: _str_argument_type | None = ...) -> Element: ... @@ -127,23 +124,23 @@ class ElementTree: def getroot(self) -> Element: ... def parse(self, source: _file_or_filename, parser: XMLParser | None = ...) -> Element: ... def iter(self, tag: _str_argument_type | None = ...) -> Generator[Element, None, None]: ... - def getiterator(self, tag: _str_argument_type | None = ...) -> List[Element]: ... + def getiterator(self, tag: _str_argument_type | None = ...) -> list[Element]: ... def find( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> Element | None: ... @overload def findtext( - self, path: _str_argument_type, default: None = ..., namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, default: None = ..., namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> _str_result_type | None: ... @overload def findtext( - self, path: _str_argument_type, default: _T, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, default: _T, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> _T | _str_result_type: ... def findall( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... - ) -> List[Element]: ... + self, path: _str_argument_type, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... + ) -> list[Element]: ... def iterfind( - self, path: _str_argument_type, namespaces: Dict[_str_argument_type, _str_argument_type] | None = ... + self, path: _str_argument_type, namespaces: dict[_str_argument_type, _str_argument_type] | None = ... ) -> Generator[Element, None, None]: ... def write( self, @@ -157,14 +154,14 @@ class ElementTree: def register_namespace(prefix: _str_argument_type, uri: _str_argument_type) -> None: ... def tostring(element: Element, encoding: str | None = ..., method: str | None = ...) -> bytes: ... -def tostringlist(element: Element, encoding: str | None = ..., method: str | None = ...) -> List[bytes]: ... +def tostringlist(element: Element, encoding: str | None = ..., method: str | None = ...) -> list[bytes]: ... def dump(elem: Element) -> None: ... def parse(source: _file_or_filename, parser: XMLParser | None = ...) -> ElementTree: ... def iterparse( source: _file_or_filename, events: Sequence[str] | None = ..., parser: XMLParser | None = ... -) -> Iterator[Tuple[str, Any]]: ... +) -> Iterator[tuple[str, Any]]: ... def XML(text: _parser_input_type, parser: XMLParser | None = ...) -> Element: ... -def XMLID(text: _parser_input_type, parser: XMLParser | None = ...) -> Tuple[Element, Dict[_str_result_type, Element]]: ... +def XMLID(text: _parser_input_type, parser: XMLParser | None = ...) -> tuple[Element, dict[_str_result_type, Element]]: ... # This is aliased to XML in the source. fromstring = XML @@ -180,13 +177,13 @@ def fromstringlist(sequence: Sequence[_parser_input_type], parser: XMLParser | N # TreeBuilder is called by client code (they could pass strs, bytes or whatever); # but we don't want to use a too-broad type, or it would be too hard to write # elementfactories. -_ElementFactory = Callable[[Any, Dict[Any, Any]], Element] +_ElementFactory = Callable[[Any, dict[Any, Any]], Element] class TreeBuilder: def __init__(self, element_factory: _ElementFactory | None = ...) -> None: ... def close(self) -> Element: ... def data(self, __data: _parser_input_type) -> None: ... - def start(self, __tag: _parser_input_type, __attrs: Dict[_parser_input_type, _parser_input_type]) -> Element: ... + def start(self, __tag: _parser_input_type, __attrs: dict[_parser_input_type, _parser_input_type]) -> Element: ... def end(self, __tag: _parser_input_type) -> Element: ... class XMLParser: diff --git a/mypy/typeshed/stdlib/@python2/xml/sax/__init__.pyi b/mypy/typeshed/stdlib/@python2/xml/sax/__init__.pyi index 0c6da9a87d13..7a35805f9f16 100644 --- a/mypy/typeshed/stdlib/@python2/xml/sax/__init__.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/sax/__init__.pyi @@ -1,4 +1,4 @@ -from typing import IO, Any, List, NoReturn, Text +from typing import IO, Any, NoReturn, Text from xml.sax.handler import ContentHandler, ErrorHandler from xml.sax.xmlreader import Locator, XMLReader @@ -19,9 +19,9 @@ class SAXNotRecognizedException(SAXException): ... class SAXNotSupportedException(SAXException): ... class SAXReaderNotAvailable(SAXNotSupportedException): ... -default_parser_list: List[str] +default_parser_list: list[str] -def make_parser(parser_list: List[str] = ...) -> XMLReader: ... +def make_parser(parser_list: list[str] = ...) -> XMLReader: ... def parse(source: str | IO[str] | IO[bytes], handler: ContentHandler, errorHandler: ErrorHandler = ...) -> None: ... def parseString(string: bytes | Text, handler: ContentHandler, errorHandler: ErrorHandler | None = ...) -> None: ... def _create_parser(parser_name: str) -> XMLReader: ... diff --git a/mypy/typeshed/stdlib/@python2/xml/sax/xmlreader.pyi b/mypy/typeshed/stdlib/@python2/xml/sax/xmlreader.pyi index 8afc566b16a1..684e9cef1f42 100644 --- a/mypy/typeshed/stdlib/@python2/xml/sax/xmlreader.pyi +++ b/mypy/typeshed/stdlib/@python2/xml/sax/xmlreader.pyi @@ -1,4 +1,4 @@ -from typing import Mapping, Tuple +from typing import Mapping class XMLReader: def __init__(self) -> None: ... @@ -64,7 +64,7 @@ class AttributesImpl: def values(self): ... class AttributesNSImpl(AttributesImpl): - def __init__(self, attrs: Mapping[Tuple[str, str], str], qnames: Mapping[Tuple[str, str], str]) -> None: ... + def __init__(self, attrs: Mapping[tuple[str, str], str], qnames: Mapping[tuple[str, str], str]) -> None: ... def getValueByQName(self, name): ... def getNameByQName(self, name): ... def getQNameByName(self, name): ... diff --git a/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi b/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi index 5a7d0fc34f0e..0defb96bffb8 100644 --- a/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi +++ b/mypy/typeshed/stdlib/@python2/xmlrpclib.pyi @@ -5,14 +5,14 @@ from ssl import SSLContext from StringIO import StringIO from time import struct_time from types import InstanceType -from typing import IO, Any, AnyStr, Callable, Iterable, List, Mapping, MutableMapping, Tuple, Type, Union +from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, MutableMapping, Union _Unmarshaller = Any -_timeTuple = Tuple[int, int, int, int, int, int, int, int, int] +_timeTuple = tuple[int, int, int, int, int, int, int, int, int] # Represents types that can be compared against a DateTime object _dateTimeComp = Union[unicode, DateTime, datetime] # A "host description" used by Transport factories -_hostDesc = Union[str, Tuple[str, Mapping[Any, Any]]] +_hostDesc = Union[str, tuple[str, Mapping[Any, Any]]] def escape(s: AnyStr, replace: Callable[[AnyStr, AnyStr, AnyStr], AnyStr] = ...) -> AnyStr: ... @@ -47,13 +47,13 @@ class Fault(Error): faultString: str def __init__(self, faultCode: Any, faultString: str, **extra: Any) -> None: ... -boolean: Type[bool] -Boolean: Type[bool] +boolean: type[bool] +Boolean: type[bool] class DateTime: value: str def __init__(self, value: str | unicode | datetime | float | int | _timeTuple | struct_time = ...) -> None: ... - def make_comparable(self, other: _dateTimeComp) -> Tuple[unicode, unicode]: ... + def make_comparable(self, other: _dateTimeComp) -> tuple[unicode, unicode]: ... def __lt__(self, other: _dateTimeComp) -> bool: ... def __le__(self, other: _dateTimeComp) -> bool: ... def __gt__(self, other: _dateTimeComp) -> bool: ... @@ -72,7 +72,7 @@ class Binary: def decode(self, data: str) -> None: ... def encode(self, out: IO[str]) -> None: ... -WRAPPERS: Tuple[Type[Any], ...] +WRAPPERS: tuple[type[Any], ...] # Still part of the public API, but see http://bugs.python.org/issue1773632 FastParser: None @@ -112,8 +112,8 @@ class Marshaller: | float | str | unicode - | List[Any] - | Tuple[Any, ...] + | list[Any] + | tuple[Any, ...] | Mapping[Any, Any] | datetime | InstanceType @@ -150,7 +150,7 @@ class Marshaller: class Unmarshaller: def append(self, object: Any) -> None: ... def __init__(self, use_datetime: bool = ...) -> None: ... - def close(self) -> Tuple[Any, ...]: ... + def close(self) -> tuple[Any, ...]: ... def getmethodname(self) -> str | None: ... def xml(self, encoding: str, standalone: bool) -> None: ... def start(self, tag: str, attrs: Any) -> None: ... @@ -173,25 +173,25 @@ class Unmarshaller: def end_methodName(self, data: str) -> None: ... class _MultiCallMethod: - def __init__(self, call_list: List[Tuple[str, Tuple[Any, ...]]], name: str) -> None: ... + def __init__(self, call_list: list[tuple[str, tuple[Any, ...]]], name: str) -> None: ... class MultiCallIterator: - def __init__(self, results: List[Any]) -> None: ... + def __init__(self, results: list[Any]) -> None: ... class MultiCall: def __init__(self, server: ServerProxy) -> None: ... def __getattr__(self, name: str) -> _MultiCallMethod: ... def __call__(self) -> MultiCallIterator: ... -def getparser(use_datetime: bool = ...) -> Tuple[ExpatParser | SlowParser, Unmarshaller]: ... +def getparser(use_datetime: bool = ...) -> tuple[ExpatParser | SlowParser, Unmarshaller]: ... def dumps( - params: Tuple[Any, ...] | Fault, + params: tuple[Any, ...] | Fault, methodname: str | None = ..., methodresponse: bool | None = ..., encoding: str | None = ..., allow_none: bool = ..., ) -> str: ... -def loads(data: str, use_datetime: bool = ...) -> Tuple[Tuple[Any, ...], str | None]: ... +def loads(data: str, use_datetime: bool = ...) -> tuple[tuple[Any, ...], str | None]: ... def gzip_encode(data: str) -> str: ... def gzip_decode(data: str, max_decode: int = ...) -> str: ... @@ -201,7 +201,7 @@ class GzipDecodedResponse(GzipFile): def close(self): ... class _Method: - def __init__(self, send: Callable[[str, Tuple[Any, ...]], Any], name: str) -> None: ... + def __init__(self, send: Callable[[str, tuple[Any, ...]], Any], name: str) -> None: ... def __getattr__(self, name: str) -> _Method: ... def __call__(self, *args: Any) -> Any: ... @@ -210,18 +210,18 @@ class Transport: accept_gzip_encoding: bool encode_threshold: int | None def __init__(self, use_datetime: bool = ...) -> None: ... - def request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> Tuple[Any, ...]: ... + def request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> tuple[Any, ...]: ... verbose: bool - def single_request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> Tuple[Any, ...]: ... - def getparser(self) -> Tuple[ExpatParser | SlowParser, Unmarshaller]: ... - def get_host_info(self, host: _hostDesc) -> Tuple[str, List[Tuple[str, str]] | None, Mapping[Any, Any] | None]: ... + def single_request(self, host: _hostDesc, handler: str, request_body: str, verbose: bool = ...) -> tuple[Any, ...]: ... + def getparser(self) -> tuple[ExpatParser | SlowParser, Unmarshaller]: ... + def get_host_info(self, host: _hostDesc) -> tuple[str, list[tuple[str, str]] | None, Mapping[Any, Any] | None]: ... def make_connection(self, host: _hostDesc) -> HTTPConnection: ... def close(self) -> None: ... def send_request(self, connection: HTTPConnection, handler: str, request_body: str) -> None: ... def send_host(self, connection: HTTPConnection, host: str) -> None: ... def send_user_agent(self, connection: HTTPConnection) -> None: ... def send_content(self, connection: HTTPConnection, request_body: str) -> None: ... - def parse_response(self, response: HTTPResponse) -> Tuple[Any, ...]: ... + def parse_response(self, response: HTTPResponse) -> tuple[Any, ...]: ... class SafeTransport(Transport): def __init__(self, use_datetime: bool = ..., context: SSLContext | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/@python2/zipfile.pyi b/mypy/typeshed/stdlib/@python2/zipfile.pyi index 5a0879492a88..b5db240bd89e 100644 --- a/mypy/typeshed/stdlib/@python2/zipfile.pyi +++ b/mypy/typeshed/stdlib/@python2/zipfile.pyi @@ -1,10 +1,10 @@ import io from _typeshed import StrPath from types import TracebackType -from typing import IO, Any, Callable, Dict, Iterable, List, Pattern, Protocol, Sequence, Text, Tuple, Type, Union +from typing import IO, Any, Callable, Iterable, Pattern, Protocol, Sequence, Text, Union _SZI = Union[Text, ZipInfo] -_DT = Tuple[int, int, int, int, int, int] +_DT = tuple[int, int, int, int, int, int] class BadZipfile(Exception): ... @@ -18,7 +18,7 @@ class ZipExtFile(io.BufferedIOBase): PATTERN: Pattern[str] = ... - newlines: List[bytes] | None + newlines: list[bytes] | None mode: str name: str def __init__( @@ -31,7 +31,6 @@ class ZipExtFile(io.BufferedIOBase): ) -> None: ... def read(self, n: int | None = ...) -> bytes: ... def readline(self, limit: int = ...) -> bytes: ... # type: ignore - def __repr__(self) -> str: ... def peek(self, n: int = ...) -> bytes: ... def read1(self, n: int | None) -> bytes: ... # type: ignore @@ -42,19 +41,19 @@ class ZipFile: filename: Text | None debug: int comment: bytes - filelist: List[ZipInfo] + filelist: list[ZipInfo] fp: IO[bytes] | None - NameToInfo: Dict[Text, ZipInfo] + NameToInfo: dict[Text, ZipInfo] start_dir: int # undocumented def __init__(self, file: StrPath | IO[bytes], mode: Text = ..., compression: int = ..., allowZip64: bool = ...) -> None: ... def __enter__(self) -> ZipFile: ... 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 close(self) -> None: ... def getinfo(self, name: Text) -> ZipInfo: ... - def infolist(self) -> List[ZipInfo]: ... - def namelist(self) -> List[Text]: ... + def infolist(self) -> list[ZipInfo]: ... + def namelist(self) -> list[Text]: ... def open(self, name: _SZI, mode: Text = ..., pwd: bytes | None = ..., *, force_zip64: bool = ...) -> IO[bytes]: ... def extract(self, member: _SZI, path: StrPath | None = ..., pwd: bytes | None = ...) -> str: ... def extractall(self, path: StrPath | None = ..., members: Iterable[Text] | None = ..., pwd: bytes | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/VERSIONS b/mypy/typeshed/stdlib/VERSIONS index 9b9271117fa7..7422882699c8 100644 --- a/mypy/typeshed/stdlib/VERSIONS +++ b/mypy/typeshed/stdlib/VERSIONS @@ -29,8 +29,8 @@ _compression: 3.6- _csv: 2.7- _curses: 2.7- _decimal: 3.6- -_dummy_thread: 3.6- -_dummy_threading: 2.7- +_dummy_thread: 3.6-3.8 +_dummy_threading: 2.7-3.8 _heapq: 2.7- _imp: 3.6- _json: 2.7- @@ -62,6 +62,13 @@ array: 2.7- ast: 2.7- asynchat: 2.7- asyncio: 3.4- +asyncio.compat: 3.4-3.6 +asyncio.exceptions: 3.8- +asyncio.format_helpers: 3.7- +asyncio.runners: 3.7- +asyncio.staggered: 3.8- +asyncio.threads: 3.9- +asyncio.trsock: 3.8- asyncore: 2.7- atexit: 2.7- audioop: 2.7- @@ -103,8 +110,9 @@ decimal: 2.7- difflib: 2.7- dis: 2.7- distutils: 2.7- +distutils.command.bdist_msi: 2.7-3.10 doctest: 2.7- -dummy_threading: 2.7- +dummy_threading: 2.7-3.8 email: 2.7- encodings: 2.7- ensurepip: 2.7- @@ -138,6 +146,7 @@ imghdr: 2.7- imp: 2.7- importlib: 2.7- importlib.metadata: 3.8- +importlib.metadata._meta: 3.10- importlib.resources: 3.7- inspect: 2.7- io: 2.7- @@ -259,6 +268,8 @@ typing: 3.5- typing_extensions: 2.7- unicodedata: 2.7- unittest: 2.7- +unittest._log: 3.9- +unittest.async_case: 3.8- urllib: 2.7- uu: 2.7- uuid: 2.7- diff --git a/mypy/typeshed/stdlib/_ast.pyi b/mypy/typeshed/stdlib/_ast.pyi index 08725cfc0b77..d1feaf235310 100644 --- a/mypy/typeshed/stdlib/_ast.pyi +++ b/mypy/typeshed/stdlib/_ast.pyi @@ -1,18 +1,17 @@ import sys -import typing from typing import Any, ClassVar from typing_extensions import Literal -PyCF_ONLY_AST: int +PyCF_ONLY_AST: Literal[1024] if sys.version_info >= (3, 8): - PyCF_TYPE_COMMENTS: int - PyCF_ALLOW_TOP_LEVEL_AWAIT: int + PyCF_TYPE_COMMENTS: Literal[4096] + PyCF_ALLOW_TOP_LEVEL_AWAIT: Literal[8192] _identifier = str class AST: - _attributes: ClassVar[typing.Tuple[str, ...]] - _fields: ClassVar[typing.Tuple[str, ...]] + _attributes: ClassVar[tuple[str, ...]] + _fields: ClassVar[tuple[str, ...]] def __init__(self, *args: Any, **kwargs: Any) -> None: ... # TODO: Not all nodes have all of the following attributes lineno: int diff --git a/mypy/typeshed/stdlib/_bisect.pyi b/mypy/typeshed/stdlib/_bisect.pyi index 6da6e7f58823..1f67dadd89a0 100644 --- a/mypy/typeshed/stdlib/_bisect.pyi +++ b/mypy/typeshed/stdlib/_bisect.pyi @@ -1,21 +1,31 @@ import sys -from _typeshed import SupportsLessThan +from _typeshed import SupportsRichComparison from typing import Callable, MutableSequence, Sequence, TypeVar _T = TypeVar("_T") if sys.version_info >= (3, 10): def bisect_left( - a: Sequence[_T], x: _T, lo: int = ..., hi: int | None = ..., *, key: Callable[[_T], SupportsLessThan] | None = ... + a: Sequence[_T], x: _T, lo: int = ..., hi: int | None = ..., *, key: Callable[[_T], SupportsRichComparison] | None = ... ) -> int: ... def bisect_right( - a: Sequence[_T], x: _T, lo: int = ..., hi: int | None = ..., *, key: Callable[[_T], SupportsLessThan] | None = ... + a: Sequence[_T], x: _T, lo: int = ..., hi: int | None = ..., *, key: Callable[[_T], SupportsRichComparison] | None = ... ) -> int: ... def insort_left( - a: MutableSequence[_T], x: _T, lo: int = ..., hi: int | None = ..., *, key: Callable[[_T], SupportsLessThan] | None = ... + a: MutableSequence[_T], + x: _T, + lo: int = ..., + hi: int | None = ..., + *, + key: Callable[[_T], SupportsRichComparison] | None = ..., ) -> None: ... def insort_right( - a: MutableSequence[_T], x: _T, lo: int = ..., hi: int | None = ..., *, key: Callable[[_T], SupportsLessThan] | None = ... + a: MutableSequence[_T], + x: _T, + lo: int = ..., + hi: int | None = ..., + *, + key: Callable[[_T], SupportsRichComparison] | None = ..., ) -> None: ... else: diff --git a/mypy/typeshed/stdlib/_codecs.pyi b/mypy/typeshed/stdlib/_codecs.pyi index 5e4a9ad6da3d..470722a293a3 100644 --- a/mypy/typeshed/stdlib/_codecs.pyi +++ b/mypy/typeshed/stdlib/_codecs.pyi @@ -1,13 +1,13 @@ import codecs import sys -from typing import Any, Callable, Dict, Tuple, Union +from typing import Any, Callable, Union # This type is not exposed; it is defined in unicodeobject.c class _EncodingMap: def size(self) -> int: ... -_MapT = Union[Dict[int, int], _EncodingMap] -_Handler = Callable[[Exception], Tuple[str, int]] +_MapT = Union[dict[int, int], _EncodingMap] +_Handler = Callable[[Exception], tuple[str, int]] def register(__search_function: Callable[[str], Any]) -> None: ... def register_error(__errors: str, __handler: _Handler) -> None: ... @@ -24,10 +24,22 @@ def escape_decode(__data: str | bytes, __errors: str | None = ...) -> tuple[str, def escape_encode(__data: bytes, __errors: str | None = ...) -> tuple[bytes, int]: ... def latin_1_decode(__data: bytes, __errors: str | None = ...) -> tuple[str, int]: ... def latin_1_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... -def raw_unicode_escape_decode(__data: str | bytes, __errors: str | None = ...) -> tuple[str, int]: ... + +if sys.version_info >= (3, 9): + def raw_unicode_escape_decode(__data: str | bytes, __errors: str | None = ..., __final: bool = ...) -> tuple[str, int]: ... + +else: + def raw_unicode_escape_decode(__data: str | bytes, __errors: str | None = ...) -> tuple[str, int]: ... + def raw_unicode_escape_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... def readbuffer_encode(__data: str | bytes, __errors: str | None = ...) -> tuple[bytes, int]: ... -def unicode_escape_decode(__data: str | bytes, __errors: str | None = ...) -> tuple[str, int]: ... + +if sys.version_info >= (3, 9): + def unicode_escape_decode(__data: str | bytes, __errors: str | None = ..., __final: bool = ...) -> tuple[str, int]: ... + +else: + def unicode_escape_decode(__data: str | bytes, __errors: str | None = ...) -> tuple[str, int]: ... + def unicode_escape_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... if sys.version_info < (3, 8): diff --git a/mypy/typeshed/stdlib/_compat_pickle.pyi b/mypy/typeshed/stdlib/_compat_pickle.pyi index 76aba3020321..50fb22442cc9 100644 --- a/mypy/typeshed/stdlib/_compat_pickle.pyi +++ b/mypy/typeshed/stdlib/_compat_pickle.pyi @@ -1,10 +1,8 @@ -from typing import Tuple - IMPORT_MAPPING: dict[str, str] NAME_MAPPING: dict[tuple[str, str], tuple[str, str]] -PYTHON2_EXCEPTIONS: Tuple[str, ...] -MULTIPROCESSING_EXCEPTIONS: Tuple[str, ...] +PYTHON2_EXCEPTIONS: tuple[str, ...] +MULTIPROCESSING_EXCEPTIONS: tuple[str, ...] REVERSE_IMPORT_MAPPING: dict[str, str] REVERSE_NAME_MAPPING: dict[tuple[str, str], tuple[str, str]] -PYTHON3_OSERROR_EXCEPTIONS: Tuple[str, ...] -PYTHON3_IMPORTERROR_EXCEPTIONS: Tuple[str, ...] +PYTHON3_OSERROR_EXCEPTIONS: tuple[str, ...] +PYTHON3_IMPORTERROR_EXCEPTIONS: tuple[str, ...] diff --git a/mypy/typeshed/stdlib/_compression.pyi b/mypy/typeshed/stdlib/_compression.pyi index 8f81847ff492..e71f7d14bd2b 100644 --- a/mypy/typeshed/stdlib/_compression.pyi +++ b/mypy/typeshed/stdlib/_compression.pyi @@ -1,8 +1,8 @@ from _typeshed import WriteableBuffer -from io import BufferedIOBase, RawIOBase -from typing import Any, Callable, Protocol, Tuple, Type +from io import DEFAULT_BUFFER_SIZE, BufferedIOBase, RawIOBase +from typing import Any, Callable, Protocol -BUFFER_SIZE: Any +BUFFER_SIZE = DEFAULT_BUFFER_SIZE class _Reader(Protocol): def read(self, __n: int) -> bytes: ... @@ -16,7 +16,7 @@ class DecompressReader(RawIOBase): self, fp: _Reader, decomp_factory: Callable[..., object], - trailing_error: Type[Exception] | Tuple[Type[Exception], ...] = ..., + trailing_error: type[Exception] | tuple[type[Exception], ...] = ..., **decomp_args: Any, ) -> None: ... def readable(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/_csv.pyi b/mypy/typeshed/stdlib/_csv.pyi index 1dc43780f687..051a5fb81c10 100644 --- a/mypy/typeshed/stdlib/_csv.pyi +++ b/mypy/typeshed/stdlib/_csv.pyi @@ -1,9 +1,10 @@ -from typing import Any, Iterable, Iterator, List, Protocol, Type, Union +from typing import Any, Iterable, Iterator, Protocol, Union +from typing_extensions import Literal -QUOTE_ALL: int -QUOTE_MINIMAL: int -QUOTE_NONE: int -QUOTE_NONNUMERIC: int +QUOTE_ALL: Literal[1] +QUOTE_MINIMAL: Literal[0] +QUOTE_NONE: Literal[3] +QUOTE_NONNUMERIC: Literal[2] class Error(Exception): ... @@ -18,9 +19,9 @@ class Dialect: strict: int def __init__(self) -> None: ... -_DialectLike = Union[str, Dialect, Type[Dialect]] +_DialectLike = Union[str, Dialect, type[Dialect]] -class _reader(Iterator[List[str]]): +class _reader(Iterator[list[str]]): dialect: Dialect line_num: int def __next__(self) -> list[str]: ... @@ -31,7 +32,7 @@ class _writer: def writerows(self, rows: Iterable[Iterable[Any]]) -> None: ... class _Writer(Protocol): - def write(self, s: str) -> Any: ... + def write(self, __s: str) -> object: ... def writer(csvfile: _Writer, dialect: _DialectLike = ..., **fmtparams: Any) -> _writer: ... def reader(csvfile: Iterable[str], dialect: _DialectLike = ..., **fmtparams: Any) -> _reader: ... diff --git a/mypy/typeshed/stdlib/_curses.pyi b/mypy/typeshed/stdlib/_curses.pyi index e0f978c5cae1..9f23eeb1c6dc 100644 --- a/mypy/typeshed/stdlib/_curses.pyi +++ b/mypy/typeshed/stdlib/_curses.pyi @@ -1,548 +1,547 @@ import sys -from typing import IO, Any, BinaryIO, NamedTuple, Union, overload +from _typeshed import SupportsRead +from typing import IO, Any, NamedTuple, Union, overload -_chtype = Union[str, bytes, int] +if sys.platform != "win32": + _chtype = Union[str, bytes, int] -# ACS codes are only initialized after initscr is called -ACS_BBSS: int -ACS_BLOCK: int -ACS_BOARD: int -ACS_BSBS: int -ACS_BSSB: int -ACS_BSSS: int -ACS_BTEE: int -ACS_BULLET: int -ACS_CKBOARD: int -ACS_DARROW: int -ACS_DEGREE: int -ACS_DIAMOND: int -ACS_GEQUAL: int -ACS_HLINE: int -ACS_LANTERN: int -ACS_LARROW: int -ACS_LEQUAL: int -ACS_LLCORNER: int -ACS_LRCORNER: int -ACS_LTEE: int -ACS_NEQUAL: int -ACS_PI: int -ACS_PLMINUS: int -ACS_PLUS: int -ACS_RARROW: int -ACS_RTEE: int -ACS_S1: int -ACS_S3: int -ACS_S7: int -ACS_S9: int -ACS_SBBS: int -ACS_SBSB: int -ACS_SBSS: int -ACS_SSBB: int -ACS_SSBS: int -ACS_SSSB: int -ACS_SSSS: int -ACS_STERLING: int -ACS_TTEE: int -ACS_UARROW: int -ACS_ULCORNER: int -ACS_URCORNER: int -ACS_VLINE: int -ALL_MOUSE_EVENTS: int -A_ALTCHARSET: int -A_ATTRIBUTES: int -A_BLINK: int -A_BOLD: int -A_CHARTEXT: int -A_COLOR: int -A_DIM: int -A_HORIZONTAL: int -A_INVIS: int -if sys.version_info >= (3, 7): - A_ITALIC: int -A_LEFT: int -A_LOW: int -A_NORMAL: int -A_PROTECT: int -A_REVERSE: int -A_RIGHT: int -A_STANDOUT: int -A_TOP: int -A_UNDERLINE: int -A_VERTICAL: int -BUTTON1_CLICKED: int -BUTTON1_DOUBLE_CLICKED: int -BUTTON1_PRESSED: int -BUTTON1_RELEASED: int -BUTTON1_TRIPLE_CLICKED: int -BUTTON2_CLICKED: int -BUTTON2_DOUBLE_CLICKED: int -BUTTON2_PRESSED: int -BUTTON2_RELEASED: int -BUTTON2_TRIPLE_CLICKED: int -BUTTON3_CLICKED: int -BUTTON3_DOUBLE_CLICKED: int -BUTTON3_PRESSED: int -BUTTON3_RELEASED: int -BUTTON3_TRIPLE_CLICKED: int -BUTTON4_CLICKED: int -BUTTON4_DOUBLE_CLICKED: int -BUTTON4_PRESSED: int -BUTTON4_RELEASED: int -BUTTON4_TRIPLE_CLICKED: int -# Darwin ncurses doesn't provide BUTTON5_* constants -if sys.version_info >= (3, 10) and sys.platform != "darwin": - BUTTON5_PRESSED: int - BUTTON5_RELEASED: int - BUTTON5_CLICKED: int - BUTTON5_DOUBLE_CLICKED: int - BUTTON5_TRIPLE_CLICKED: int -BUTTON_ALT: int -BUTTON_CTRL: int -BUTTON_SHIFT: int -COLOR_BLACK: int -COLOR_BLUE: int -COLOR_CYAN: int -COLOR_GREEN: int -COLOR_MAGENTA: int -COLOR_RED: int -COLOR_WHITE: int -COLOR_YELLOW: int -ERR: int -KEY_A1: int -KEY_A3: int -KEY_B2: int -KEY_BACKSPACE: int -KEY_BEG: int -KEY_BREAK: int -KEY_BTAB: int -KEY_C1: int -KEY_C3: int -KEY_CANCEL: int -KEY_CATAB: int -KEY_CLEAR: int -KEY_CLOSE: int -KEY_COMMAND: int -KEY_COPY: int -KEY_CREATE: int -KEY_CTAB: int -KEY_DC: int -KEY_DL: int -KEY_DOWN: int -KEY_EIC: int -KEY_END: int -KEY_ENTER: int -KEY_EOL: int -KEY_EOS: int -KEY_EXIT: int -KEY_F0: int -KEY_F1: int -KEY_F10: int -KEY_F11: int -KEY_F12: int -KEY_F13: int -KEY_F14: int -KEY_F15: int -KEY_F16: int -KEY_F17: int -KEY_F18: int -KEY_F19: int -KEY_F2: int -KEY_F20: int -KEY_F21: int -KEY_F22: int -KEY_F23: int -KEY_F24: int -KEY_F25: int -KEY_F26: int -KEY_F27: int -KEY_F28: int -KEY_F29: int -KEY_F3: int -KEY_F30: int -KEY_F31: int -KEY_F32: int -KEY_F33: int -KEY_F34: int -KEY_F35: int -KEY_F36: int -KEY_F37: int -KEY_F38: int -KEY_F39: int -KEY_F4: int -KEY_F40: int -KEY_F41: int -KEY_F42: int -KEY_F43: int -KEY_F44: int -KEY_F45: int -KEY_F46: int -KEY_F47: int -KEY_F48: int -KEY_F49: int -KEY_F5: int -KEY_F50: int -KEY_F51: int -KEY_F52: int -KEY_F53: int -KEY_F54: int -KEY_F55: int -KEY_F56: int -KEY_F57: int -KEY_F58: int -KEY_F59: int -KEY_F6: int -KEY_F60: int -KEY_F61: int -KEY_F62: int -KEY_F63: int -KEY_F7: int -KEY_F8: int -KEY_F9: int -KEY_FIND: int -KEY_HELP: int -KEY_HOME: int -KEY_IC: int -KEY_IL: int -KEY_LEFT: int -KEY_LL: int -KEY_MARK: int -KEY_MAX: int -KEY_MESSAGE: int -KEY_MIN: int -KEY_MOUSE: int -KEY_MOVE: int -KEY_NEXT: int -KEY_NPAGE: int -KEY_OPEN: int -KEY_OPTIONS: int -KEY_PPAGE: int -KEY_PREVIOUS: int -KEY_PRINT: int -KEY_REDO: int -KEY_REFERENCE: int -KEY_REFRESH: int -KEY_REPLACE: int -KEY_RESET: int -KEY_RESIZE: int -KEY_RESTART: int -KEY_RESUME: int -KEY_RIGHT: int -KEY_SAVE: int -KEY_SBEG: int -KEY_SCANCEL: int -KEY_SCOMMAND: int -KEY_SCOPY: int -KEY_SCREATE: int -KEY_SDC: int -KEY_SDL: int -KEY_SELECT: int -KEY_SEND: int -KEY_SEOL: int -KEY_SEXIT: int -KEY_SF: int -KEY_SFIND: int -KEY_SHELP: int -KEY_SHOME: int -KEY_SIC: int -KEY_SLEFT: int -KEY_SMESSAGE: int -KEY_SMOVE: int -KEY_SNEXT: int -KEY_SOPTIONS: int -KEY_SPREVIOUS: int -KEY_SPRINT: int -KEY_SR: int -KEY_SREDO: int -KEY_SREPLACE: int -KEY_SRESET: int -KEY_SRIGHT: int -KEY_SRSUME: int -KEY_SSAVE: int -KEY_SSUSPEND: int -KEY_STAB: int -KEY_SUNDO: int -KEY_SUSPEND: int -KEY_UNDO: int -KEY_UP: int -OK: int -REPORT_MOUSE_POSITION: int -_C_API: Any -version: bytes - -def baudrate() -> int: ... -def beep() -> None: ... -def can_change_color() -> bool: ... -def cbreak(__flag: bool = ...) -> None: ... -def color_content(__color_number: int) -> tuple[int, int, int]: ... - -# Changed in Python 3.8.8 and 3.9.2 -if sys.version_info >= (3, 8): - def color_pair(pair_number: int) -> int: ... - -else: - def color_pair(__color_number: int) -> int: ... - -def curs_set(__visibility: int) -> int: ... -def def_prog_mode() -> None: ... -def def_shell_mode() -> None: ... -def delay_output(__ms: int) -> None: ... -def doupdate() -> None: ... -def echo(__flag: bool = ...) -> None: ... -def endwin() -> None: ... -def erasechar() -> bytes: ... -def filter() -> None: ... -def flash() -> None: ... -def flushinp() -> None: ... -def getmouse() -> tuple[int, int, int, int, int]: ... -def getsyx() -> tuple[int, int]: ... -def getwin(__file: BinaryIO) -> _CursesWindow: ... -def halfdelay(__tenths: int) -> None: ... -def has_colors() -> bool: ... - -if sys.version_info >= (3, 10): - def has_extended_color_support() -> bool: ... - -def has_ic() -> bool: ... -def has_il() -> bool: ... -def has_key(__key: int) -> bool: ... -def init_color(__color_number: int, __r: int, __g: int, __b: int) -> None: ... -def init_pair(__pair_number: int, __fg: int, __bg: int) -> None: ... -def initscr() -> _CursesWindow: ... -def intrflush(__flag: bool) -> None: ... -def is_term_resized(__nlines: int, __ncols: int) -> bool: ... -def isendwin() -> bool: ... -def keyname(__key: int) -> bytes: ... -def killchar() -> bytes: ... -def longname() -> bytes: ... -def meta(__yes: bool) -> None: ... -def mouseinterval(__interval: int) -> None: ... -def mousemask(__newmask: int) -> tuple[int, int]: ... -def napms(__ms: int) -> int: ... -def newpad(__nlines: int, __ncols: int) -> _CursesWindow: ... -def newwin(__nlines: int, __ncols: int, __begin_y: int = ..., __begin_x: int = ...) -> _CursesWindow: ... -def nl(__flag: bool = ...) -> None: ... -def nocbreak() -> None: ... -def noecho() -> None: ... -def nonl() -> None: ... -def noqiflush() -> None: ... -def noraw() -> None: ... -def pair_content(__pair_number: int) -> tuple[int, int]: ... -def pair_number(__attr: int) -> int: ... -def putp(__string: bytes) -> None: ... -def qiflush(__flag: bool = ...) -> None: ... -def raw(__flag: bool = ...) -> None: ... -def reset_prog_mode() -> None: ... -def reset_shell_mode() -> None: ... -def resetty() -> None: ... -def resize_term(__nlines: int, __ncols: int) -> None: ... -def resizeterm(__nlines: int, __ncols: int) -> None: ... -def savetty() -> None: ... -def setsyx(__y: int, __x: int) -> None: ... -def setupterm(term: str | None = ..., fd: int = ...) -> None: ... -def start_color() -> None: ... -def termattrs() -> int: ... -def termname() -> bytes: ... -def tigetflag(__capname: str) -> int: ... -def tigetnum(__capname: str) -> int: ... -def tigetstr(__capname: str) -> bytes: ... -def tparm( - __str: bytes, - __i1: int = ..., - __i2: int = ..., - __i3: int = ..., - __i4: int = ..., - __i5: int = ..., - __i6: int = ..., - __i7: int = ..., - __i8: int = ..., - __i9: int = ..., -) -> bytes: ... -def typeahead(__fd: int) -> None: ... -def unctrl(__ch: _chtype) -> bytes: ... -def unget_wch(__ch: int | str) -> None: ... -def ungetch(__ch: _chtype) -> None: ... -def ungetmouse(__id: int, __x: int, __y: int, __z: int, __bstate: int) -> None: ... -def update_lines_cols() -> int: ... -def use_default_colors() -> None: ... -def use_env(__flag: bool) -> None: ... - -class error(Exception): ... - -class _CursesWindow: - encoding: str - @overload - def addch(self, ch: _chtype, attr: int = ...) -> None: ... - @overload - def addch(self, y: int, x: int, ch: _chtype, attr: int = ...) -> None: ... - @overload - def addnstr(self, str: str, n: int, attr: int = ...) -> None: ... - @overload - def addnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... - @overload - def addstr(self, str: str, attr: int = ...) -> None: ... - @overload - def addstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... - def attroff(self, __attr: int) -> None: ... - def attron(self, __attr: int) -> None: ... - def attrset(self, __attr: int) -> None: ... - def bkgd(self, __ch: _chtype, __attr: int = ...) -> None: ... - def bkgdset(self, __ch: _chtype, __attr: int = ...) -> None: ... - def border( - self, - ls: _chtype = ..., - rs: _chtype = ..., - ts: _chtype = ..., - bs: _chtype = ..., - tl: _chtype = ..., - tr: _chtype = ..., - bl: _chtype = ..., - br: _chtype = ..., - ) -> None: ... - @overload - def box(self) -> None: ... - @overload - def box(self, vertch: _chtype = ..., horch: _chtype = ...) -> None: ... - @overload - def chgat(self, attr: int) -> None: ... - @overload - def chgat(self, num: int, attr: int) -> None: ... - @overload - def chgat(self, y: int, x: int, attr: int) -> None: ... - @overload - def chgat(self, y: int, x: int, num: int, attr: int) -> None: ... - def clear(self) -> None: ... - def clearok(self, yes: int) -> None: ... - def clrtobot(self) -> None: ... - def clrtoeol(self) -> None: ... - def cursyncup(self) -> None: ... - @overload - def delch(self) -> None: ... - @overload - def delch(self, y: int, x: int) -> None: ... - def deleteln(self) -> None: ... - @overload - def derwin(self, begin_y: int, begin_x: int) -> _CursesWindow: ... - @overload - def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... - def echochar(self, __ch: _chtype, __attr: int = ...) -> None: ... - def enclose(self, __y: int, __x: int) -> bool: ... - def erase(self) -> None: ... - def getbegyx(self) -> tuple[int, int]: ... - def getbkgd(self) -> tuple[int, int]: ... - @overload - def getch(self) -> int: ... - @overload - def getch(self, y: int, x: int) -> int: ... - @overload - def get_wch(self) -> int | str: ... - @overload - def get_wch(self, y: int, x: int) -> int | str: ... - @overload - def getkey(self) -> str: ... - @overload - def getkey(self, y: int, x: int) -> str: ... - def getmaxyx(self) -> tuple[int, int]: ... - def getparyx(self) -> tuple[int, int]: ... - @overload - def getstr(self) -> _chtype: ... - @overload - def getstr(self, n: int) -> _chtype: ... - @overload - def getstr(self, y: int, x: int) -> _chtype: ... - @overload - def getstr(self, y: int, x: int, n: int) -> _chtype: ... - def getyx(self) -> tuple[int, int]: ... - @overload - def hline(self, ch: _chtype, n: int) -> None: ... - @overload - def hline(self, y: int, x: int, ch: _chtype, n: int) -> None: ... - def idcok(self, flag: bool) -> None: ... - def idlok(self, yes: bool) -> None: ... - def immedok(self, flag: bool) -> None: ... - @overload - def inch(self) -> _chtype: ... - @overload - def inch(self, y: int, x: int) -> _chtype: ... - @overload - def insch(self, ch: _chtype, attr: int = ...) -> None: ... - @overload - def insch(self, y: int, x: int, ch: _chtype, attr: int = ...) -> None: ... - def insdelln(self, nlines: int) -> None: ... - def insertln(self) -> None: ... - @overload - def insnstr(self, str: str, n: int, attr: int = ...) -> None: ... - @overload - def insnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... - @overload - def insstr(self, str: str, attr: int = ...) -> None: ... - @overload - def insstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... - @overload - def instr(self, n: int = ...) -> _chtype: ... - @overload - def instr(self, y: int, x: int, n: int = ...) -> _chtype: ... - def is_linetouched(self, __line: int) -> bool: ... - def is_wintouched(self) -> bool: ... - def keypad(self, yes: bool) -> None: ... - def leaveok(self, yes: bool) -> None: ... - def move(self, new_y: int, new_x: int) -> None: ... - def mvderwin(self, y: int, x: int) -> None: ... - def mvwin(self, new_y: int, new_x: int) -> None: ... - def nodelay(self, yes: bool) -> None: ... - def notimeout(self, yes: bool) -> None: ... - @overload - def noutrefresh(self) -> None: ... - @overload - def noutrefresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... - @overload - def overlay(self, destwin: _CursesWindow) -> None: ... - @overload - def overlay( - self, destwin: _CursesWindow, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int - ) -> None: ... - @overload - def overwrite(self, destwin: _CursesWindow) -> None: ... - @overload - def overwrite( - self, destwin: _CursesWindow, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int - ) -> None: ... - def putwin(self, __file: IO[Any]) -> None: ... - def redrawln(self, __beg: int, __num: int) -> None: ... - def redrawwin(self) -> None: ... - @overload - def refresh(self) -> None: ... - @overload - def refresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... - def resize(self, nlines: int, ncols: int) -> None: ... - def scroll(self, lines: int = ...) -> None: ... - def scrollok(self, flag: bool) -> None: ... - def setscrreg(self, __top: int, __bottom: int) -> None: ... - def standend(self) -> None: ... - def standout(self) -> None: ... - @overload - def subpad(self, begin_y: int, begin_x: int) -> _CursesWindow: ... - @overload - def subpad(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... - @overload - def subwin(self, begin_y: int, begin_x: int) -> _CursesWindow: ... - @overload - def subwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... - def syncdown(self) -> None: ... - def syncok(self, flag: bool) -> None: ... - def syncup(self) -> None: ... - def timeout(self, delay: int) -> None: ... - def touchline(self, start: int, count: int, changed: bool = ...) -> None: ... - def touchwin(self) -> None: ... - def untouchwin(self) -> None: ... - @overload - def vline(self, ch: _chtype, n: int) -> None: ... - @overload - def vline(self, y: int, x: int, ch: _chtype, n: int) -> None: ... - -if sys.version_info >= (3, 8): - class _ncurses_version(NamedTuple): - major: int - minor: int - patch: int - ncurses_version: _ncurses_version - window = _CursesWindow # undocumented + # ACS codes are only initialized after initscr is called + ACS_BBSS: int + ACS_BLOCK: int + ACS_BOARD: int + ACS_BSBS: int + ACS_BSSB: int + ACS_BSSS: int + ACS_BTEE: int + ACS_BULLET: int + ACS_CKBOARD: int + ACS_DARROW: int + ACS_DEGREE: int + ACS_DIAMOND: int + ACS_GEQUAL: int + ACS_HLINE: int + ACS_LANTERN: int + ACS_LARROW: int + ACS_LEQUAL: int + ACS_LLCORNER: int + ACS_LRCORNER: int + ACS_LTEE: int + ACS_NEQUAL: int + ACS_PI: int + ACS_PLMINUS: int + ACS_PLUS: int + ACS_RARROW: int + ACS_RTEE: int + ACS_S1: int + ACS_S3: int + ACS_S7: int + ACS_S9: int + ACS_SBBS: int + ACS_SBSB: int + ACS_SBSS: int + ACS_SSBB: int + ACS_SSBS: int + ACS_SSSB: int + ACS_SSSS: int + ACS_STERLING: int + ACS_TTEE: int + ACS_UARROW: int + ACS_ULCORNER: int + ACS_URCORNER: int + ACS_VLINE: int + ALL_MOUSE_EVENTS: int + A_ALTCHARSET: int + A_ATTRIBUTES: int + A_BLINK: int + A_BOLD: int + A_CHARTEXT: int + A_COLOR: int + A_DIM: int + A_HORIZONTAL: int + A_INVIS: int + if sys.version_info >= (3, 7): + A_ITALIC: int + A_LEFT: int + A_LOW: int + A_NORMAL: int + A_PROTECT: int + A_REVERSE: int + A_RIGHT: int + A_STANDOUT: int + A_TOP: int + A_UNDERLINE: int + A_VERTICAL: int + BUTTON1_CLICKED: int + BUTTON1_DOUBLE_CLICKED: int + BUTTON1_PRESSED: int + BUTTON1_RELEASED: int + BUTTON1_TRIPLE_CLICKED: int + BUTTON2_CLICKED: int + BUTTON2_DOUBLE_CLICKED: int + BUTTON2_PRESSED: int + BUTTON2_RELEASED: int + BUTTON2_TRIPLE_CLICKED: int + BUTTON3_CLICKED: int + BUTTON3_DOUBLE_CLICKED: int + BUTTON3_PRESSED: int + BUTTON3_RELEASED: int + BUTTON3_TRIPLE_CLICKED: int + BUTTON4_CLICKED: int + BUTTON4_DOUBLE_CLICKED: int + BUTTON4_PRESSED: int + BUTTON4_RELEASED: int + BUTTON4_TRIPLE_CLICKED: int + # Darwin ncurses doesn't provide BUTTON5_* constants + if sys.version_info >= (3, 10) and sys.platform != "darwin": + BUTTON5_PRESSED: int + BUTTON5_RELEASED: int + BUTTON5_CLICKED: int + BUTTON5_DOUBLE_CLICKED: int + BUTTON5_TRIPLE_CLICKED: int + BUTTON_ALT: int + BUTTON_CTRL: int + BUTTON_SHIFT: int + COLOR_BLACK: int + COLOR_BLUE: int + COLOR_CYAN: int + COLOR_GREEN: int + COLOR_MAGENTA: int + COLOR_RED: int + COLOR_WHITE: int + COLOR_YELLOW: int + ERR: int + KEY_A1: int + KEY_A3: int + KEY_B2: int + KEY_BACKSPACE: int + KEY_BEG: int + KEY_BREAK: int + KEY_BTAB: int + KEY_C1: int + KEY_C3: int + KEY_CANCEL: int + KEY_CATAB: int + KEY_CLEAR: int + KEY_CLOSE: int + KEY_COMMAND: int + KEY_COPY: int + KEY_CREATE: int + KEY_CTAB: int + KEY_DC: int + KEY_DL: int + KEY_DOWN: int + KEY_EIC: int + KEY_END: int + KEY_ENTER: int + KEY_EOL: int + KEY_EOS: int + KEY_EXIT: int + KEY_F0: int + KEY_F1: int + KEY_F10: int + KEY_F11: int + KEY_F12: int + KEY_F13: int + KEY_F14: int + KEY_F15: int + KEY_F16: int + KEY_F17: int + KEY_F18: int + KEY_F19: int + KEY_F2: int + KEY_F20: int + KEY_F21: int + KEY_F22: int + KEY_F23: int + KEY_F24: int + KEY_F25: int + KEY_F26: int + KEY_F27: int + KEY_F28: int + KEY_F29: int + KEY_F3: int + KEY_F30: int + KEY_F31: int + KEY_F32: int + KEY_F33: int + KEY_F34: int + KEY_F35: int + KEY_F36: int + KEY_F37: int + KEY_F38: int + KEY_F39: int + KEY_F4: int + KEY_F40: int + KEY_F41: int + KEY_F42: int + KEY_F43: int + KEY_F44: int + KEY_F45: int + KEY_F46: int + KEY_F47: int + KEY_F48: int + KEY_F49: int + KEY_F5: int + KEY_F50: int + KEY_F51: int + KEY_F52: int + KEY_F53: int + KEY_F54: int + KEY_F55: int + KEY_F56: int + KEY_F57: int + KEY_F58: int + KEY_F59: int + KEY_F6: int + KEY_F60: int + KEY_F61: int + KEY_F62: int + KEY_F63: int + KEY_F7: int + KEY_F8: int + KEY_F9: int + KEY_FIND: int + KEY_HELP: int + KEY_HOME: int + KEY_IC: int + KEY_IL: int + KEY_LEFT: int + KEY_LL: int + KEY_MARK: int + KEY_MAX: int + KEY_MESSAGE: int + KEY_MIN: int + KEY_MOUSE: int + KEY_MOVE: int + KEY_NEXT: int + KEY_NPAGE: int + KEY_OPEN: int + KEY_OPTIONS: int + KEY_PPAGE: int + KEY_PREVIOUS: int + KEY_PRINT: int + KEY_REDO: int + KEY_REFERENCE: int + KEY_REFRESH: int + KEY_REPLACE: int + KEY_RESET: int + KEY_RESIZE: int + KEY_RESTART: int + KEY_RESUME: int + KEY_RIGHT: int + KEY_SAVE: int + KEY_SBEG: int + KEY_SCANCEL: int + KEY_SCOMMAND: int + KEY_SCOPY: int + KEY_SCREATE: int + KEY_SDC: int + KEY_SDL: int + KEY_SELECT: int + KEY_SEND: int + KEY_SEOL: int + KEY_SEXIT: int + KEY_SF: int + KEY_SFIND: int + KEY_SHELP: int + KEY_SHOME: int + KEY_SIC: int + KEY_SLEFT: int + KEY_SMESSAGE: int + KEY_SMOVE: int + KEY_SNEXT: int + KEY_SOPTIONS: int + KEY_SPREVIOUS: int + KEY_SPRINT: int + KEY_SR: int + KEY_SREDO: int + KEY_SREPLACE: int + KEY_SRESET: int + KEY_SRIGHT: int + KEY_SRSUME: int + KEY_SSAVE: int + KEY_SSUSPEND: int + KEY_STAB: int + KEY_SUNDO: int + KEY_SUSPEND: int + KEY_UNDO: int + KEY_UP: int + OK: int + REPORT_MOUSE_POSITION: int + _C_API: Any + version: bytes + def baudrate() -> int: ... + def beep() -> None: ... + def can_change_color() -> bool: ... + def cbreak(__flag: bool = ...) -> None: ... + def color_content(__color_number: int) -> tuple[int, int, int]: ... + # Changed in Python 3.8.8 and 3.9.2 + if sys.version_info >= (3, 8): + def color_pair(pair_number: int) -> int: ... + else: + def color_pair(__color_number: int) -> int: ... + def curs_set(__visibility: int) -> int: ... + def def_prog_mode() -> None: ... + def def_shell_mode() -> None: ... + def delay_output(__ms: int) -> None: ... + def doupdate() -> None: ... + def echo(__flag: bool = ...) -> None: ... + def endwin() -> None: ... + def erasechar() -> bytes: ... + def filter() -> None: ... + def flash() -> None: ... + def flushinp() -> None: ... + if sys.version_info >= (3, 9): + def get_escdelay() -> int: ... + def get_tabsize() -> int: ... + def getmouse() -> tuple[int, int, int, int, int]: ... + def getsyx() -> tuple[int, int]: ... + def getwin(__file: SupportsRead[bytes]) -> _CursesWindow: ... + def halfdelay(__tenths: int) -> None: ... + def has_colors() -> bool: ... + if sys.version_info >= (3, 10): + def has_extended_color_support() -> bool: ... + def has_ic() -> bool: ... + def has_il() -> bool: ... + def has_key(__key: int) -> bool: ... + def init_color(__color_number: int, __r: int, __g: int, __b: int) -> None: ... + def init_pair(__pair_number: int, __fg: int, __bg: int) -> None: ... + def initscr() -> _CursesWindow: ... + def intrflush(__flag: bool) -> None: ... + def is_term_resized(__nlines: int, __ncols: int) -> bool: ... + def isendwin() -> bool: ... + def keyname(__key: int) -> bytes: ... + def killchar() -> bytes: ... + def longname() -> bytes: ... + def meta(__yes: bool) -> None: ... + def mouseinterval(__interval: int) -> None: ... + def mousemask(__newmask: int) -> tuple[int, int]: ... + def napms(__ms: int) -> int: ... + def newpad(__nlines: int, __ncols: int) -> _CursesWindow: ... + def newwin(__nlines: int, __ncols: int, __begin_y: int = ..., __begin_x: int = ...) -> _CursesWindow: ... + def nl(__flag: bool = ...) -> None: ... + def nocbreak() -> None: ... + def noecho() -> None: ... + def nonl() -> None: ... + def noqiflush() -> None: ... + def noraw() -> None: ... + def pair_content(__pair_number: int) -> tuple[int, int]: ... + def pair_number(__attr: int) -> int: ... + def putp(__string: bytes) -> None: ... + def qiflush(__flag: bool = ...) -> None: ... + def raw(__flag: bool = ...) -> None: ... + def reset_prog_mode() -> None: ... + def reset_shell_mode() -> None: ... + def resetty() -> None: ... + def resize_term(__nlines: int, __ncols: int) -> None: ... + def resizeterm(__nlines: int, __ncols: int) -> None: ... + def savetty() -> None: ... + if sys.version_info >= (3, 9): + def set_escdelay(__ms: int) -> None: ... + def set_tabsize(__size: int) -> None: ... + def setsyx(__y: int, __x: int) -> None: ... + def setupterm(term: str | None = ..., fd: int = ...) -> None: ... + def start_color() -> None: ... + def termattrs() -> int: ... + def termname() -> bytes: ... + def tigetflag(__capname: str) -> int: ... + def tigetnum(__capname: str) -> int: ... + def tigetstr(__capname: str) -> bytes | None: ... + def tparm( + __str: bytes, + __i1: int = ..., + __i2: int = ..., + __i3: int = ..., + __i4: int = ..., + __i5: int = ..., + __i6: int = ..., + __i7: int = ..., + __i8: int = ..., + __i9: int = ..., + ) -> bytes: ... + def typeahead(__fd: int) -> None: ... + def unctrl(__ch: _chtype) -> bytes: ... + def unget_wch(__ch: int | str) -> None: ... + def ungetch(__ch: _chtype) -> None: ... + def ungetmouse(__id: int, __x: int, __y: int, __z: int, __bstate: int) -> None: ... + def update_lines_cols() -> None: ... + def use_default_colors() -> None: ... + def use_env(__flag: bool) -> None: ... + class error(Exception): ... + class _CursesWindow: + encoding: str + @overload + def addch(self, ch: _chtype, attr: int = ...) -> None: ... + @overload + def addch(self, y: int, x: int, ch: _chtype, attr: int = ...) -> None: ... + @overload + def addnstr(self, str: str, n: int, attr: int = ...) -> None: ... + @overload + def addnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... + @overload + def addstr(self, str: str, attr: int = ...) -> None: ... + @overload + def addstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... + def attroff(self, __attr: int) -> None: ... + def attron(self, __attr: int) -> None: ... + def attrset(self, __attr: int) -> None: ... + def bkgd(self, __ch: _chtype, __attr: int = ...) -> None: ... + def bkgdset(self, __ch: _chtype, __attr: int = ...) -> None: ... + def border( + self, + ls: _chtype = ..., + rs: _chtype = ..., + ts: _chtype = ..., + bs: _chtype = ..., + tl: _chtype = ..., + tr: _chtype = ..., + bl: _chtype = ..., + br: _chtype = ..., + ) -> None: ... + @overload + def box(self) -> None: ... + @overload + def box(self, vertch: _chtype = ..., horch: _chtype = ...) -> None: ... + @overload + def chgat(self, attr: int) -> None: ... + @overload + def chgat(self, num: int, attr: int) -> None: ... + @overload + def chgat(self, y: int, x: int, attr: int) -> None: ... + @overload + def chgat(self, y: int, x: int, num: int, attr: int) -> None: ... + def clear(self) -> None: ... + def clearok(self, yes: int) -> None: ... + def clrtobot(self) -> None: ... + def clrtoeol(self) -> None: ... + def cursyncup(self) -> None: ... + @overload + def delch(self) -> None: ... + @overload + def delch(self, y: int, x: int) -> None: ... + def deleteln(self) -> None: ... + @overload + def derwin(self, begin_y: int, begin_x: int) -> _CursesWindow: ... + @overload + def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... + def echochar(self, __ch: _chtype, __attr: int = ...) -> None: ... + def enclose(self, __y: int, __x: int) -> bool: ... + def erase(self) -> None: ... + def getbegyx(self) -> tuple[int, int]: ... + def getbkgd(self) -> tuple[int, int]: ... + @overload + def getch(self) -> int: ... + @overload + def getch(self, y: int, x: int) -> int: ... + @overload + def get_wch(self) -> int | str: ... + @overload + def get_wch(self, y: int, x: int) -> int | str: ... + @overload + def getkey(self) -> str: ... + @overload + def getkey(self, y: int, x: int) -> str: ... + def getmaxyx(self) -> tuple[int, int]: ... + def getparyx(self) -> tuple[int, int]: ... + @overload + def getstr(self) -> bytes: ... + @overload + def getstr(self, n: int) -> bytes: ... + @overload + def getstr(self, y: int, x: int) -> bytes: ... + @overload + def getstr(self, y: int, x: int, n: int) -> bytes: ... + def getyx(self) -> tuple[int, int]: ... + @overload + def hline(self, ch: _chtype, n: int) -> None: ... + @overload + def hline(self, y: int, x: int, ch: _chtype, n: int) -> None: ... + def idcok(self, flag: bool) -> None: ... + def idlok(self, yes: bool) -> None: ... + def immedok(self, flag: bool) -> None: ... + @overload + def inch(self) -> int: ... + @overload + def inch(self, y: int, x: int) -> int: ... + @overload + def insch(self, ch: _chtype, attr: int = ...) -> None: ... + @overload + def insch(self, y: int, x: int, ch: _chtype, attr: int = ...) -> None: ... + def insdelln(self, nlines: int) -> None: ... + def insertln(self) -> None: ... + @overload + def insnstr(self, str: str, n: int, attr: int = ...) -> None: ... + @overload + def insnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ... + @overload + def insstr(self, str: str, attr: int = ...) -> None: ... + @overload + def insstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ... + @overload + def instr(self, n: int = ...) -> bytes: ... + @overload + def instr(self, y: int, x: int, n: int = ...) -> bytes: ... + def is_linetouched(self, __line: int) -> bool: ... + def is_wintouched(self) -> bool: ... + def keypad(self, yes: bool) -> None: ... + def leaveok(self, yes: bool) -> None: ... + def move(self, new_y: int, new_x: int) -> None: ... + def mvderwin(self, y: int, x: int) -> None: ... + def mvwin(self, new_y: int, new_x: int) -> None: ... + def nodelay(self, yes: bool) -> None: ... + def notimeout(self, yes: bool) -> None: ... + @overload + def noutrefresh(self) -> None: ... + @overload + def noutrefresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... + @overload + def overlay(self, destwin: _CursesWindow) -> None: ... + @overload + def overlay( + self, destwin: _CursesWindow, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int + ) -> None: ... + @overload + def overwrite(self, destwin: _CursesWindow) -> None: ... + @overload + def overwrite( + self, destwin: _CursesWindow, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int + ) -> None: ... + def putwin(self, __file: IO[Any]) -> None: ... + def redrawln(self, __beg: int, __num: int) -> None: ... + def redrawwin(self) -> None: ... + @overload + def refresh(self) -> None: ... + @overload + def refresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ... + def resize(self, nlines: int, ncols: int) -> None: ... + def scroll(self, lines: int = ...) -> None: ... + def scrollok(self, flag: bool) -> None: ... + def setscrreg(self, __top: int, __bottom: int) -> None: ... + def standend(self) -> None: ... + def standout(self) -> None: ... + @overload + def subpad(self, begin_y: int, begin_x: int) -> _CursesWindow: ... + @overload + def subpad(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... + @overload + def subwin(self, begin_y: int, begin_x: int) -> _CursesWindow: ... + @overload + def subwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> _CursesWindow: ... + def syncdown(self) -> None: ... + def syncok(self, flag: bool) -> None: ... + def syncup(self) -> None: ... + def timeout(self, delay: int) -> None: ... + def touchline(self, start: int, count: int, changed: bool = ...) -> None: ... + def touchwin(self) -> None: ... + def untouchwin(self) -> None: ... + @overload + def vline(self, ch: _chtype, n: int) -> None: ... + @overload + def vline(self, y: int, x: int, ch: _chtype, n: int) -> None: ... + if sys.version_info >= (3, 8): + class _ncurses_version(NamedTuple): + major: int + minor: int + patch: int + ncurses_version: _ncurses_version + window = _CursesWindow # undocumented diff --git a/mypy/typeshed/stdlib/_dummy_thread.pyi b/mypy/typeshed/stdlib/_dummy_thread.pyi index 886d9d739780..6e936726a48f 100644 --- a/mypy/typeshed/stdlib/_dummy_thread.pyi +++ b/mypy/typeshed/stdlib/_dummy_thread.pyi @@ -1,15 +1,15 @@ -from typing import Any, Callable, NoReturn, Tuple +from typing import Any, Callable, NoReturn TIMEOUT_MAX: int error = RuntimeError -def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: dict[str, Any] = ...) -> None: ... +def start_new_thread(function: Callable[..., Any], args: tuple[Any, ...], kwargs: dict[str, Any] = ...) -> None: ... def exit() -> NoReturn: ... def get_ident() -> int: ... def allocate_lock() -> LockType: ... def stack_size(size: int | None = ...) -> int: ... -class LockType(object): +class LockType: locked_status: bool def __init__(self) -> None: ... def acquire(self, waitflag: bool | None = ..., timeout: int = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/_dummy_threading.pyi b/mypy/typeshed/stdlib/_dummy_threading.pyi index 64998d86bf9f..e7a830f4a5dc 100644 --- a/mypy/typeshed/stdlib/_dummy_threading.pyi +++ b/mypy/typeshed/stdlib/_dummy_threading.pyi @@ -1,6 +1,6 @@ import sys from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, Optional, Type, TypeVar +from typing import Any, Callable, Iterable, Mapping, Optional, TypeVar # TODO recursive type _TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] @@ -28,7 +28,7 @@ TIMEOUT_MAX: float class ThreadError(Exception): ... -class local(object): +class local: def __getattribute__(self, name: str) -> Any: ... def __setattr__(self, name: str, value: Any) -> None: ... def __delattr__(self, name: str) -> None: ... @@ -67,7 +67,7 @@ class Lock: def __init__(self) -> None: ... def __enter__(self) -> bool: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... @@ -77,7 +77,7 @@ class _RLock: def __init__(self) -> None: ... def __enter__(self) -> bool: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... @@ -88,7 +88,7 @@ class Condition: def __init__(self, lock: Lock | _RLock | None = ...) -> None: ... def __enter__(self) -> bool: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... @@ -101,7 +101,7 @@ class Condition: class Semaphore: def __init__(self, value: int = ...) -> None: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ..., timeout: float | None = ...) -> bool: ... def __enter__(self, blocking: bool = ..., timeout: float | None = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/_imp.pyi b/mypy/typeshed/stdlib/_imp.pyi index b61c9f29b96d..23272591df4c 100644 --- a/mypy/typeshed/stdlib/_imp.pyi +++ b/mypy/typeshed/stdlib/_imp.pyi @@ -1,7 +1,11 @@ +import sys import types from importlib.machinery import ModuleSpec from typing import Any +if sys.version_info >= (3, 7): + check_hash_based_pycs: str + def create_builtin(__spec: ModuleSpec) -> types.ModuleType: ... def create_dynamic(__spec: ModuleSpec, __file: Any = ...) -> None: ... def acquire_lock() -> None: ... diff --git a/mypy/typeshed/stdlib/_markupbase.pyi b/mypy/typeshed/stdlib/_markupbase.pyi index 368d32bd5b4c..2c497f65bb43 100644 --- a/mypy/typeshed/stdlib/_markupbase.pyi +++ b/mypy/typeshed/stdlib/_markupbase.pyi @@ -1,6 +1,17 @@ +import sys +from typing import Any + class ParserBase: def __init__(self) -> None: ... - def error(self, message: str) -> None: ... def reset(self) -> None: ... def getpos(self) -> tuple[int, int]: ... def unknown_decl(self, data: str) -> None: ... + def parse_comment(self, i: int, report: int = ...) -> int: ... # undocumented + def parse_declaration(self, i: int) -> int: ... # undocumented + def parse_marked_section(self, i: int, report: int = ...) -> int: ... # undocumented + def updatepos(self, i: int, j: int) -> int: ... # undocumented + if sys.version_info < (3, 10): + # Removed from ParserBase: https://bugs.python.org/issue31844 + def error(self, message: str) -> Any: ... # undocumented + lineno: int # undocumented + offset: int # undocumented diff --git a/mypy/typeshed/stdlib/_msi.pyi b/mypy/typeshed/stdlib/_msi.pyi index 754febe68da9..b7e852f38ae9 100644 --- a/mypy/typeshed/stdlib/_msi.pyi +++ b/mypy/typeshed/stdlib/_msi.pyi @@ -10,8 +10,8 @@ if sys.platform == "win32": def Modify(self, mode: int, record: _Record) -> None: ... def Close(self) -> None: ... # Don't exist at runtime - __new__: None # type: ignore - __init__: None # type: ignore + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] # Actual typename Summary, not exposed by the implementation class _Summary: def GetProperty(self, propid: int) -> str | bytes | None: ... @@ -19,8 +19,8 @@ if sys.platform == "win32": def SetProperty(self, propid: int, value: str | bytes) -> None: ... def Persist(self) -> None: ... # Don't exist at runtime - __new__: None # type: ignore - __init__: None # type: ignore + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] # Actual typename Database, not exposed by the implementation class _Database: def OpenView(self, sql: str) -> _View: ... @@ -28,8 +28,8 @@ if sys.platform == "win32": def GetSummaryInformation(self, updateCount: int) -> _Summary: ... def Close(self) -> None: ... # Don't exist at runtime - __new__: None # type: ignore - __init__: None # type: ignore + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] # Actual typename Record, not exposed by the implementation class _Record: def GetFieldCount(self) -> int: ... @@ -40,8 +40,8 @@ if sys.platform == "win32": def SetInteger(self, field: int, int: int) -> None: ... def ClearData(self) -> None: ... # Don't exist at runtime - __new__: None # type: ignore - __init__: None # type: ignore + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] def UuidCreate() -> str: ... def FCICreate(cabname: str, files: list[str]) -> None: ... def OpenDatabase(name: str, flags: int) -> _Database: ... diff --git a/mypy/typeshed/stdlib/_operator.pyi b/mypy/typeshed/stdlib/_operator.pyi index bea438861886..77a88d4fa141 100644 --- a/mypy/typeshed/stdlib/_operator.pyi +++ b/mypy/typeshed/stdlib/_operator.pyi @@ -1,60 +1,141 @@ -# In reality the import is the other way around, but this way we can keep the operator stub in 2and3 -from operator import ( - abs as abs, - add as add, - and_ as and_, - attrgetter as attrgetter, - concat as concat, - contains as contains, - countOf as countOf, - delitem as delitem, - eq as eq, - floordiv as floordiv, - ge as ge, - getitem as getitem, - gt as gt, - iadd as iadd, - iand as iand, - iconcat as iconcat, - ifloordiv as ifloordiv, - ilshift as ilshift, - imatmul as imatmul, - imod as imod, - imul as imul, - index as index, - indexOf as indexOf, - inv as inv, - invert as invert, - ior as ior, - ipow as ipow, - irshift as irshift, - is_ as is_, - is_not as is_not, - isub as isub, - itemgetter as itemgetter, - itruediv as itruediv, - ixor as ixor, - le as le, - length_hint as length_hint, - lshift as lshift, - lt as lt, - matmul as matmul, - methodcaller as methodcaller, - mod as mod, - mul as mul, - ne as ne, - neg as neg, - not_ as not_, - or_ as or_, - pos as pos, - pow as pow, - rshift as rshift, - setitem as setitem, - sub as sub, - truediv as truediv, - truth as truth, - xor as xor, +import sys +from _typeshed import SupportsAnyComparison +from typing import ( + Any, + AnyStr, + Callable, + Container, + Generic, + Iterable, + Mapping, + MutableMapping, + MutableSequence, + Protocol, + Sequence, + SupportsAbs, + TypeVar, + overload, ) -from typing import AnyStr +from typing_extensions import ParamSpec, SupportsIndex, final + +_R = TypeVar("_R") +_T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) +_K = TypeVar("_K") +_V = TypeVar("_V") +_P = ParamSpec("_P") + +class _SupportsInversion(Protocol[_T_co]): + def __invert__(self) -> _T_co: ... + +class _SupportsNeg(Protocol[_T_co]): + def __neg__(self) -> _T_co: ... + +class _SupportsPos(Protocol[_T_co]): + def __pos__(self) -> _T_co: ... + +# All four comparison functions must have the same signature, or we get false-positive errors +def lt(__a: SupportsAnyComparison, __b: SupportsAnyComparison) -> Any: ... +def le(__a: SupportsAnyComparison, __b: SupportsAnyComparison) -> Any: ... +def eq(__a: object, __b: object) -> Any: ... +def ne(__a: object, __b: object) -> Any: ... +def ge(__a: SupportsAnyComparison, __b: SupportsAnyComparison) -> Any: ... +def gt(__a: SupportsAnyComparison, __b: SupportsAnyComparison) -> Any: ... +def not_(__a: object) -> bool: ... +def truth(__a: object) -> bool: ... +def is_(__a: object, __b: object) -> bool: ... +def is_not(__a: object, __b: object) -> bool: ... +def abs(__a: SupportsAbs[_T]) -> _T: ... +def add(__a: Any, __b: Any) -> Any: ... +def and_(__a: Any, __b: Any) -> Any: ... +def floordiv(__a: Any, __b: Any) -> Any: ... +def index(__a: SupportsIndex) -> int: ... +def inv(__a: _SupportsInversion[_T_co]) -> _T_co: ... +def invert(__a: _SupportsInversion[_T_co]) -> _T_co: ... +def lshift(__a: Any, __b: Any) -> Any: ... +def mod(__a: Any, __b: Any) -> Any: ... +def mul(__a: Any, __b: Any) -> Any: ... +def matmul(__a: Any, __b: Any) -> Any: ... +def neg(__a: _SupportsNeg[_T_co]) -> _T_co: ... +def or_(__a: Any, __b: Any) -> Any: ... +def pos(__a: _SupportsPos[_T_co]) -> _T_co: ... +def pow(__a: Any, __b: Any) -> Any: ... +def rshift(__a: Any, __b: Any) -> Any: ... +def sub(__a: Any, __b: Any) -> Any: ... +def truediv(__a: Any, __b: Any) -> Any: ... +def xor(__a: Any, __b: Any) -> Any: ... +def concat(__a: Sequence[_T], __b: Sequence[_T]) -> Sequence[_T]: ... +def contains(__a: Container[object], __b: object) -> bool: ... +def countOf(__a: Iterable[object], __b: object) -> int: ... +@overload +def delitem(__a: MutableSequence[Any], __b: SupportsIndex) -> None: ... +@overload +def delitem(__a: MutableSequence[Any], __b: slice) -> None: ... +@overload +def delitem(__a: MutableMapping[_K, Any], __b: _K) -> None: ... +@overload +def getitem(__a: Sequence[_T], __b: SupportsIndex) -> _T: ... +@overload +def getitem(__a: Sequence[_T], __b: slice) -> Sequence[_T]: ... +@overload +def getitem(__a: Mapping[_K, _V], __b: _K) -> _V: ... +def indexOf(__a: Iterable[_T], __b: _T) -> int: ... +@overload +def setitem(__a: MutableSequence[_T], __b: SupportsIndex, __c: _T) -> None: ... +@overload +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: object, __default: int = ...) -> int: ... +@final +class attrgetter(Generic[_T_co]): + @overload + def __new__(cls, attr: str) -> attrgetter[Any]: ... + @overload + def __new__(cls, attr: str, __attr2: str) -> attrgetter[tuple[Any, Any]]: ... + @overload + def __new__(cls, attr: str, __attr2: str, __attr3: str) -> attrgetter[tuple[Any, Any, Any]]: ... + @overload + def __new__(cls, attr: str, __attr2: str, __attr3: str, __attr4: str) -> attrgetter[tuple[Any, Any, Any, Any]]: ... + @overload + 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]: ... + @overload + def __new__(cls, item: Any, __item2: Any) -> itemgetter[tuple[Any, Any]]: ... + @overload + def __new__(cls, item: Any, __item2: Any, __item3: Any) -> itemgetter[tuple[Any, Any, Any]]: ... + @overload + def __new__(cls, item: Any, __item2: Any, __item3: Any, __item4: Any) -> itemgetter[tuple[Any, Any, Any, Any]]: ... + @overload + 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: ... + +def iadd(__a: Any, __b: Any) -> Any: ... +def iand(__a: Any, __b: Any) -> Any: ... +def iconcat(__a: Any, __b: Any) -> Any: ... +def ifloordiv(__a: Any, __b: Any) -> Any: ... +def ilshift(__a: Any, __b: Any) -> Any: ... +def imod(__a: Any, __b: Any) -> Any: ... +def imul(__a: Any, __b: Any) -> Any: ... +def imatmul(__a: Any, __b: Any) -> Any: ... +def ior(__a: Any, __b: Any) -> Any: ... +def ipow(__a: Any, __b: Any) -> Any: ... +def irshift(__a: Any, __b: Any) -> Any: ... +def isub(__a: Any, __b: Any) -> Any: ... +def itruediv(__a: Any, __b: Any) -> Any: ... +def ixor(__a: Any, __b: Any) -> Any: ... + +if sys.version_info >= (3, 11): + def call(__obj: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... def _compare_digest(__a: AnyStr, __b: AnyStr) -> bool: ... diff --git a/mypy/typeshed/stdlib/_osx_support.pyi b/mypy/typeshed/stdlib/_osx_support.pyi index ce1fffc00e8c..ffb25d5a2c0e 100644 --- a/mypy/typeshed/stdlib/_osx_support.pyi +++ b/mypy/typeshed/stdlib/_osx_support.pyi @@ -1,4 +1,5 @@ -from typing import Iterable, Sequence, Tuple, TypeVar +import sys +from typing import Iterable, Sequence, TypeVar _T = TypeVar("_T") _K = TypeVar("_K") @@ -6,12 +7,18 @@ _V = TypeVar("_V") __all__: list[str] -_UNIVERSAL_CONFIG_VARS: Tuple[str, ...] # undocumented -_COMPILER_CONFIG_VARS: Tuple[str, ...] # undocumented +_UNIVERSAL_CONFIG_VARS: tuple[str, ...] # undocumented +_COMPILER_CONFIG_VARS: tuple[str, ...] # undocumented _INITPRE: str # undocumented def _find_executable(executable: str, path: str | None = ...) -> str | None: ... # undocumented -def _read_output(commandstring: str) -> str | None: ... # undocumented + +if sys.version_info >= (3, 8): + def _read_output(commandstring: str, capture_stderr: bool = ...) -> str | None: ... # undocumented + +else: + def _read_output(commandstring: str) -> str | None: ... # undocumented + def _find_build_tool(toolname: str) -> str: ... # undocumented _SYSTEM_VERSION: str | None # undocumented diff --git a/mypy/typeshed/stdlib/_posixsubprocess.pyi b/mypy/typeshed/stdlib/_posixsubprocess.pyi index 0eae723e7a67..5481100cacfc 100644 --- a/mypy/typeshed/stdlib/_posixsubprocess.pyi +++ b/mypy/typeshed/stdlib/_posixsubprocess.pyi @@ -1,24 +1,24 @@ -# NOTE: These are incomplete! - +import sys from typing import Callable, Sequence -def cloexec_pipe() -> tuple[int, int]: ... -def fork_exec( - args: Sequence[str], - executable_list: Sequence[bytes], - close_fds: bool, - fds_to_keep: Sequence[int], - cwd: str, - env_list: Sequence[bytes], - p2cread: int, - p2cwrite: int, - c2pred: int, - c2pwrite: int, - errread: int, - errwrite: int, - errpipe_read: int, - errpipe_write: int, - restore_signals: int, - start_new_session: int, - preexec_fn: Callable[[], None], -) -> int: ... +if sys.platform != "win32": + def cloexec_pipe() -> tuple[int, int]: ... + def fork_exec( + args: Sequence[str], + executable_list: Sequence[bytes], + close_fds: bool, + fds_to_keep: Sequence[int], + cwd: str, + env_list: Sequence[bytes], + p2cread: int, + p2cwrite: int, + c2pred: int, + c2pwrite: int, + errread: int, + errwrite: int, + errpipe_read: int, + errpipe_write: int, + restore_signals: int, + start_new_session: int, + preexec_fn: Callable[[], None], + ) -> int: ... diff --git a/mypy/typeshed/stdlib/_py_abc.pyi b/mypy/typeshed/stdlib/_py_abc.pyi index 8d7938918271..c7794079d1bd 100644 --- a/mypy/typeshed/stdlib/_py_abc.pyi +++ b/mypy/typeshed/stdlib/_py_abc.pyi @@ -1,10 +1,11 @@ -from typing import Any, Tuple, Type, TypeVar +from typing import Any, NewType, TypeVar _T = TypeVar("_T") -# TODO: Change the return into a NewType bound to int after pytype/#597 -def get_cache_token() -> object: ... +_CacheToken = NewType("_CacheToken", int) + +def get_cache_token() -> _CacheToken: ... class ABCMeta(type): - def __new__(__mcls, __name: str, __bases: Tuple[Type[Any], ...], __namespace: dict[str, Any]) -> ABCMeta: ... - def register(cls, subclass: Type[_T]) -> Type[_T]: ... + def __new__(__mcls, __name: str, __bases: tuple[type[Any], ...], __namespace: dict[str, Any]) -> ABCMeta: ... + def register(cls, subclass: type[_T]) -> type[_T]: ... diff --git a/mypy/typeshed/stdlib/_random.pyi b/mypy/typeshed/stdlib/_random.pyi index fa80c6d98144..9aff4b3cb026 100644 --- a/mypy/typeshed/stdlib/_random.pyi +++ b/mypy/typeshed/stdlib/_random.pyi @@ -1,9 +1,7 @@ -from typing import Tuple - # Actually Tuple[(int,) * 625] -_State = Tuple[int, ...] +_State = tuple[int, ...] -class Random(object): +class Random: def __init__(self, seed: object = ...) -> None: ... def seed(self, __n: object = ...) -> None: ... def getstate(self) -> _State: ... diff --git a/mypy/typeshed/stdlib/_socket.pyi b/mypy/typeshed/stdlib/_socket.pyi index 846f64d5a433..e0a3f85078e6 100644 --- a/mypy/typeshed/stdlib/_socket.pyi +++ b/mypy/typeshed/stdlib/_socket.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import ReadableBuffer, WriteableBuffer from collections.abc import Iterable -from typing import Any, SupportsInt, Tuple, Union, overload +from typing import Any, SupportsInt, Union, overload if sys.version_info >= (3, 8): from typing import SupportsIndex @@ -10,12 +10,12 @@ if sys.version_info >= (3, 8): else: _FD = SupportsInt -_CMSG = Tuple[int, int, bytes] -_CMSGArg = Tuple[int, int, ReadableBuffer] +_CMSG = tuple[int, int, bytes] +_CMSGArg = tuple[int, int, ReadableBuffer] # Addresses can be either tuples of varying lengths (AF_INET, AF_INET6, # AF_NETLINK, AF_TIPC) or strings (AF_UNIX). -_Address = Union[Tuple[Any, ...], str] +_Address = Union[tuple[Any, ...], str] _RetAddress = Any # TODO Most methods allow bytes as address objects @@ -356,6 +356,9 @@ if sys.platform == "linux" and sys.version_info >= (3, 9): J1939_FILTER_MAX: int +if sys.platform == "linux" and sys.version_info >= (3, 10): + IPPROTO_MPTCP: int + if sys.platform == "linux": AF_PACKET: int PF_PACKET: int @@ -527,6 +530,8 @@ class socket: family: int type: int proto: int + @property + def timeout(self) -> float | None: ... def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: _FD | None = ...) -> None: ... def bind(self, __address: _Address | bytes) -> None: ... def close(self) -> None: ... diff --git a/mypy/typeshed/stdlib/_stat.pyi b/mypy/typeshed/stdlib/_stat.pyi index 634f7da02563..83d832e4dd8e 100644 --- a/mypy/typeshed/stdlib/_stat.pyi +++ b/mypy/typeshed/stdlib/_stat.pyi @@ -1,54 +1,68 @@ -SF_APPEND: int -SF_ARCHIVED: int -SF_IMMUTABLE: int -SF_NOUNLINK: int -SF_SNAPSHOT: int -ST_ATIME: int -ST_CTIME: int -ST_DEV: int -ST_GID: int -ST_INO: int -ST_MODE: int -ST_MTIME: int -ST_NLINK: int -ST_SIZE: int -ST_UID: int -S_ENFMT: int -S_IEXEC: int -S_IFBLK: int -S_IFCHR: int -S_IFDIR: int +import sys +from typing_extensions import Literal + +SF_APPEND: Literal[0x00040000] +SF_ARCHIVED: Literal[0x00010000] +SF_IMMUTABLE: Literal[0x00020000] +SF_NOUNLINK: Literal[0x00100000] +SF_SNAPSHOT: Literal[0x00200000] + +ST_MODE: Literal[0] +ST_INO: Literal[1] +ST_DEV: Literal[2] +ST_NLINK: Literal[3] +ST_UID: Literal[4] +ST_GID: Literal[5] +ST_SIZE: Literal[6] +ST_ATIME: Literal[7] +ST_MTIME: Literal[8] +ST_CTIME: Literal[9] + +S_IFIFO: Literal[0o010000] +S_IFLNK: Literal[0o120000] +S_IFREG: Literal[0o100000] +S_IFSOCK: Literal[0o140000] +S_IFBLK: Literal[0o060000] +S_IFCHR: Literal[0o020000] +S_IFDIR: Literal[0o040000] + +# These are 0 on systems that don't support the specific kind of file. +# Example: Linux doesn't support door files, so S_IFDOOR is 0 on linux. S_IFDOOR: int -S_IFIFO: int -S_IFLNK: int S_IFPORT: int -S_IFREG: int -S_IFSOCK: int S_IFWHT: int -S_IREAD: int -S_IRGRP: int -S_IROTH: int -S_IRUSR: int -S_IRWXG: int -S_IRWXO: int -S_IRWXU: int -S_ISGID: int -S_ISUID: int -S_ISVTX: int -S_IWGRP: int -S_IWOTH: int -S_IWRITE: int -S_IWUSR: int -S_IXGRP: int -S_IXOTH: int -S_IXUSR: int -UF_APPEND: int -UF_COMPRESSED: int -UF_HIDDEN: int -UF_IMMUTABLE: int -UF_NODUMP: int -UF_NOUNLINK: int -UF_OPAQUE: int + +S_ISUID: Literal[0o4000] +S_ISGID: Literal[0o2000] +S_ISVTX: Literal[0o1000] + +S_IRWXU: Literal[0o0700] +S_IRUSR: Literal[0o0400] +S_IWUSR: Literal[0o0200] +S_IXUSR: Literal[0o0100] + +S_IRWXG: Literal[0o0070] +S_IRGRP: Literal[0o0040] +S_IWGRP: Literal[0o0020] +S_IXGRP: Literal[0o0010] + +S_IRWXO: Literal[0o0007] +S_IROTH: Literal[0o0004] +S_IWOTH: Literal[0o0002] +S_IXOTH: Literal[0o0001] + +S_ENFMT: Literal[0o2000] +S_IREAD: Literal[0o0400] +S_IWRITE: Literal[0o0200] +S_IEXEC: Literal[0o0100] + +UF_APPEND: Literal[0x00000004] +UF_COMPRESSED: Literal[0x00000020] # OS X 10.6+ only +UF_HIDDEN: Literal[0x00008000] # OX X 10.5+ only +UF_IMMUTABLE: Literal[0x00000002] +UF_NODUMP: Literal[0x00000001] +UF_NOUNLINK: Literal[0x00000010] +UF_OPAQUE: Literal[0x00000008] def S_IMODE(mode: int) -> int: ... def S_IFMT(mode: int) -> int: ... @@ -63,3 +77,27 @@ def S_ISREG(mode: int) -> bool: ... def S_ISSOCK(mode: int) -> bool: ... def S_ISWHT(mode: int) -> bool: ... def filemode(mode: int) -> str: ... + +if sys.platform == "win32" and sys.version_info >= (3, 8): + IO_REPARSE_TAG_SYMLINK: int + IO_REPARSE_TAG_MOUNT_POINT: int + IO_REPARSE_TAG_APPEXECLINK: int + +if sys.platform == "win32": + FILE_ATTRIBUTE_ARCHIVE: Literal[32] + FILE_ATTRIBUTE_COMPRESSED: Literal[2048] + FILE_ATTRIBUTE_DEVICE: Literal[64] + FILE_ATTRIBUTE_DIRECTORY: Literal[16] + FILE_ATTRIBUTE_ENCRYPTED: Literal[16384] + FILE_ATTRIBUTE_HIDDEN: Literal[2] + FILE_ATTRIBUTE_INTEGRITY_STREAM: Literal[32768] + FILE_ATTRIBUTE_NORMAL: Literal[128] + FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: Literal[8192] + FILE_ATTRIBUTE_NO_SCRUB_DATA: Literal[131072] + FILE_ATTRIBUTE_OFFLINE: Literal[4096] + FILE_ATTRIBUTE_READONLY: Literal[1] + FILE_ATTRIBUTE_REPARSE_POINT: Literal[1024] + FILE_ATTRIBUTE_SPARSE_FILE: Literal[512] + FILE_ATTRIBUTE_SYSTEM: Literal[4] + FILE_ATTRIBUTE_TEMPORARY: Literal[256] + FILE_ATTRIBUTE_VIRTUAL: Literal[65536] diff --git a/mypy/typeshed/stdlib/_thread.pyi b/mypy/typeshed/stdlib/_thread.pyi index 2f4252981b68..744799f1f66f 100644 --- a/mypy/typeshed/stdlib/_thread.pyi +++ b/mypy/typeshed/stdlib/_thread.pyi @@ -1,7 +1,8 @@ import sys +from _typeshed import structseq from threading import Thread from types import TracebackType -from typing import Any, Callable, NoReturn, Optional, Tuple, Type +from typing import Any, Callable, NoReturn, Optional from typing_extensions import final error = RuntimeError @@ -17,10 +18,10 @@ class LockType: def locked(self) -> bool: ... def __enter__(self) -> bool: ... def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... -def start_new_thread(function: Callable[..., Any], args: Tuple[Any, ...], kwargs: dict[str, Any] = ...) -> int: ... +def start_new_thread(function: Callable[..., Any], args: tuple[Any, ...], kwargs: dict[str, Any] = ...) -> int: ... def interrupt_main() -> None: ... def exit() -> NoReturn: ... def allocate_lock() -> LockType: ... @@ -32,9 +33,11 @@ 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]]): + class _ExceptHookArgs( + structseq[Any], tuple[type[BaseException], Optional[BaseException], Optional[TracebackType], Optional[Thread]] + ): @property - def exc_type(self) -> Type[BaseException]: ... + def exc_type(self) -> type[BaseException]: ... @property def exc_value(self) -> BaseException | None: ... @property diff --git a/mypy/typeshed/stdlib/_threading_local.pyi b/mypy/typeshed/stdlib/_threading_local.pyi index bab69a7c2e7d..9e1e3f48d286 100644 --- a/mypy/typeshed/stdlib/_threading_local.pyi +++ b/mypy/typeshed/stdlib/_threading_local.pyi @@ -1,7 +1,7 @@ -from typing import Any, Dict +from typing import Any from weakref import ReferenceType -localdict = Dict[Any, Any] +localdict = dict[Any, Any] class _localimpl: key: str diff --git a/mypy/typeshed/stdlib/_tkinter.pyi b/mypy/typeshed/stdlib/_tkinter.pyi index e97edf5b4fae..db1bfa866998 100644 --- a/mypy/typeshed/stdlib/_tkinter.pyi +++ b/mypy/typeshed/stdlib/_tkinter.pyi @@ -1,3 +1,4 @@ +import sys from typing import Any from typing_extensions import Literal, final @@ -16,8 +17,15 @@ from typing_extensions import Literal, final # (, ) @final class Tcl_Obj: - string: str # str(tclobj) returns this + string: str | bytes typename: str + __hash__: None # type: ignore[assignment] + def __eq__(self, other): ... + def __ge__(self, other): ... + def __gt__(self, other): ... + def __le__(self, other): ... + def __lt__(self, other): ... + def __ne__(self, other): ... class TclError(Exception): ... @@ -41,38 +49,40 @@ class TclError(Exception): ... @final class TkappType: # Please keep in sync with tkinter.Tk + def adderrorinfo(self, __msg): ... def call(self, __command: Any, *args: Any) -> Any: ... + def createcommand(self, __name, __func): ... + if sys.platform != "win32": + def createfilehandler(self, __file, __mask, __func): ... + def deletefilehandler(self, __file): ... + def createtimerhandler(self, __milliseconds, __func): ... + def deletecommand(self, __name): ... + def dooneevent(self, __flags: int = ...): ... def eval(self, __script: str) -> str: ... - adderrorinfo: Any - createcommand: Any - createfilehandler: Any - createtimerhandler: Any - deletecommand: Any - deletefilehandler: Any - dooneevent: Any - evalfile: Any - exprboolean: Any - exprdouble: Any - exprlong: Any - exprstring: Any - getboolean: Any - getdouble: Any - getint: Any - getvar: Any - globalgetvar: Any - globalsetvar: Any - globalunsetvar: Any - interpaddr: Any - loadtk: Any - mainloop: Any - quit: Any - record: Any - setvar: Any - split: Any - splitlist: Any - unsetvar: Any - wantobjects: Any - willdispatch: Any + def evalfile(self, __fileName): ... + def exprboolean(self, __s): ... + def exprdouble(self, __s): ... + def exprlong(self, __s): ... + def exprstring(self, __s): ... + def getboolean(self, __arg): ... + def getdouble(self, __arg): ... + def getint(self, __arg): ... + def getvar(self, *args, **kwargs): ... + def globalgetvar(self, *args, **kwargs): ... + def globalsetvar(self, *args, **kwargs): ... + def globalunsetvar(self, *args, **kwargs): ... + def interpaddr(self): ... + def loadtk(self) -> None: ... + def mainloop(self, __threshold: int = ...): ... + def quit(self): ... + def record(self, __script): ... + def setvar(self, *ags, **kwargs): ... + if sys.version_info < (3, 11): + def split(self, __arg): ... + def splitlist(self, __arg): ... + def unsetvar(self, *args, **kwargs): ... + def wantobjects(self, *args, **kwargs): ... + def willdispatch(self): ... # These should be kept in sync with tkinter.tix constants, except ALL_EVENTS which doesn't match TCL_ALL_EVENTS ALL_EVENTS: Literal[-3] @@ -89,9 +99,18 @@ WRITABLE: Literal[4] TCL_VERSION: str TK_VERSION: str -# TODO: figure out what these are (with e.g. help()) and get rid of Any -TkttType: Any -_flatten: Any -create: Any -getbusywaitinterval: Any -setbusywaitinterval: Any +class TkttType: + def deletetimerhandler(self): ... + +def create( + __screenName: str | None = ..., + __baseName: str | None = ..., + __className: str = ..., + __interactive: bool = ..., + __wantobjects: bool = ..., + __wantTk: bool = ..., + __sync: bool = ..., + __use: str | None = ..., +): ... +def getbusywaitinterval(): ... +def setbusywaitinterval(__new_val): ... diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index 0d4c42afc285..b076c1f6cbbe 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -7,8 +7,8 @@ import ctypes import mmap import sys from os import PathLike -from typing import AbstractSet, Any, Awaitable, Container, Iterable, Protocol, TypeVar, Union -from typing_extensions import Literal, final +from typing import AbstractSet, Any, Awaitable, Container, Generic, Iterable, Protocol, TypeVar, Union +from typing_extensions import Final, Literal, final _KT = TypeVar("_KT") _KT_co = TypeVar("_KT_co", covariant=True) @@ -35,16 +35,6 @@ class SupportsNext(Protocol[_T_co]): class SupportsAnext(Protocol[_T_co]): def __anext__(self) -> Awaitable[_T_co]: ... -class SupportsLessThan(Protocol): - def __lt__(self, __other: Any) -> bool: ... - -SupportsLessThanT = TypeVar("SupportsLessThanT", bound=SupportsLessThan) # noqa: Y001 - -class SupportsGreaterThan(Protocol): - def __gt__(self, __other: Any) -> bool: ... - -SupportsGreaterThanT = TypeVar("SupportsGreaterThanT", bound=SupportsGreaterThan) # noqa: Y001 - # Comparison protocols class SupportsDunderLT(Protocol): @@ -209,3 +199,20 @@ else: @final class NoneType: def __bool__(self) -> Literal[False]: ... + +# This is an internal CPython type that is like, but subtly different from, a NamedTuple +# Subclasses of this type are found in multiple modules. +# In typeshed, `structseq` is only ever used as a mixin in combination with a fixed-length `Tuple` +# See discussion at #6546 & #6560 +# `structseq` classes are unsubclassable, so are all decorated with `@final`. +class structseq(Generic[_T_co]): + n_fields: Final[int] + n_unnamed_fields: Final[int] + n_sequence_fields: Final[int] + # The first parameter will generally only take an iterable of a specific length. + # E.g. `os.uname_result` takes any iterable of length exactly 5. + # + # The second parameter will accept a dict of any kind without raising an exception, + # but only has any meaning if you supply it a dict where the keys are strings. + # https://github.com/python/typeshed/pull/6560#discussion_r767149830 + def __new__(cls: type[Self], sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> Self: ... diff --git a/mypy/typeshed/stdlib/_typeshed/dbapi.pyi b/mypy/typeshed/stdlib/_typeshed/dbapi.pyi new file mode 100644 index 000000000000..eee4fc03874e --- /dev/null +++ b/mypy/typeshed/stdlib/_typeshed/dbapi.pyi @@ -0,0 +1,36 @@ +# PEP 249 Database API 2.0 Types +# https://www.python.org/dev/peps/pep-0249/ + +from collections.abc import Mapping, Sequence +from typing import Any, Protocol + +DBAPITypeCode = Any | None +# Strictly speaking, this should be a Sequence, but the type system does +# not support fixed-length sequences. +DBAPIColumnDescription = tuple[str, DBAPITypeCode, int | None, int | None, int | None, int | None, bool | None] + +class DBAPIConnection(Protocol): + def close(self) -> object: ... + def commit(self) -> object: ... + # optional: + # def rollback(self) -> Any: ... + def cursor(self) -> DBAPICursor: ... + +class DBAPICursor(Protocol): + @property + def description(self) -> Sequence[DBAPIColumnDescription] | None: ... + @property + def rowcount(self) -> int: ... + # optional: + # def callproc(self, __procname: str, __parameters: Sequence[Any] = ...) -> Sequence[Any]: ... + def close(self) -> object: ... + def execute(self, __operation: str, __parameters: Sequence[Any] | Mapping[str, Any] = ...) -> object: ... + def executemany(self, __operation: str, __seq_of_parameters: Sequence[Sequence[Any]]) -> object: ... + def fetchone(self) -> Sequence[Any] | None: ... + def fetchmany(self, __size: int = ...) -> Sequence[Sequence[Any]]: ... + def fetchall(self) -> Sequence[Sequence[Any]]: ... + # optional: + # def nextset(self) -> None | Literal[True]: ... + arraysize: int + def setinputsizes(self, __sizes: Sequence[DBAPITypeCode | int | None]) -> object: ... + def setoutputsize(self, __size: int, __column: int = ...) -> object: ... diff --git a/mypy/typeshed/stdlib/_typeshed/wsgi.pyi b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi index 658b0fed2c6c..031d1472b6c5 100644 --- a/mypy/typeshed/stdlib/_typeshed/wsgi.pyi +++ b/mypy/typeshed/stdlib/_typeshed/wsgi.pyi @@ -3,7 +3,7 @@ # See the README.md file in this directory for more information. from sys import _OptExcInfo -from typing import Any, Callable, Dict, Iterable, Protocol +from typing import Any, Callable, Iterable, Protocol # stable class StartResponse(Protocol): @@ -11,7 +11,7 @@ class StartResponse(Protocol): self, status: str, headers: list[tuple[str, str]], exc_info: _OptExcInfo | None = ... ) -> Callable[[bytes], Any]: ... -WSGIEnvironment = Dict[str, Any] # stable +WSGIEnvironment = dict[str, Any] # stable WSGIApplication = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]] # stable # WSGI input streams per PEP 3333, stable diff --git a/mypy/typeshed/stdlib/_typeshed/xml.pyi b/mypy/typeshed/stdlib/_typeshed/xml.pyi index d53b743af2d3..231c2b86e912 100644 --- a/mypy/typeshed/stdlib/_typeshed/xml.pyi +++ b/mypy/typeshed/stdlib/_typeshed/xml.pyi @@ -1,7 +1,6 @@ # See the README.md file in this directory for more information. -from typing import Any -from typing_extensions import Protocol +from typing import Any, Protocol # As defined https://docs.python.org/3/library/xml.dom.html#domimplementation-objects class DOMImplementation(Protocol): diff --git a/mypy/typeshed/stdlib/_warnings.pyi b/mypy/typeshed/stdlib/_warnings.pyi index e5b180b14fea..2eb9ae478a5d 100644 --- a/mypy/typeshed/stdlib/_warnings.pyi +++ b/mypy/typeshed/stdlib/_warnings.pyi @@ -1,21 +1,21 @@ -from typing import Any, Type, overload +from typing import Any, overload _defaultaction: str _onceregistry: dict[Any, Any] -filters: list[tuple[str, str | None, Type[Warning], str | None, int]] +filters: list[tuple[str, str | None, type[Warning], str | None, int]] @overload -def warn(message: str, category: Type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ...) -> None: ... +def warn(message: str, category: type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ...) -> None: ... @overload def warn(message: Warning, category: Any = ..., stacklevel: int = ..., source: Any | None = ...) -> None: ... @overload def warn_explicit( message: str, - category: Type[Warning], + category: type[Warning], filename: str, lineno: int, module: str | None = ..., - registry: dict[str | tuple[str, Type[Warning], int], int] | None = ..., + registry: dict[str | tuple[str, type[Warning], int], int] | None = ..., module_globals: dict[str, Any] | None = ..., source: Any | None = ..., ) -> None: ... @@ -26,7 +26,7 @@ def warn_explicit( filename: str, lineno: int, module: str | None = ..., - registry: dict[str | tuple[str, Type[Warning], int], int] | None = ..., + registry: dict[str | tuple[str, type[Warning], int], int] | None = ..., module_globals: dict[str, Any] | None = ..., source: Any | None = ..., ) -> None: ... diff --git a/mypy/typeshed/stdlib/_weakref.pyi b/mypy/typeshed/stdlib/_weakref.pyi index dcaef25b3f0f..00dc2d5114b8 100644 --- a/mypy/typeshed/stdlib/_weakref.pyi +++ b/mypy/typeshed/stdlib/_weakref.pyi @@ -11,6 +11,7 @@ _T = TypeVar("_T") @final class CallableProxyType(Generic[_C]): # "weakcallableproxy" def __getattr__(self, attr: str) -> Any: ... + __call__: _C @final class ProxyType(Generic[_T]): # "weakproxy" diff --git a/mypy/typeshed/stdlib/_weakrefset.pyi b/mypy/typeshed/stdlib/_weakrefset.pyi index 1f0132f4c240..c738fa8df654 100644 --- a/mypy/typeshed/stdlib/_weakrefset.pyi +++ b/mypy/typeshed/stdlib/_weakrefset.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from typing import Any, Generic, Iterable, Iterator, MutableSet, TypeVar if sys.version_info >= (3, 9): @@ -6,14 +7,13 @@ if sys.version_info >= (3, 9): _S = TypeVar("_S") _T = TypeVar("_T") -_SelfT = TypeVar("_SelfT", bound=WeakSet[Any]) class WeakSet(MutableSet[_T], Generic[_T]): def __init__(self, data: Iterable[_T] | None = ...) -> None: ... def add(self, item: _T) -> None: ... def clear(self) -> None: ... def discard(self, item: _T) -> None: ... - def copy(self: _SelfT) -> _SelfT: ... + def copy(self: Self) -> Self: ... def pop(self) -> _T: ... def remove(self, item: _T) -> None: ... def update(self, other: Iterable[_T]) -> None: ... @@ -21,14 +21,14 @@ class WeakSet(MutableSet[_T], Generic[_T]): def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... def __ior__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ... - def difference(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def __sub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def difference(self: Self, other: Iterable[_T]) -> Self: ... + def __sub__(self: Self, other: Iterable[_T]) -> Self: ... def difference_update(self, other: Iterable[_T]) -> None: ... - def __isub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def intersection(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def __and__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def __isub__(self: Self, other: Iterable[_T]) -> Self: ... + def intersection(self: Self, other: Iterable[_T]) -> Self: ... + def __and__(self: Self, other: Iterable[_T]) -> Self: ... def intersection_update(self, other: Iterable[_T]) -> None: ... - def __iand__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... + def __iand__(self: Self, other: Iterable[_T]) -> Self: ... def issubset(self, other: Iterable[_T]) -> bool: ... def __le__(self, other: Iterable[_T]) -> bool: ... def __lt__(self, other: Iterable[_T]) -> bool: ... diff --git a/mypy/typeshed/stdlib/_winapi.pyi b/mypy/typeshed/stdlib/_winapi.pyi index 83089d485c17..eba236597840 100644 --- a/mypy/typeshed/stdlib/_winapi.pyi +++ b/mypy/typeshed/stdlib/_winapi.pyi @@ -2,133 +2,194 @@ import sys from typing import Any, NoReturn, Sequence, overload from typing_extensions import Literal, final -CREATE_NEW_CONSOLE: int -CREATE_NEW_PROCESS_GROUP: int -DUPLICATE_CLOSE_SOURCE: int -DUPLICATE_SAME_ACCESS: int -ERROR_ALREADY_EXISTS: int -ERROR_BROKEN_PIPE: int -ERROR_IO_PENDING: int -ERROR_MORE_DATA: int -ERROR_NETNAME_DELETED: int -ERROR_NO_DATA: int -ERROR_NO_SYSTEM_RESOURCES: int -ERROR_OPERATION_ABORTED: int -ERROR_PIPE_BUSY: int -ERROR_PIPE_CONNECTED: int -ERROR_SEM_TIMEOUT: int -FILE_FLAG_FIRST_PIPE_INSTANCE: int -FILE_FLAG_OVERLAPPED: int -FILE_GENERIC_READ: int -FILE_GENERIC_WRITE: int -GENERIC_READ: int -GENERIC_WRITE: int -INFINITE: int -NMPWAIT_WAIT_FOREVER: int -NULL: int -OPEN_EXISTING: int -PIPE_ACCESS_DUPLEX: int -PIPE_ACCESS_INBOUND: int -PIPE_READMODE_MESSAGE: int -PIPE_TYPE_MESSAGE: int -PIPE_UNLIMITED_INSTANCES: int -PIPE_WAIT: int -PROCESS_ALL_ACCESS: int -PROCESS_DUP_HANDLE: int -STARTF_USESHOWWINDOW: int -STARTF_USESTDHANDLES: int -STD_ERROR_HANDLE: int -STD_INPUT_HANDLE: int -STD_OUTPUT_HANDLE: int -STILL_ACTIVE: int -SW_HIDE: int -WAIT_ABANDONED_0: int -WAIT_OBJECT_0: int -WAIT_TIMEOUT: int +if sys.platform == "win32": + if sys.version_info >= (3, 7): + ABOVE_NORMAL_PRIORITY_CLASS: Literal[32768] + BELOW_NORMAL_PRIORITY_CLASS: Literal[16384] + CREATE_BREAKAWAY_FROM_JOB: Literal[16777216] + CREATE_DEFAULT_ERROR_MODE: Literal[67108864] + CREATE_NO_WINDOW: Literal[134217728] + CREATE_NEW_CONSOLE: Literal[16] + CREATE_NEW_PROCESS_GROUP: Literal[512] + if sys.version_info >= (3, 7): + DETACHED_PROCESS: Literal[8] + DUPLICATE_CLOSE_SOURCE: Literal[1] + DUPLICATE_SAME_ACCESS: Literal[2] -def CloseHandle(__handle: int) -> None: ... -@overload -def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ... -@overload -def ConnectNamedPipe(handle: int, overlapped: Literal[False] = ...) -> None: ... -@overload -def ConnectNamedPipe(handle: int, overlapped: bool) -> Overlapped | None: ... -def CreateFile( - __file_name: str, - __desired_access: int, - __share_mode: int, - __security_attributes: int, - __creation_disposition: int, - __flags_and_attributes: int, - __template_file: int, -) -> int: ... -def CreateJunction(__src_path: str, __dst_path: str) -> None: ... -def CreateNamedPipe( - __name: str, - __open_mode: int, - __pipe_mode: int, - __max_instances: int, - __out_buffer_size: int, - __in_buffer_size: int, - __default_timeout: int, - __security_attributes: int, -) -> int: ... -def CreatePipe(__pipe_attrs: Any, __size: int) -> tuple[int, int]: ... -def CreateProcess( - __application_name: str | None, - __command_line: str | None, - __proc_attrs: Any, - __thread_attrs: Any, - __inherit_handles: bool, - __creation_flags: int, - __env_mapping: dict[str, str], - __current_directory: str | None, - __startup_info: Any, -) -> tuple[int, int, int, int]: ... -def DuplicateHandle( - __source_process_handle: int, - __source_handle: int, - __target_process_handle: int, - __desired_access: int, - __inherit_handle: bool, - __options: int = ..., -) -> int: ... -def ExitProcess(__ExitCode: int) -> NoReturn: ... + ERROR_ALREADY_EXISTS: Literal[183] + ERROR_BROKEN_PIPE: Literal[109] + ERROR_IO_PENDING: Literal[997] + ERROR_MORE_DATA: Literal[234] + ERROR_NETNAME_DELETED: Literal[64] + ERROR_NO_DATA: Literal[232] + ERROR_NO_SYSTEM_RESOURCES: Literal[1450] + ERROR_OPERATION_ABORTED: Literal[995] + ERROR_PIPE_BUSY: Literal[231] + ERROR_PIPE_CONNECTED: Literal[535] + ERROR_SEM_TIMEOUT: Literal[121] -if sys.version_info >= (3, 7): - def GetACP() -> int: ... - def GetFileType(handle: int) -> int: ... + FILE_FLAG_FIRST_PIPE_INSTANCE: Literal[524288] + FILE_FLAG_OVERLAPPED: Literal[1073741824] + FILE_GENERIC_READ: Literal[1179785] + FILE_GENERIC_WRITE: Literal[1179926] + if sys.version_info >= (3, 8): + FILE_MAP_ALL_ACCESS: Literal[983071] + FILE_MAP_COPY: Literal[1] + FILE_MAP_EXECUTE: Literal[32] + FILE_MAP_READ: Literal[4] + FILE_MAP_WRITE: Literal[2] + if sys.version_info >= (3, 7): + FILE_TYPE_CHAR: Literal[2] + FILE_TYPE_DISK: Literal[1] + FILE_TYPE_PIPE: Literal[3] + FILE_TYPE_REMOTE: Literal[32768] + FILE_TYPE_UNKNOWN: Literal[0] -def GetCurrentProcess() -> int: ... -def GetExitCodeProcess(__process: int) -> int: ... -def GetLastError() -> int: ... -def GetModuleFileName(__module_handle: int) -> str: ... -def GetStdHandle(__std_handle: int) -> int: ... -def GetVersion() -> int: ... -def OpenProcess(__desired_access: int, __inherit_handle: bool, __process_id: int) -> int: ... -def PeekNamedPipe(__handle: int, __size: int = ...) -> tuple[int, int] | tuple[bytes, int, int]: ... -@overload -def ReadFile(handle: int, size: int, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... -@overload -def ReadFile(handle: int, size: int, overlapped: Literal[False] = ...) -> tuple[bytes, int]: ... -@overload -def ReadFile(handle: int, size: int, overlapped: int | bool) -> tuple[Any, int]: ... -def SetNamedPipeHandleState( - __named_pipe: int, __mode: int | None, __max_collection_count: int | None, __collect_data_timeout: int | None -) -> None: ... -def TerminateProcess(__handle: int, __exit_code: int) -> None: ... -def WaitForMultipleObjects(__handle_seq: Sequence[int], __wait_flag: bool, __milliseconds: int = ...) -> int: ... -def WaitForSingleObject(__handle: int, __milliseconds: int) -> int: ... -def WaitNamedPipe(__name: str, __timeout: int) -> None: ... -@overload -def WriteFile(handle: int, buffer: bytes, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... -@overload -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]: ... - def cancel(self) -> None: ... - def getbuffer(self) -> bytes | None: ... + GENERIC_READ: Literal[2147483648] + GENERIC_WRITE: Literal[1073741824] + if sys.version_info >= (3, 7): + HIGH_PRIORITY_CLASS: Literal[128] + INFINITE: Literal[4294967295] + if sys.version_info >= (3, 8): + INVALID_HANDLE_VALUE: int # very large number + if sys.version_info >= (3, 7): + IDLE_PRIORITY_CLASS: Literal[64] + NORMAL_PRIORITY_CLASS: Literal[32] + REALTIME_PRIORITY_CLASS: Literal[256] + NMPWAIT_WAIT_FOREVER: Literal[4294967295] + + if sys.version_info >= (3, 8): + MEM_COMMIT: Literal[4096] + MEM_FREE: Literal[65536] + MEM_IMAGE: Literal[16777216] + MEM_MAPPED: Literal[262144] + MEM_PRIVATE: Literal[131072] + MEM_RESERVE: Literal[8192] + + NULL: Literal[0] + OPEN_EXISTING: Literal[3] + + PIPE_ACCESS_DUPLEX: Literal[3] + PIPE_ACCESS_INBOUND: Literal[1] + PIPE_READMODE_MESSAGE: Literal[2] + PIPE_TYPE_MESSAGE: Literal[4] + PIPE_UNLIMITED_INSTANCES: Literal[255] + PIPE_WAIT: Literal[0] + if sys.version_info >= (3, 8): + PAGE_EXECUTE: Literal[16] + PAGE_EXECUTE_READ: Literal[32] + PAGE_EXECUTE_READWRITE: Literal[64] + PAGE_EXECUTE_WRITECOPY: Literal[128] + PAGE_GUARD: Literal[256] + PAGE_NOACCESS: Literal[1] + PAGE_NOCACHE: Literal[512] + PAGE_READONLY: Literal[2] + PAGE_READWRITE: Literal[4] + PAGE_WRITECOMBINE: Literal[1024] + PAGE_WRITECOPY: Literal[8] + + PROCESS_ALL_ACCESS: Literal[2097151] + PROCESS_DUP_HANDLE: Literal[64] + if sys.version_info >= (3, 8): + SEC_COMMIT: Literal[134217728] + SEC_IMAGE: Literal[16777216] + SEC_LARGE_PAGES: Literal[2147483648] + SEC_NOCACHE: Literal[268435456] + SEC_RESERVE: Literal[67108864] + SEC_WRITECOMBINE: Literal[1073741824] + STARTF_USESHOWWINDOW: Literal[1] + STARTF_USESTDHANDLES: Literal[256] + STD_ERROR_HANDLE: Literal[4294967284] + STD_INPUT_HANDLE: Literal[4294967286] + STD_OUTPUT_HANDLE: Literal[4294967285] + STILL_ACTIVE: Literal[259] + SW_HIDE: Literal[0] + if sys.version_info >= (3, 8): + SYNCHRONIZE: Literal[1048576] + WAIT_ABANDONED_0: Literal[128] + WAIT_OBJECT_0: Literal[0] + WAIT_TIMEOUT: Literal[258] + def CloseHandle(__handle: int) -> None: ... + @overload + def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ... + @overload + def ConnectNamedPipe(handle: int, overlapped: Literal[False] = ...) -> None: ... + @overload + def ConnectNamedPipe(handle: int, overlapped: bool) -> Overlapped | None: ... + def CreateFile( + __file_name: str, + __desired_access: int, + __share_mode: int, + __security_attributes: int, + __creation_disposition: int, + __flags_and_attributes: int, + __template_file: int, + ) -> int: ... + def CreateJunction(__src_path: str, __dst_path: str) -> None: ... + def CreateNamedPipe( + __name: str, + __open_mode: int, + __pipe_mode: int, + __max_instances: int, + __out_buffer_size: int, + __in_buffer_size: int, + __default_timeout: int, + __security_attributes: int, + ) -> int: ... + def CreatePipe(__pipe_attrs: Any, __size: int) -> tuple[int, int]: ... + def CreateProcess( + __application_name: str | None, + __command_line: str | None, + __proc_attrs: Any, + __thread_attrs: Any, + __inherit_handles: bool, + __creation_flags: int, + __env_mapping: dict[str, str], + __current_directory: str | None, + __startup_info: Any, + ) -> tuple[int, int, int, int]: ... + def DuplicateHandle( + __source_process_handle: int, + __source_handle: int, + __target_process_handle: int, + __desired_access: int, + __inherit_handle: bool, + __options: int = ..., + ) -> int: ... + def ExitProcess(__ExitCode: int) -> NoReturn: ... + if sys.version_info >= (3, 7): + def GetACP() -> int: ... + def GetFileType(handle: int) -> int: ... + def GetCurrentProcess() -> int: ... + def GetExitCodeProcess(__process: int) -> int: ... + def GetLastError() -> int: ... + def GetModuleFileName(__module_handle: int) -> str: ... + def GetStdHandle(__std_handle: int) -> int: ... + def GetVersion() -> int: ... + def OpenProcess(__desired_access: int, __inherit_handle: bool, __process_id: int) -> int: ... + def PeekNamedPipe(__handle: int, __size: int = ...) -> tuple[int, int] | tuple[bytes, int, int]: ... + @overload + def ReadFile(handle: int, size: int, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... + @overload + def ReadFile(handle: int, size: int, overlapped: Literal[False] = ...) -> tuple[bytes, int]: ... + @overload + def ReadFile(handle: int, size: int, overlapped: int | bool) -> tuple[Any, int]: ... + def SetNamedPipeHandleState( + __named_pipe: int, __mode: int | None, __max_collection_count: int | None, __collect_data_timeout: int | None + ) -> None: ... + def TerminateProcess(__handle: int, __exit_code: int) -> None: ... + def WaitForMultipleObjects(__handle_seq: Sequence[int], __wait_flag: bool, __milliseconds: int = ...) -> int: ... + def WaitForSingleObject(__handle: int, __milliseconds: int) -> int: ... + def WaitNamedPipe(__name: str, __timeout: int) -> None: ... + @overload + def WriteFile(handle: int, buffer: bytes, overlapped: Literal[True]) -> tuple[Overlapped, int]: ... + @overload + 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]: ... + def cancel(self) -> None: ... + def getbuffer(self) -> bytes | None: ... diff --git a/mypy/typeshed/stdlib/abc.pyi b/mypy/typeshed/stdlib/abc.pyi index 7896e910c81f..33a53cc74c33 100644 --- a/mypy/typeshed/stdlib/abc.pyi +++ b/mypy/typeshed/stdlib/abc.pyi @@ -1,5 +1,6 @@ +import sys from _typeshed import SupportsWrite -from typing import Any, Callable, Tuple, Type, TypeVar +from typing import Any, Callable, TypeVar _T = TypeVar("_T") _FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) @@ -7,11 +8,11 @@ _FuncT = TypeVar("_FuncT", bound=Callable[..., Any]) # These definitions have special processing in mypy class ABCMeta(type): __abstractmethods__: frozenset[str] - def __init__(self, name: str, bases: Tuple[type, ...], namespace: dict[str, Any]) -> None: ... + def __init__(self, name: str, bases: tuple[type, ...], namespace: dict[str, Any]) -> None: ... def __instancecheck__(cls: ABCMeta, instance: Any) -> Any: ... def __subclasscheck__(cls: ABCMeta, subclass: Any) -> Any: ... def _dump_registry(cls: ABCMeta, file: SupportsWrite[str] | None = ...) -> None: ... - def register(cls: ABCMeta, subclass: Type[_T]) -> Type[_T]: ... + def register(cls: ABCMeta, subclass: type[_T]) -> type[_T]: ... def abstractmethod(funcobj: _FuncT) -> _FuncT: ... @@ -24,3 +25,6 @@ def abstractclassmethod(callable: _FuncT) -> _FuncT: ... class ABC(metaclass=ABCMeta): ... def get_cache_token() -> object: ... + +if sys.version_info >= (3, 10): + def update_abstractmethods(cls: type[_T]) -> type[_T]: ... diff --git a/mypy/typeshed/stdlib/aifc.pyi b/mypy/typeshed/stdlib/aifc.pyi index 79f470a366bb..f88459befa27 100644 --- a/mypy/typeshed/stdlib/aifc.pyi +++ b/mypy/typeshed/stdlib/aifc.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Self from types import TracebackType -from typing import IO, Any, NamedTuple, Tuple, Type, Union, overload +from typing import IO, Any, NamedTuple, Union, overload from typing_extensions import Literal class Error(Exception): ... @@ -15,13 +15,13 @@ class _aifc_params(NamedTuple): compname: bytes _File = Union[str, IO[bytes]] -_Marker = Tuple[int, int, bytes] +_Marker = tuple[int, int, bytes] class Aifc_read: def __init__(self, f: _File) -> 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 initfp(self, file: IO[bytes]) -> None: ... def getfp(self) -> IO[bytes]: ... @@ -45,7 +45,7 @@ class Aifc_write: def __del__(self) -> 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 initfp(self, file: IO[bytes]) -> None: ... def aiff(self) -> None: ... diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index b9a09f56a812..d2b18d42c5d4 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -1,20 +1,5 @@ import sys -from typing import ( - IO, - Any, - Callable, - Generator, - Generic, - Iterable, - NoReturn, - Pattern, - Protocol, - Sequence, - Tuple, - Type, - TypeVar, - overload, -) +from typing import IO, Any, Callable, Generator, Generic, Iterable, NoReturn, Pattern, Protocol, Sequence, TypeVar, overload _T = TypeVar("_T") _ActionT = TypeVar("_ActionT", bound=Action) @@ -62,15 +47,15 @@ class _ActionsContainer: def add_argument( self, *name_or_flags: str, - action: str | Type[Action] = ..., + action: str | type[Action] = ..., nargs: int | str = ..., const: Any = ..., default: Any = ..., - type: Callable[[str], _T] | Callable[[str], _T] | FileType = ..., + type: Callable[[str], _T] | FileType = ..., choices: Iterable[_T] | None = ..., required: bool = ..., help: str | None = ..., - metavar: str | Tuple[str, ...] | None = ..., + metavar: str | tuple[str, ...] | None = ..., dest: str | None = ..., version: str = ..., **kwargs: Any, @@ -82,7 +67,7 @@ class _ActionsContainer: def _add_container_actions(self, container: _ActionsContainer) -> None: ... def _get_positional_kwargs(self, dest: str, **kwargs: Any) -> dict[str, Any]: ... def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> dict[str, Any]: ... - def _pop_action_class(self, kwargs: Any, default: Type[Action] | None = ...) -> Type[Action]: ... + def _pop_action_class(self, kwargs: Any, default: type[Action] | None = ...) -> type[Action]: ... def _get_handler(self) -> Callable[[Action, Iterable[tuple[str, Action]]], Any]: ... def _check_conflict(self, action: Action) -> None: ... def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> NoReturn: ... @@ -143,11 +128,11 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): @overload def parse_args(self, args: Sequence[str] | None = ...) -> Namespace: ... @overload - def parse_args(self, args: Sequence[str] | None, namespace: None) -> Namespace: ... # type: ignore + def parse_args(self, args: Sequence[str] | None, namespace: None) -> Namespace: ... # type: ignore[misc] @overload def parse_args(self, args: Sequence[str] | None, namespace: _N) -> _N: ... @overload - def parse_args(self, *, namespace: None) -> Namespace: ... # type: ignore + def parse_args(self, *, namespace: None) -> Namespace: ... # type: ignore[misc] @overload def parse_args(self, *, namespace: _N) -> _N: ... if sys.version_info >= (3, 7): @@ -158,7 +143,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): title: str = ..., description: str | None = ..., prog: str = ..., - action: Type[Action] = ..., + action: type[Action] = ..., option_string: str = ..., dest: str | None = ..., required: bool = ..., @@ -172,8 +157,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): title: str = ..., description: str | None = ..., prog: str = ..., - parser_class: Type[_ArgumentParserT] = ..., - action: Type[Action] = ..., + parser_class: type[_ArgumentParserT] = ..., + action: type[Action] = ..., option_string: str = ..., dest: str | None = ..., required: bool = ..., @@ -188,7 +173,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): title: str = ..., description: str | None = ..., prog: str = ..., - action: Type[Action] = ..., + action: type[Action] = ..., option_string: str = ..., dest: str | None = ..., help: str | None = ..., @@ -201,8 +186,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): title: str = ..., description: str | None = ..., prog: str = ..., - parser_class: Type[_ArgumentParserT] = ..., - action: Type[Action] = ..., + parser_class: type[_ArgumentParserT] = ..., + action: type[Action] = ..., option_string: str = ..., dest: str | None = ..., help: str | None = ..., @@ -252,7 +237,7 @@ class HelpFormatter: _current_section: Any _whitespace_matcher: Pattern[str] _long_break_matcher: Pattern[str] - _Section: Type[Any] # Nested class + _Section: type[Any] # Nested class def __init__(self, prog: str, indent_increment: int = ..., max_help_position: int = ..., width: int | None = ...) -> None: ... def _indent(self) -> None: ... def _dedent(self) -> None: ... @@ -274,7 +259,7 @@ class HelpFormatter: def _format_text(self, text: str) -> str: ... def _format_action(self, action: Action) -> str: ... def _format_action_invocation(self, action: Action) -> str: ... - def _metavar_formatter(self, action: Action, default_metavar: str) -> Callable[[int], Tuple[str, ...]]: ... + def _metavar_formatter(self, action: Action, default_metavar: str) -> Callable[[int], tuple[str, ...]]: ... def _format_args(self, action: Action, default_metavar: str) -> str: ... def _expand_help(self, action: Action) -> str: ... def _iter_indented_subactions(self, action: Action) -> Generator[Action, None, None]: ... @@ -299,7 +284,7 @@ class Action(_AttributeHolder): choices: Iterable[Any] | None required: bool help: str | None - metavar: str | Tuple[str, ...] | None + metavar: str | tuple[str, ...] | None def __init__( self, option_strings: Sequence[str], @@ -307,11 +292,11 @@ class Action(_AttributeHolder): nargs: int | str | None = ..., const: _T | None = ..., default: _T | str | None = ..., - type: Callable[[str], _T] | Callable[[str], _T] | FileType | None = ..., + type: Callable[[str], _T] | FileType | None = ..., choices: Iterable[_T] | None = ..., required: bool = ..., help: str | None = ..., - metavar: str | Tuple[str, ...] | None = ..., + metavar: str | tuple[str, ...] | None = ..., ) -> None: ... def __call__( self, parser: ArgumentParser, namespace: Namespace, values: str | Sequence[Any] | None, option_string: str | None = ... @@ -326,11 +311,11 @@ if sys.version_info >= (3, 9): option_strings: Sequence[str], dest: str, default: _T | str | None = ..., - type: Callable[[str], _T] | Callable[[str], _T] | FileType | None = ..., + type: Callable[[str], _T] | FileType | None = ..., choices: Iterable[_T] | None = ..., required: bool = ..., help: str | None = ..., - metavar: str | Tuple[str, ...] | None = ..., + metavar: str | tuple[str, ...] | None = ..., ) -> None: ... class Namespace(_AttributeHolder): @@ -375,7 +360,7 @@ class _StoreConstAction(Action): default: Any = ..., required: bool = ..., help: str | None = ..., - metavar: str | Tuple[str, ...] | None = ..., + metavar: str | tuple[str, ...] | None = ..., ) -> None: ... # undocumented @@ -403,7 +388,7 @@ class _AppendConstAction(Action): default: Any = ..., required: bool = ..., help: str | None = ..., - metavar: str | Tuple[str, ...] | None = ..., + metavar: str | tuple[str, ...] | None = ..., ) -> None: ... # undocumented @@ -425,9 +410,9 @@ class _VersionAction(Action): # undocumented class _SubParsersAction(Action, Generic[_ArgumentParserT]): - _ChoicesPseudoAction: Type[Any] # nested class + _ChoicesPseudoAction: type[Any] # nested class _prog_prefix: str - _parser_class: Type[_ArgumentParserT] + _parser_class: type[_ArgumentParserT] _name_parser_map: dict[str, _ArgumentParserT] choices: dict[str, _ArgumentParserT] _choices_actions: list[Action] @@ -436,21 +421,21 @@ class _SubParsersAction(Action, Generic[_ArgumentParserT]): self, option_strings: Sequence[str], prog: str, - parser_class: Type[_ArgumentParserT], + parser_class: type[_ArgumentParserT], dest: str = ..., required: bool = ..., help: str | None = ..., - metavar: str | Tuple[str, ...] | None = ..., + metavar: str | tuple[str, ...] | None = ..., ) -> None: ... else: def __init__( self, option_strings: Sequence[str], prog: str, - parser_class: Type[_ArgumentParserT], + parser_class: type[_ArgumentParserT], dest: str = ..., help: str | None = ..., - metavar: str | Tuple[str, ...] | None = ..., + metavar: str | tuple[str, ...] | None = ..., ) -> None: ... # TODO: Type keyword args properly. def add_parser(self, name: str, **kwargs: Any) -> _ArgumentParserT: ... diff --git a/mypy/typeshed/stdlib/array.pyi b/mypy/typeshed/stdlib/array.pyi index 6f4444b10f96..87b6027f73ac 100644 --- a/mypy/typeshed/stdlib/array.pyi +++ b/mypy/typeshed/stdlib/array.pyi @@ -1,6 +1,6 @@ import sys -from typing import Any, BinaryIO, Generic, Iterable, MutableSequence, TypeVar, Union, overload -from typing_extensions import Literal +from typing import BinaryIO, Generic, Iterable, MutableSequence, TypeVar, Union, overload +from typing_extensions import Literal, SupportsIndex _IntTypeCode = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] _FloatTypeCode = Literal["f", "d"] @@ -25,7 +25,7 @@ class array(MutableSequence[_T], Generic[_T]): def append(self, __v: _T) -> None: ... def buffer_info(self) -> tuple[int, int]: ... def byteswap(self) -> None: ... - def count(self, __v: Any) -> int: ... + def count(self, __v: _T) -> int: ... def extend(self, __bb: Iterable[_T]) -> None: ... def frombytes(self, __buffer: bytes) -> None: ... def fromfile(self, __f: BinaryIO, __n: int) -> None: ... @@ -37,7 +37,7 @@ class array(MutableSequence[_T], Generic[_T]): def index(self, __v: _T) -> int: ... # type: ignore # Overrides Sequence def insert(self, __i: int, __v: _T) -> None: ... def pop(self, __i: int = ...) -> _T: ... - def remove(self, __v: Any) -> None: ... + def remove(self, __v: _T) -> None: ... def reverse(self) -> None: ... def tobytes(self) -> bytes: ... def tofile(self, __f: BinaryIO) -> None: ... @@ -48,14 +48,14 @@ 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: SupportsIndex) -> _T: ... @overload def __getitem__(self, __s: slice) -> array[_T]: ... @overload # type: ignore # Overrides MutableSequence - def __setitem__(self, __i: int, __o: _T) -> None: ... + def __setitem__(self, __i: SupportsIndex, __o: _T) -> None: ... @overload def __setitem__(self, __s: slice, __o: array[_T]) -> None: ... - def __delitem__(self, __i: int | slice) -> None: ... + def __delitem__(self, __i: SupportsIndex | slice) -> None: ... def __add__(self, __x: array[_T]) -> array[_T]: ... def __ge__(self, __other: array[_T]) -> bool: ... def __gt__(self, __other: array[_T]) -> bool: ... diff --git a/mypy/typeshed/stdlib/ast.pyi b/mypy/typeshed/stdlib/ast.pyi index 00c62c30c037..8494a3a99126 100644 --- a/mypy/typeshed/stdlib/ast.pyi +++ b/mypy/typeshed/stdlib/ast.pyi @@ -8,7 +8,7 @@ # sys. import sys import typing as _typing -from _ast import * # type: ignore +from _ast import * from typing import Any, Iterator, TypeVar, overload from typing_extensions import Literal @@ -165,6 +165,57 @@ if sys.version_info >= (3, 8): feature_version: None | int | _typing.Tuple[int, int] = ..., ) -> Module: ... @overload + def parse( + source: str | bytes, + filename: str | bytes, + mode: Literal["eval"], + *, + type_comments: bool = ..., + feature_version: None | int | _typing.Tuple[int, int] = ..., + ) -> Expression: ... + @overload + def parse( + source: str | bytes, + filename: str | bytes, + mode: Literal["func_type"], + *, + type_comments: bool = ..., + feature_version: None | int | _typing.Tuple[int, int] = ..., + ) -> FunctionType: ... + @overload + def parse( + source: str | bytes, + filename: str | bytes, + mode: Literal["single"], + *, + type_comments: bool = ..., + feature_version: None | int | _typing.Tuple[int, int] = ..., + ) -> Interactive: ... + @overload + def parse( + source: str | bytes, + *, + mode: Literal["eval"], + type_comments: bool = ..., + feature_version: None | int | _typing.Tuple[int, int] = ..., + ) -> Expression: ... + @overload + def parse( + source: str | bytes, + *, + mode: Literal["func_type"], + type_comments: bool = ..., + feature_version: None | int | _typing.Tuple[int, int] = ..., + ) -> FunctionType: ... + @overload + def parse( + source: str | bytes, + *, + mode: Literal["single"], + type_comments: bool = ..., + feature_version: None | int | _typing.Tuple[int, int] = ..., + ) -> Interactive: ... + @overload def parse( source: str | bytes, filename: str | bytes = ..., @@ -178,6 +229,14 @@ else: @overload def parse(source: str | bytes, filename: str | bytes = ..., mode: Literal["exec"] = ...) -> Module: ... @overload + def parse(source: str | bytes, filename: str | bytes, mode: Literal["eval"]) -> Expression: ... + @overload + def parse(source: str | bytes, filename: str | bytes, mode: Literal["single"]) -> Interactive: ... + @overload + def parse(source: str | bytes, *, mode: Literal["eval"]) -> Expression: ... + @overload + def parse(source: str | bytes, *, mode: Literal["single"]) -> Interactive: ... + @overload def parse(source: str | bytes, filename: str | bytes = ..., mode: str = ...) -> AST: ... if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/asyncio/__init__.pyi b/mypy/typeshed/stdlib/asyncio/__init__.pyi index 42e7aa9ba6d8..e75874627a30 100644 --- a/mypy/typeshed/stdlib/asyncio/__init__.pyi +++ b/mypy/typeshed/stdlib/asyncio/__init__.pyi @@ -1,8 +1,7 @@ import sys -from typing import Type from .base_events import BaseEventLoop as BaseEventLoop -from .coroutines import coroutine as coroutine, iscoroutine as iscoroutine, iscoroutinefunction as iscoroutinefunction +from .coroutines import iscoroutine as iscoroutine, iscoroutinefunction as iscoroutinefunction from .events import ( AbstractEventLoop as AbstractEventLoop, AbstractEventLoopPolicy as AbstractEventLoopPolicy, @@ -71,39 +70,48 @@ from .transports import ( WriteTransport as WriteTransport, ) -if sys.version_info >= (3, 7): - from .events import get_running_loop as get_running_loop +if sys.version_info < (3, 11): + from .coroutines import coroutine as coroutine + +if sys.version_info >= (3, 9): + from .threads import to_thread as to_thread + if sys.version_info >= (3, 8): from .exceptions import ( CancelledError as CancelledError, IncompleteReadError as IncompleteReadError, InvalidStateError as InvalidStateError, LimitOverrunError as LimitOverrunError, - SendfileNotAvailableError as SendfileNotAvailableError, TimeoutError as TimeoutError, ) else: - if sys.version_info >= (3, 7): - from .events import SendfileNotAvailableError as SendfileNotAvailableError from .futures import CancelledError as CancelledError, InvalidStateError as InvalidStateError, TimeoutError as TimeoutError from .streams import IncompleteReadError as IncompleteReadError, LimitOverrunError as LimitOverrunError -if sys.version_info >= (3, 7): - from .protocols import BufferedProtocol as BufferedProtocol +if sys.version_info >= (3, 8): + from .exceptions import SendfileNotAvailableError as SendfileNotAvailableError +elif sys.version_info >= (3, 7): + from .events import SendfileNotAvailableError as SendfileNotAvailableError if sys.version_info >= (3, 7): + from .events import get_running_loop as get_running_loop + from .protocols import BufferedProtocol as BufferedProtocol from .runners import run as run + from .tasks import ( + _enter_task as _enter_task, + _leave_task as _leave_task, + _register_task as _register_task, + _unregister_task as _unregister_task, + all_tasks as all_tasks, + create_task as create_task, + current_task as current_task, + ) -if sys.version_info >= (3, 7): - from .tasks import all_tasks as all_tasks, create_task as create_task, current_task as current_task -if sys.version_info >= (3, 9): - from .threads import to_thread as to_thread +DefaultEventLoopPolicy: type[AbstractEventLoopPolicy] -DefaultEventLoopPolicy: Type[AbstractEventLoopPolicy] if sys.platform == "win32": from .windows_events import * - -if sys.platform != "win32": +else: from .streams import open_unix_connection as open_unix_connection, start_unix_server as start_unix_server from .unix_events import ( AbstractChildWatcher as AbstractChildWatcher, diff --git a/mypy/typeshed/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi index 15471f54483f..b4b111698ea8 100644 --- a/mypy/typeshed/stdlib/asyncio/base_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_events.pyi @@ -9,18 +9,18 @@ from asyncio.tasks import Task from asyncio.transports import BaseTransport from collections.abc import Iterable from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Awaitable, Callable, Dict, Generator, Sequence, Tuple, TypeVar, Union, overload +from typing import IO, Any, Awaitable, Callable, Generator, Sequence, TypeVar, Union, overload from typing_extensions import Literal if sys.version_info >= (3, 7): from contextvars import Context _T = TypeVar("_T") -_Context = Dict[str, Any] +_ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) +_Context = dict[str, Any] _ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] _ProtocolFactory = Callable[[], BaseProtocol] _SSLContext = Union[bool, None, ssl.SSLContext] -_TransProtPair = Tuple[BaseTransport, BaseProtocol] class Server(AbstractServer): if sys.version_info >= (3, 7): @@ -37,7 +37,7 @@ class Server(AbstractServer): def __init__(self, loop: AbstractEventLoop, sockets: list[socket]) -> None: ... if sys.version_info >= (3, 8): @property - def sockets(self) -> Tuple[socket, ...]: ... + def sockets(self) -> tuple[socket, ...]: ... elif sys.version_info >= (3, 7): @property def sockets(self) -> list[socket]: ... @@ -95,7 +95,7 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, @@ -109,11 +109,11 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): ssl_handshake_timeout: float | None = ..., happy_eyeballs_delay: float | None = ..., interleave: int | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: None = ..., port: None = ..., *, @@ -127,12 +127,12 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): ssl_handshake_timeout: float | None = ..., happy_eyeballs_delay: float | None = ..., interleave: int | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... elif sys.version_info >= (3, 7): @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, @@ -144,11 +144,11 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): local_addr: tuple[str, int] | None = ..., server_hostname: str | None = ..., ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: None = ..., port: None = ..., *, @@ -160,12 +160,12 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): local_addr: None = ..., server_hostname: str | None = ..., ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... else: @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, @@ -176,11 +176,11 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): sock: None = ..., local_addr: tuple[str, int] | None = ..., server_hostname: str | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... @overload async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: None = ..., port: None = ..., *, @@ -191,7 +191,7 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): sock: socket, local_addr: None = ..., server_hostname: str | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... if sys.version_info >= (3, 7): async def sock_sendfile( self, sock: socket, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool | None = ... @@ -232,12 +232,12 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): ) -> Server: ... async def connect_accepted_socket( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], sock: socket, *, ssl: _SSLContext = ..., ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... async def sendfile( self, transport: BaseTransport, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool = ... ) -> int: ... @@ -283,28 +283,47 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): reuse_port: bool | None = ..., ) -> Server: ... async def connect_accepted_socket( - self, protocol_factory: _ProtocolFactory, sock: socket, *, ssl: _SSLContext = ... - ) -> _TransProtPair: ... - async def create_datagram_endpoint( - self, - protocol_factory: _ProtocolFactory, - local_addr: tuple[str, int] | None = ..., - remote_addr: tuple[str, int] | None = ..., - *, - family: int = ..., - proto: int = ..., - flags: int = ..., - reuse_address: bool | None = ..., - reuse_port: bool | None = ..., - allow_broadcast: bool | None = ..., - sock: socket | None = ..., - ) -> _TransProtPair: ... + self, protocol_factory: Callable[[], _ProtocolT], sock: socket, *, ssl: _SSLContext = ... + ) -> tuple[BaseTransport, _ProtocolT]: ... + if sys.version_info >= (3, 11): + async def create_datagram_endpoint( + self, + protocol_factory: Callable[[], _ProtocolT], + local_addr: tuple[str, int] | None = ..., + remote_addr: tuple[str, int] | None = ..., + *, + family: int = ..., + proto: int = ..., + flags: int = ..., + reuse_port: bool | None = ..., + allow_broadcast: bool | None = ..., + sock: socket | None = ..., + ) -> tuple[BaseTransport, _ProtocolT]: ... + else: + async def create_datagram_endpoint( + self, + protocol_factory: Callable[[], _ProtocolT], + local_addr: tuple[str, int] | None = ..., + remote_addr: tuple[str, int] | None = ..., + *, + family: int = ..., + proto: int = ..., + flags: int = ..., + reuse_address: bool | None = ..., + reuse_port: bool | None = ..., + allow_broadcast: bool | None = ..., + sock: socket | None = ..., + ) -> tuple[BaseTransport, _ProtocolT]: ... # Pipes and subprocesses. - async def connect_read_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... - async def connect_write_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... + async def connect_read_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[BaseTransport, _ProtocolT]: ... + async def connect_write_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[BaseTransport, _ProtocolT]: ... async def subprocess_shell( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], cmd: bytes | str, *, stdin: int | IO[Any] | None = ..., @@ -317,10 +336,10 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): errors: None = ..., text: Literal[False, None] = ..., **kwargs: Any, - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... async def subprocess_exec( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], program: Any, *args: Any, stdin: int | IO[Any] | None = ..., @@ -332,7 +351,7 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): encoding: None = ..., errors: None = ..., **kwargs: Any, - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... def add_reader(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... def remove_reader(self, fd: FileDescriptorLike) -> None: ... def add_writer(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi index 23034790a4a9..94c7c01dd1bc 100644 --- a/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi @@ -1,6 +1,6 @@ import subprocess from collections import deque -from typing import IO, Any, Callable, Optional, Sequence, Tuple, Union +from typing import IO, Any, Callable, Optional, Sequence, Union from . import events, futures, protocols, transports @@ -15,7 +15,7 @@ class BaseSubprocessTransport(transports.SubprocessTransport): _pid: int | None # undocumented _returncode: int | None # undocumented _exit_waiters: list[futures.Future[Any]] # undocumented - _pending_calls: deque[tuple[Callable[..., Any], Tuple[Any, ...]]] # undocumented + _pending_calls: deque[tuple[Callable[..., Any], tuple[Any, ...]]] # undocumented _pipes: dict[int, _File] # undocumented _finished: bool # undocumented def __init__( @@ -46,11 +46,11 @@ class BaseSubprocessTransport(transports.SubprocessTransport): def get_protocol(self) -> protocols.BaseProtocol: ... def is_closing(self) -> bool: ... def close(self) -> None: ... - def get_pid(self) -> int | None: ... # type: ignore + def get_pid(self) -> int | None: ... # type: ignore[override] def get_returncode(self) -> int | None: ... - def get_pipe_transport(self, fd: int) -> _File: ... # type: ignore + def get_pipe_transport(self, fd: int) -> _File: ... # type: ignore[override] def _check_proc(self) -> None: ... # undocumented - def send_signal(self, signal: int) -> None: ... # type: ignore + def send_signal(self, signal: int) -> None: ... # type: ignore[override] def terminate(self) -> None: ... def kill(self) -> None: ... async def _connect_pipes(self, waiter: futures.Future[Any] | None) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/asyncio/compat.pyi b/mypy/typeshed/stdlib/asyncio/compat.pyi index 1beeea9d6c3f..f6f1bbca7faf 100644 --- a/mypy/typeshed/stdlib/asyncio/compat.pyi +++ b/mypy/typeshed/stdlib/asyncio/compat.pyi @@ -1,7 +1,5 @@ -import sys +PY34: bool +PY35: bool +PY352: bool -if sys.version_info < (3, 7): - PY34: bool - PY35: bool - PY352: bool - def flatten_list_bytes(list_of_data: list[bytes]) -> bytes: ... +def flatten_list_bytes(list_of_data: list[bytes]) -> bytes: ... diff --git a/mypy/typeshed/stdlib/asyncio/constants.pyi b/mypy/typeshed/stdlib/asyncio/constants.pyi index 2010fe9123ae..230cf4faf483 100644 --- a/mypy/typeshed/stdlib/asyncio/constants.pyi +++ b/mypy/typeshed/stdlib/asyncio/constants.pyi @@ -1,12 +1,13 @@ import enum import sys +from typing_extensions import Literal -LOG_THRESHOLD_FOR_CONNLOST_WRITES: int -ACCEPT_RETRY_DELAY: int -DEBUG_STACK_DEPTH: int +LOG_THRESHOLD_FOR_CONNLOST_WRITES: Literal[5] +ACCEPT_RETRY_DELAY: Literal[1] +DEBUG_STACK_DEPTH: Literal[10] if sys.version_info >= (3, 7): SSL_HANDSHAKE_TIMEOUT: float - SENDFILE_FALLBACK_READBUFFER_SIZE: int + SENDFILE_FALLBACK_READBUFFER_SIZE: Literal[262144] class _SendfileMode(enum.Enum): UNSUPPORTED: int diff --git a/mypy/typeshed/stdlib/asyncio/coroutines.pyi b/mypy/typeshed/stdlib/asyncio/coroutines.pyi index df94d5ba156a..6c2d8179d1f1 100644 --- a/mypy/typeshed/stdlib/asyncio/coroutines.pyi +++ b/mypy/typeshed/stdlib/asyncio/coroutines.pyi @@ -1,16 +1,20 @@ import sys import types -from collections.abc import Callable, Coroutine -from typing import Any, TypeVar +from collections.abc import Coroutine +from typing import Any from typing_extensions import TypeGuard -_F = TypeVar("_F", bound=Callable[..., Any]) +if sys.version_info < (3, 11): + from collections.abc import Callable + from typing import TypeVar + + _F = TypeVar("_F", bound=Callable[..., Any]) + def coroutine(func: _F) -> _F: ... -def coroutine(func: _F) -> _F: ... def iscoroutinefunction(func: object) -> bool: ... -if sys.version_info < (3, 8): - def iscoroutine(obj: object) -> TypeGuard[types.GeneratorType[Any, Any, Any] | Coroutine[Any, Any, Any]]: ... +if sys.version_info >= (3, 8): + def iscoroutine(obj: object) -> TypeGuard[Coroutine[Any, Any, Any]]: ... else: - def iscoroutine(obj: object) -> TypeGuard[Coroutine[Any, Any, Any]]: ... + def iscoroutine(obj: object) -> TypeGuard[types.GeneratorType[Any, Any, Any] | Coroutine[Any, Any, Any]]: ... diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index 6ef9117b6491..a2b6b8a77fc9 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -3,7 +3,7 @@ import sys from _typeshed import FileDescriptorLike, Self from abc import ABCMeta, abstractmethod from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket -from typing import IO, Any, Awaitable, Callable, Dict, Generator, Sequence, Tuple, TypeVar, Union, overload +from typing import IO, Any, Awaitable, Callable, Generator, Sequence, TypeVar, Union, overload from typing_extensions import Literal from .base_events import Server @@ -17,14 +17,14 @@ if sys.version_info >= (3, 7): from contextvars import Context _T = TypeVar("_T") -_Context = Dict[str, Any] +_ProtocolT = TypeVar("_ProtocolT", bound=BaseProtocol) +_Context = dict[str, Any] _ExceptionHandler = Callable[[AbstractEventLoop, _Context], Any] _ProtocolFactory = Callable[[], BaseProtocol] _SSLContext = Union[bool, None, ssl.SSLContext] -_TransProtPair = Tuple[BaseTransport, BaseProtocol] class Handle: - _cancelled = False + _cancelled: bool _args: Sequence[Any] if sys.version_info >= (3, 7): def __init__( @@ -32,7 +32,6 @@ class Handle: ) -> None: ... else: def __init__(self, callback: Callable[..., Any], args: Sequence[Any], loop: AbstractEventLoop) -> None: ... - def __repr__(self) -> str: ... def cancel(self) -> None: ... def _run(self) -> None: ... if sys.version_info >= (3, 7): @@ -128,7 +127,7 @@ class AbstractEventLoop(metaclass=ABCMeta): @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, @@ -142,12 +141,12 @@ class AbstractEventLoop(metaclass=ABCMeta): ssl_handshake_timeout: float | None = ..., happy_eyeballs_delay: float | None = ..., interleave: int | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... @overload @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: None = ..., port: None = ..., *, @@ -161,13 +160,13 @@ class AbstractEventLoop(metaclass=ABCMeta): ssl_handshake_timeout: float | None = ..., happy_eyeballs_delay: float | None = ..., interleave: int | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... elif sys.version_info >= (3, 7): @overload @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, @@ -179,12 +178,12 @@ class AbstractEventLoop(metaclass=ABCMeta): local_addr: tuple[str, int] | None = ..., server_hostname: str | None = ..., ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... @overload @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: None = ..., port: None = ..., *, @@ -196,13 +195,13 @@ class AbstractEventLoop(metaclass=ABCMeta): local_addr: None = ..., server_hostname: str | None = ..., ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... else: @overload @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: str = ..., port: int = ..., *, @@ -213,12 +212,12 @@ class AbstractEventLoop(metaclass=ABCMeta): sock: None = ..., local_addr: tuple[str, int] | None = ..., server_hostname: str | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... @overload @abstractmethod async def create_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], host: None = ..., port: None = ..., *, @@ -229,7 +228,7 @@ class AbstractEventLoop(metaclass=ABCMeta): sock: socket, local_addr: None = ..., server_hostname: str | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... if sys.version_info >= (3, 7): @abstractmethod async def sock_sendfile( @@ -273,14 +272,14 @@ class AbstractEventLoop(metaclass=ABCMeta): ) -> Server: ... async def create_unix_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], path: str | None = ..., *, ssl: _SSLContext = ..., sock: socket | None = ..., server_hostname: str | None = ..., ssl_handshake_timeout: float | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... async def create_unix_server( self, protocol_factory: _ProtocolFactory, @@ -342,13 +341,13 @@ class AbstractEventLoop(metaclass=ABCMeta): ) -> Server: ... async def create_unix_connection( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], path: str, *, ssl: _SSLContext = ..., sock: socket | None = ..., server_hostname: str | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... async def create_unix_server( self, protocol_factory: _ProtocolFactory, @@ -361,7 +360,7 @@ class AbstractEventLoop(metaclass=ABCMeta): @abstractmethod async def create_datagram_endpoint( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], local_addr: tuple[str, int] | None = ..., remote_addr: tuple[str, int] | None = ..., *, @@ -372,16 +371,20 @@ class AbstractEventLoop(metaclass=ABCMeta): reuse_port: bool | None = ..., allow_broadcast: bool | None = ..., sock: socket | None = ..., - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... # Pipes and subprocesses. @abstractmethod - async def connect_read_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... + async def connect_read_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[BaseTransport, _ProtocolT]: ... @abstractmethod - async def connect_write_pipe(self, protocol_factory: _ProtocolFactory, pipe: Any) -> _TransProtPair: ... + async def connect_write_pipe( + self, protocol_factory: Callable[[], _ProtocolT], pipe: Any + ) -> tuple[BaseTransport, _ProtocolT]: ... @abstractmethod async def subprocess_shell( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], cmd: bytes | str, *, stdin: int | IO[Any] | None = ..., @@ -394,11 +397,11 @@ class AbstractEventLoop(metaclass=ABCMeta): errors: None = ..., text: Literal[False, None] = ..., **kwargs: Any, - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... @abstractmethod async def subprocess_exec( self, - protocol_factory: _ProtocolFactory, + protocol_factory: Callable[[], _ProtocolT], program: Any, *args: Any, stdin: int | IO[Any] | None = ..., @@ -410,7 +413,7 @@ class AbstractEventLoop(metaclass=ABCMeta): encoding: None = ..., errors: None = ..., **kwargs: Any, - ) -> _TransProtPair: ... + ) -> tuple[BaseTransport, _ProtocolT]: ... @abstractmethod def add_reader(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... @abstractmethod diff --git a/mypy/typeshed/stdlib/asyncio/exceptions.pyi b/mypy/typeshed/stdlib/asyncio/exceptions.pyi index 5b99966329ac..aec2e1685a3e 100644 --- a/mypy/typeshed/stdlib/asyncio/exceptions.pyi +++ b/mypy/typeshed/stdlib/asyncio/exceptions.pyi @@ -1,14 +1,13 @@ -import sys +class CancelledError(BaseException): ... +class TimeoutError(Exception): ... +class InvalidStateError(Exception): ... +class SendfileNotAvailableError(RuntimeError): ... -if sys.version_info >= (3, 8): - class CancelledError(BaseException): ... - class TimeoutError(Exception): ... - class InvalidStateError(Exception): ... - class SendfileNotAvailableError(RuntimeError): ... - class IncompleteReadError(EOFError): - expected: int | None - partial: bytes - def __init__(self, partial: bytes, expected: int | None) -> None: ... - class LimitOverrunError(Exception): - consumed: int - def __init__(self, message: str, consumed: int) -> None: ... +class IncompleteReadError(EOFError): + expected: int | None + partial: bytes + def __init__(self, partial: bytes, expected: int | None) -> None: ... + +class LimitOverrunError(Exception): + consumed: int + def __init__(self, message: str, consumed: int) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/format_helpers.pyi b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi index be80efe266b1..bf4412264ced 100644 --- a/mypy/typeshed/stdlib/asyncio/format_helpers.pyi +++ b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi @@ -1,5 +1,4 @@ import functools -import sys import traceback from types import FrameType, FunctionType from typing import Any, Iterable, Union, overload @@ -9,12 +8,11 @@ class _HasWrapper: _FuncType = Union[FunctionType, _HasWrapper, functools.partial[Any], functools.partialmethod[Any]] -if sys.version_info >= (3, 7): - @overload - def _get_function_source(func: _FuncType) -> tuple[str, int]: ... - @overload - def _get_function_source(func: object) -> tuple[str, int] | None: ... - def _format_callback_source(func: object, args: Iterable[Any]) -> str: ... - def _format_args_and_kwargs(args: Iterable[Any], kwargs: dict[str, Any]) -> str: ... - def _format_callback(func: object, args: Iterable[Any], kwargs: dict[str, Any], suffix: str = ...) -> str: ... - def extract_stack(f: FrameType | None = ..., limit: int | None = ...) -> traceback.StackSummary: ... +@overload +def _get_function_source(func: _FuncType) -> tuple[str, int]: ... +@overload +def _get_function_source(func: object) -> tuple[str, int] | None: ... +def _format_callback_source(func: object, args: Iterable[Any]) -> str: ... +def _format_args_and_kwargs(args: Iterable[Any], kwargs: dict[str, Any]) -> str: ... +def _format_callback(func: object, args: Iterable[Any], kwargs: dict[str, Any], suffix: str = ...) -> str: ... +def extract_stack(f: FrameType | None = ..., limit: int | None = ...) -> traceback.StackSummary: ... diff --git a/mypy/typeshed/stdlib/asyncio/futures.pyi b/mypy/typeshed/stdlib/asyncio/futures.pyi index 9788123f427e..3ec16f28850e 100644 --- a/mypy/typeshed/stdlib/asyncio/futures.pyi +++ b/mypy/typeshed/stdlib/asyncio/futures.pyi @@ -34,7 +34,6 @@ class Future(Awaitable[_T], Iterable[_T]): _blocking = False _log_traceback = False def __init__(self, *, loop: AbstractEventLoop | None = ...) -> None: ... - def __repr__(self) -> str: ... def __del__(self) -> None: ... if sys.version_info >= (3, 7): def get_loop(self) -> AbstractEventLoop: ... diff --git a/mypy/typeshed/stdlib/asyncio/locks.pyi b/mypy/typeshed/stdlib/asyncio/locks.pyi index 7c4f40d9e4ca..fa1b9235ae29 100644 --- a/mypy/typeshed/stdlib/asyncio/locks.pyi +++ b/mypy/typeshed/stdlib/asyncio/locks.pyi @@ -1,7 +1,7 @@ import sys from collections import deque from types import TracebackType -from typing import Any, Awaitable, Callable, Generator, Type, TypeVar +from typing import Any, Awaitable, Callable, Generator, TypeVar from .events import AbstractEventLoop from .futures import Future @@ -13,7 +13,7 @@ if sys.version_info >= (3, 9): def __init__(self, lock: Lock | Semaphore) -> None: ... def __aenter__(self) -> Awaitable[None]: ... def __aexit__( - self, exc_type: Type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None ) -> Awaitable[None]: ... else: @@ -30,7 +30,7 @@ else: def __await__(self) -> Generator[Any, None, _ContextManager]: ... def __aenter__(self) -> Awaitable[None]: ... def __aexit__( - self, exc_type: Type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None ) -> Awaitable[None]: ... class Lock(_ContextManagerMixin): diff --git a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi index 6c8c558e5dfa..64c65d847fcf 100644 --- a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi @@ -1,14 +1,14 @@ import sys from socket import socket -from typing import Any, Mapping, Type -from typing_extensions import Literal, Protocol +from typing import Any, Mapping, Protocol +from typing_extensions import Literal from . import base_events, constants, events, futures, streams, transports if sys.version_info >= (3, 8): class _WarnCallbackProtocol(Protocol): def __call__( - self, message: str, category: Type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ... + self, message: str, category: type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ... ) -> None: ... class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTransport): @@ -21,7 +21,6 @@ class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTr extra: Mapping[Any, Any] | None = ..., server: events.AbstractServer | None = ..., ) -> None: ... - def __repr__(self) -> str: ... if sys.version_info >= (3, 8): def __del__(self, _warn: _WarnCallbackProtocol = ...) -> None: ... else: diff --git a/mypy/typeshed/stdlib/asyncio/queues.pyi b/mypy/typeshed/stdlib/asyncio/queues.pyi index aff4af727b08..994268f54f0a 100644 --- a/mypy/typeshed/stdlib/asyncio/queues.pyi +++ b/mypy/typeshed/stdlib/asyncio/queues.pyi @@ -15,8 +15,6 @@ class Queue(Generic[_T]): def _init(self, maxsize: int) -> None: ... def _get(self) -> _T: ... def _put(self, item: _T) -> None: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... def _format(self) -> str: ... def qsize(self) -> int: ... @property diff --git a/mypy/typeshed/stdlib/asyncio/runners.pyi b/mypy/typeshed/stdlib/asyncio/runners.pyi index 3f0f42eef48b..b32550b06e84 100644 --- a/mypy/typeshed/stdlib/asyncio/runners.pyi +++ b/mypy/typeshed/stdlib/asyncio/runners.pyi @@ -1,10 +1,9 @@ import sys +from typing import Awaitable, TypeVar -if sys.version_info >= (3, 7): - from typing import Awaitable, TypeVar +_T = TypeVar("_T") +if sys.version_info >= (3, 8): + def run(main: Awaitable[_T], *, debug: bool | None = ...) -> _T: ... - _T = TypeVar("_T") - if sys.version_info >= (3, 8): - def run(main: Awaitable[_T], *, debug: bool | None = ...) -> _T: ... - else: - def run(main: Awaitable[_T], *, debug: bool = ...) -> _T: ... +else: + def run(main: Awaitable[_T], *, debug: bool = ...) -> _T: ... diff --git a/mypy/typeshed/stdlib/asyncio/staggered.pyi b/mypy/typeshed/stdlib/asyncio/staggered.pyi index 1d76d382555d..d5b9156a1e3b 100644 --- a/mypy/typeshed/stdlib/asyncio/staggered.pyi +++ b/mypy/typeshed/stdlib/asyncio/staggered.pyi @@ -1,9 +1,7 @@ -import sys from typing import Any, Awaitable, Callable, Iterable from . import events -if sys.version_info >= (3, 8): - async def staggered_race( - coro_fns: Iterable[Callable[[], Awaitable[Any]]], delay: float | None, *, loop: events.AbstractEventLoop | None = ... - ) -> tuple[Any, int | None, list[Exception | None]]: ... +async def staggered_race( + coro_fns: Iterable[Callable[[], Awaitable[Any]]], delay: float | None, *, loop: events.AbstractEventLoop | None = ... +) -> tuple[Any, int | None, list[Exception | None]]: ... diff --git a/mypy/typeshed/stdlib/asyncio/streams.pyi b/mypy/typeshed/stdlib/asyncio/streams.pyi index 595222280d58..6dae893e3b97 100644 --- a/mypy/typeshed/stdlib/asyncio/streams.pyi +++ b/mypy/typeshed/stdlib/asyncio/streams.pyi @@ -16,43 +16,71 @@ if sys.version_info < (3, 8): consumed: int def __init__(self, message: str, consumed: int) -> None: ... -async def open_connection( - host: str | None = ..., - port: int | str | None = ..., - *, - loop: events.AbstractEventLoop | None = ..., - limit: int = ..., - ssl_handshake_timeout: float | None = ..., - **kwds: Any, -) -> tuple[StreamReader, StreamWriter]: ... -async def start_server( - client_connected_cb: _ClientConnectedCallback, - host: str | None = ..., - port: int | str | None = ..., - *, - loop: events.AbstractEventLoop | None = ..., - limit: int = ..., - ssl_handshake_timeout: float | None = ..., - **kwds: Any, -) -> Server: ... +if sys.version_info >= (3, 10): + async def open_connection( + host: str | None = ..., + port: int | str | None = ..., + *, + limit: int = ..., + ssl_handshake_timeout: float | None = ..., + **kwds: Any, + ) -> tuple[StreamReader, StreamWriter]: ... + async def start_server( + client_connected_cb: _ClientConnectedCallback, + host: str | None = ..., + port: int | str | None = ..., + *, + limit: int = ..., + ssl_handshake_timeout: float | None = ..., + **kwds: Any, + ) -> Server: ... -if sys.platform != "win32": - if sys.version_info >= (3, 7): - _PathType = StrPath - else: - _PathType = str - async def open_unix_connection( - path: _PathType | None = ..., *, loop: events.AbstractEventLoop | None = ..., limit: int = ..., **kwds: Any +else: + async def open_connection( + host: str | None = ..., + port: int | str | None = ..., + *, + loop: events.AbstractEventLoop | None = ..., + limit: int = ..., + ssl_handshake_timeout: float | None = ..., + **kwds: Any, ) -> tuple[StreamReader, StreamWriter]: ... - async def start_unix_server( + async def start_server( client_connected_cb: _ClientConnectedCallback, - path: _PathType | None = ..., + host: str | None = ..., + port: int | str | None = ..., *, loop: events.AbstractEventLoop | None = ..., limit: int = ..., + ssl_handshake_timeout: float | None = ..., **kwds: Any, ) -> Server: ... +if sys.platform != "win32": + if sys.version_info >= (3, 7): + _PathType = StrPath + else: + _PathType = str + if sys.version_info >= (3, 10): + async def open_unix_connection( + path: _PathType | None = ..., *, limit: int = ..., **kwds: Any + ) -> tuple[StreamReader, StreamWriter]: ... + async def start_unix_server( + client_connected_cb: _ClientConnectedCallback, path: _PathType | None = ..., *, limit: int = ..., **kwds: Any + ) -> Server: ... + else: + async def open_unix_connection( + path: _PathType | None = ..., *, loop: events.AbstractEventLoop | None = ..., limit: int = ..., **kwds: Any + ) -> tuple[StreamReader, StreamWriter]: ... + async def start_unix_server( + client_connected_cb: _ClientConnectedCallback, + path: _PathType | None = ..., + *, + loop: events.AbstractEventLoop | None = ..., + limit: int = ..., + **kwds: Any, + ) -> Server: ... + class FlowControlMixin(protocols.Protocol): def __init__(self, loop: events.AbstractEventLoop | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index 15c12909f3c3..c1c073895650 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -21,9 +21,9 @@ _FT = TypeVar("_FT", bound=Future[Any]) _FutureT = Union[Future[_T], Generator[Any, None, _T], Awaitable[_T]] _TaskYieldType = Optional[Future[object]] -FIRST_EXCEPTION: str -FIRST_COMPLETED: str -ALL_COMPLETED: str +FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED +FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION +ALL_COMPLETED = concurrent.futures.ALL_COMPLETED if sys.version_info >= (3, 10): def as_completed(fs: Iterable[_FutureT[_T]], *, timeout: float | None = ...) -> Iterator[Future[_T]]: ... @@ -34,7 +34,7 @@ else: ) -> Iterator[Future[_T]]: ... @overload -def ensure_future(coro_or_future: _FT, *, loop: AbstractEventLoop | None = ...) -> _FT: ... # type: ignore +def ensure_future(coro_or_future: _FT, *, loop: AbstractEventLoop | None = ...) -> _FT: ... # type: ignore[misc] @overload def ensure_future(coro_or_future: Awaitable[_T], *, loop: AbstractEventLoop | None = ...) -> Task[_T]: ... @@ -47,79 +47,79 @@ def ensure_future(coro_or_future: Awaitable[_T], *, loop: AbstractEventLoop | No # typing PR #1550 for discussion. if sys.version_info >= (3, 10): @overload - def gather(coro_or_future1: _FutureT[_T1], *, return_exceptions: Literal[False] = ...) -> Future[tuple[_T1]]: ... + def gather(__coro_or_future1: _FutureT[_T1], *, return_exceptions: Literal[False] = ...) -> Future[tuple[_T1]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, return_exceptions: Literal[False] = ... + __coro_or_future1: _FutureT[_T1], __coro_or_future2: _FutureT[_T2], *, return_exceptions: Literal[False] = ... ) -> Future[tuple[_T1, _T2]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], *, return_exceptions: Literal[False] = ..., ) -> Future[tuple[_T1, _T2, _T3]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], + __coro_or_future4: _FutureT[_T4], *, return_exceptions: Literal[False] = ..., ) -> Future[tuple[_T1, _T2, _T3, _T4]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], - coro_or_future5: _FutureT[_T5], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], + __coro_or_future4: _FutureT[_T4], + __coro_or_future5: _FutureT[_T5], *, return_exceptions: Literal[False] = ..., ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def gather( - coro_or_future1: _FutureT[Any], - coro_or_future2: _FutureT[Any], - coro_or_future3: _FutureT[Any], - coro_or_future4: _FutureT[Any], - coro_or_future5: _FutureT[Any], - coro_or_future6: _FutureT[Any], + __coro_or_future1: _FutureT[Any], + __coro_or_future2: _FutureT[Any], + __coro_or_future3: _FutureT[Any], + __coro_or_future4: _FutureT[Any], + __coro_or_future5: _FutureT[Any], + __coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], return_exceptions: bool = ..., ) -> Future[list[Any]]: ... @overload - def gather(coro_or_future1: _FutureT[_T1], *, return_exceptions: bool = ...) -> Future[tuple[_T1 | BaseException]]: ... + def gather(__coro_or_future1: _FutureT[_T1], *, return_exceptions: bool = ...) -> Future[tuple[_T1 | BaseException]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], coro_or_future2: _FutureT[_T2], *, return_exceptions: bool = ... + __coro_or_future1: _FutureT[_T1], __coro_or_future2: _FutureT[_T2], *, return_exceptions: bool = ... ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], *, return_exceptions: bool = ..., ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], + __coro_or_future4: _FutureT[_T4], *, return_exceptions: bool = ..., ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], - coro_or_future5: _FutureT[_T5], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], + __coro_or_future4: _FutureT[_T4], + __coro_or_future5: _FutureT[_T5], *, return_exceptions: bool = ..., ) -> Future[ @@ -129,96 +129,96 @@ if sys.version_info >= (3, 10): else: @overload def gather( - coro_or_future1: _FutureT[_T1], *, loop: AbstractEventLoop | None = ..., return_exceptions: Literal[False] = ... + __coro_or_future1: _FutureT[_T1], *, loop: AbstractEventLoop | None = ..., return_exceptions: Literal[False] = ... ) -> Future[tuple[_T1]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], *, loop: AbstractEventLoop | None = ..., return_exceptions: Literal[False] = ..., ) -> Future[tuple[_T1, _T2]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], *, loop: AbstractEventLoop | None = ..., return_exceptions: Literal[False] = ..., ) -> Future[tuple[_T1, _T2, _T3]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], + __coro_or_future4: _FutureT[_T4], *, loop: AbstractEventLoop | None = ..., return_exceptions: Literal[False] = ..., ) -> Future[tuple[_T1, _T2, _T3, _T4]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], - coro_or_future5: _FutureT[_T5], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], + __coro_or_future4: _FutureT[_T4], + __coro_or_future5: _FutureT[_T5], *, loop: AbstractEventLoop | None = ..., return_exceptions: Literal[False] = ..., ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5]]: ... @overload def gather( - coro_or_future1: _FutureT[Any], - coro_or_future2: _FutureT[Any], - coro_or_future3: _FutureT[Any], - coro_or_future4: _FutureT[Any], - coro_or_future5: _FutureT[Any], - coro_or_future6: _FutureT[Any], + __coro_or_future1: _FutureT[Any], + __coro_or_future2: _FutureT[Any], + __coro_or_future3: _FutureT[Any], + __coro_or_future4: _FutureT[Any], + __coro_or_future5: _FutureT[Any], + __coro_or_future6: _FutureT[Any], *coros_or_futures: _FutureT[Any], loop: AbstractEventLoop | None = ..., return_exceptions: bool = ..., ) -> Future[list[Any]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], *, loop: AbstractEventLoop | None = ..., return_exceptions: bool = ... + __coro_or_future1: _FutureT[_T1], *, loop: AbstractEventLoop | None = ..., return_exceptions: bool = ... ) -> Future[tuple[_T1 | BaseException]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], *, loop: AbstractEventLoop | None = ..., return_exceptions: bool = ..., ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], *, loop: AbstractEventLoop | None = ..., return_exceptions: bool = ..., ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], + __coro_or_future4: _FutureT[_T4], *, loop: AbstractEventLoop | None = ..., return_exceptions: bool = ..., ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException]]: ... @overload def gather( - coro_or_future1: _FutureT[_T1], - coro_or_future2: _FutureT[_T2], - coro_or_future3: _FutureT[_T3], - coro_or_future4: _FutureT[_T4], - coro_or_future5: _FutureT[_T5], + __coro_or_future1: _FutureT[_T1], + __coro_or_future2: _FutureT[_T2], + __coro_or_future3: _FutureT[_T3], + __coro_or_future4: _FutureT[_T4], + __coro_or_future5: _FutureT[_T5], *, loop: AbstractEventLoop | None = ..., return_exceptions: bool = ..., @@ -230,25 +230,27 @@ def run_coroutine_threadsafe(coro: _FutureT[_T], loop: AbstractEventLoop) -> con if sys.version_info >= (3, 10): def shield(arg: _FutureT[_T]) -> Future[_T]: ... - def sleep(delay: float, result: _T = ...) -> Future[_T]: ... + async def sleep(delay: float, result: _T = ...) -> _T: ... @overload - def wait(fs: Iterable[_FT], *, timeout: float | None = ..., return_when: str = ...) -> Future[tuple[set[_FT], set[_FT]]]: ... # type: ignore + async def wait(fs: Iterable[_FT], *, timeout: float | None = ..., return_when: str = ...) -> tuple[set[_FT], set[_FT]]: ... # type: ignore[misc] @overload - def wait( + async def wait( fs: Iterable[Awaitable[_T]], *, timeout: float | None = ..., return_when: str = ... - ) -> Future[tuple[set[Task[_T]], set[Task[_T]]]]: ... - def wait_for(fut: _FutureT[_T], timeout: float | None) -> Future[_T]: ... + ) -> tuple[set[Task[_T]], set[Task[_T]]]: ... + async def wait_for(fut: _FutureT[_T], timeout: float | None) -> _T: ... else: def shield(arg: _FutureT[_T], *, loop: AbstractEventLoop | None = ...) -> Future[_T]: ... - def sleep(delay: float, result: _T = ..., *, loop: AbstractEventLoop | None = ...) -> Future[_T]: ... + async def sleep(delay: float, result: _T = ..., *, loop: AbstractEventLoop | None = ...) -> _T: ... @overload - def wait(fs: Iterable[_FT], *, loop: AbstractEventLoop | None = ..., timeout: float | None = ..., return_when: str = ...) -> Future[tuple[set[_FT], set[_FT]]]: ... # type: ignore + async def wait( # type: ignore[misc] + fs: Iterable[_FT], *, loop: AbstractEventLoop | None = ..., timeout: float | None = ..., return_when: str = ... + ) -> tuple[set[_FT], set[_FT]]: ... @overload - def wait( + async def wait( fs: Iterable[Awaitable[_T]], *, loop: AbstractEventLoop | None = ..., timeout: float | None = ..., return_when: str = ... - ) -> Future[tuple[set[Task[_T]], set[Task[_T]]]]: ... - def wait_for(fut: _FutureT[_T], timeout: float | None, *, loop: AbstractEventLoop | None = ...) -> Future[_T]: ... + ) -> tuple[set[Task[_T]], set[Task[_T]]]: ... + async def wait_for(fut: _FutureT[_T], timeout: float | None, *, loop: AbstractEventLoop | None = ...) -> _T: ... class Task(Future[_T], Generic[_T]): if sys.version_info >= (3, 8): @@ -263,7 +265,6 @@ class Task(Future[_T], Generic[_T]): def __init__( self, coro: Generator[_TaskYieldType, None, _T] | Awaitable[_T], *, loop: AbstractEventLoop = ... ) -> None: ... - def __repr__(self) -> str: ... if sys.version_info >= (3, 8): def get_coro(self) -> Generator[_TaskYieldType, None, _T] | Awaitable[_T]: ... def get_name(self) -> str: ... @@ -291,3 +292,7 @@ if sys.version_info >= (3, 7): else: def create_task(coro: Generator[_TaskYieldType, None, _T] | Awaitable[_T]) -> Task[_T]: ... def current_task(loop: AbstractEventLoop | None = ...) -> Task[Any] | None: ... + def _enter_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ... + def _leave_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ... + def _register_task(task: Task[Any]) -> None: ... + def _unregister_task(task: Task[Any]) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/threads.pyi b/mypy/typeshed/stdlib/asyncio/threads.pyi index 3f798d8ac862..dbb15bb8f400 100644 --- a/mypy/typeshed/stdlib/asyncio/threads.pyi +++ b/mypy/typeshed/stdlib/asyncio/threads.pyi @@ -1,7 +1,7 @@ -import sys -from typing import Any, Callable, TypeVar +from typing import Callable, TypeVar +from typing_extensions import ParamSpec -_T = TypeVar("_T") +_P = ParamSpec("_P") +_R = TypeVar("_R") -if sys.version_info >= (3, 9): - async def to_thread(__func: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: ... +async def to_thread(__func: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R: ... diff --git a/mypy/typeshed/stdlib/asyncio/trsock.pyi b/mypy/typeshed/stdlib/asyncio/trsock.pyi index 33ec5d67aaf9..6d4b7378b9d0 100644 --- a/mypy/typeshed/stdlib/asyncio/trsock.pyi +++ b/mypy/typeshed/stdlib/asyncio/trsock.pyi @@ -1,86 +1,87 @@ import socket import sys +from builtins import type as Type # alias to avoid name clashes with property named "type" from types import TracebackType -from typing import Any, BinaryIO, Iterable, NoReturn, Tuple, Type, Union, overload +from typing import Any, BinaryIO, Iterable, NoReturn, Union, overload -if sys.version_info >= (3, 8): - # These are based in socket, maybe move them out into _typeshed.pyi or such - _Address = Union[Tuple[Any, ...], str] - _RetAddress = Any - _WriteBuffer = Union[bytearray, memoryview] - _CMSG = Tuple[int, int, bytes] - class TransportSocket: - def __init__(self, sock: socket.socket) -> None: ... - def _na(self, what: str) -> None: ... - @property - def family(self) -> int: ... - @property - def type(self) -> int: ... - @property - def proto(self) -> int: ... - def __getstate__(self) -> NoReturn: ... - def fileno(self) -> int: ... - def dup(self) -> socket.socket: ... - def get_inheritable(self) -> bool: ... - def shutdown(self, how: int) -> None: ... - @overload - def getsockopt(self, level: int, optname: int) -> int: ... - @overload - def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... - @overload - def setsockopt(self, level: int, optname: int, value: int | bytes) -> None: ... - @overload - def setsockopt(self, level: int, optname: int, value: None, optlen: int) -> None: ... - def getpeername(self) -> _RetAddress: ... - def getsockname(self) -> _RetAddress: ... - def getsockbyname(self) -> NoReturn: ... # This method doesn't exist on socket, yet is passed through? - def accept(self) -> tuple[socket.socket, _RetAddress]: ... - def connect(self, address: _Address | bytes) -> None: ... - def connect_ex(self, address: _Address | bytes) -> int: ... - def bind(self, address: _Address | bytes) -> None: ... - if sys.platform == "win32": - def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> None: ... - else: - def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> NoReturn: ... - def listen(self, __backlog: int = ...) -> None: ... - def makefile(self) -> BinaryIO: ... - def sendfile(self, file: BinaryIO, offset: int = ..., count: int | None = ...) -> int: ... - def close(self) -> None: ... - def detach(self) -> int: ... - if sys.platform == "linux": - def sendmsg_afalg( - self, msg: Iterable[bytes] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... - ) -> int: ... - else: - def sendmsg_afalg( - self, msg: Iterable[bytes] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... - ) -> NoReturn: ... - def sendmsg( - self, __buffers: Iterable[bytes], __ancdata: Iterable[_CMSG] = ..., __flags: int = ..., __address: _Address = ... +# These are based in socket, maybe move them out into _typeshed.pyi or such +_Address = Union[tuple[Any, ...], str] +_RetAddress = Any +_WriteBuffer = Union[bytearray, memoryview] +_CMSG = tuple[int, int, bytes] + +class TransportSocket: + def __init__(self, sock: socket.socket) -> None: ... + def _na(self, what: str) -> None: ... + @property + def family(self) -> int: ... + @property + def type(self) -> int: ... + @property + def proto(self) -> int: ... + def __getstate__(self) -> NoReturn: ... + def fileno(self) -> int: ... + def dup(self) -> socket.socket: ... + def get_inheritable(self) -> bool: ... + def shutdown(self, how: int) -> None: ... + @overload + def getsockopt(self, level: int, optname: int) -> int: ... + @overload + def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ... + @overload + def setsockopt(self, level: int, optname: int, value: int | bytes) -> None: ... + @overload + def setsockopt(self, level: int, optname: int, value: None, optlen: int) -> None: ... + def getpeername(self) -> _RetAddress: ... + def getsockname(self) -> _RetAddress: ... + def getsockbyname(self) -> NoReturn: ... # This method doesn't exist on socket, yet is passed through? + def accept(self) -> tuple[socket.socket, _RetAddress]: ... + def connect(self, address: _Address | bytes) -> None: ... + def connect_ex(self, address: _Address | bytes) -> int: ... + def bind(self, address: _Address | bytes) -> None: ... + if sys.platform == "win32": + def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> None: ... + else: + def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> NoReturn: ... + def listen(self, __backlog: int = ...) -> None: ... + def makefile(self) -> BinaryIO: ... + def sendfile(self, file: BinaryIO, offset: int = ..., count: int | None = ...) -> int: ... + def close(self) -> None: ... + def detach(self) -> int: ... + if sys.platform == "linux": + def sendmsg_afalg( + self, msg: Iterable[bytes] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... ) -> int: ... - @overload - def sendto(self, data: bytes, address: _Address) -> int: ... - @overload - def sendto(self, data: bytes, flags: int, address: _Address) -> int: ... - def send(self, data: bytes, flags: int = ...) -> int: ... - def sendall(self, data: bytes, flags: int = ...) -> None: ... - def set_inheritable(self, inheritable: bool) -> None: ... - if sys.platform == "win32": - def share(self, process_id: int) -> bytes: ... - else: - def share(self, process_id: int) -> NoReturn: ... - def recv_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> int: ... - def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ... - def recvmsg_into( - self, __buffers: Iterable[_WriteBuffer], __ancbufsize: int = ..., __flags: int = ... - ) -> tuple[int, list[_CMSG], int, Any]: ... - def recvmsg(self, __bufsize: int, __ancbufsize: int = ..., __flags: int = ...) -> tuple[bytes, list[_CMSG], int, Any]: ... - def recvfrom(self, bufsize: int, flags: int = ...) -> tuple[bytes, _RetAddress]: ... - def recv(self, bufsize: int, flags: int = ...) -> bytes: ... - def settimeout(self, value: float | None) -> None: ... - def gettimeout(self) -> float | None: ... - def setblocking(self, flag: bool) -> None: ... - def __enter__(self) -> socket.socket: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> None: ... + else: + def sendmsg_afalg( + self, msg: Iterable[bytes] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = ... + ) -> NoReturn: ... + def sendmsg( + self, __buffers: Iterable[bytes], __ancdata: Iterable[_CMSG] = ..., __flags: int = ..., __address: _Address = ... + ) -> int: ... + @overload + def sendto(self, data: bytes, address: _Address) -> int: ... + @overload + def sendto(self, data: bytes, flags: int, address: _Address) -> int: ... + def send(self, data: bytes, flags: int = ...) -> int: ... + def sendall(self, data: bytes, flags: int = ...) -> None: ... + def set_inheritable(self, inheritable: bool) -> None: ... + if sys.platform == "win32": + def share(self, process_id: int) -> bytes: ... + else: + def share(self, process_id: int) -> NoReturn: ... + def recv_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> int: ... + def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = ..., flags: int = ...) -> tuple[int, _RetAddress]: ... + def recvmsg_into( + self, __buffers: Iterable[_WriteBuffer], __ancbufsize: int = ..., __flags: int = ... + ) -> tuple[int, list[_CMSG], int, Any]: ... + def recvmsg(self, __bufsize: int, __ancbufsize: int = ..., __flags: int = ...) -> tuple[bytes, list[_CMSG], int, Any]: ... + def recvfrom(self, bufsize: int, flags: int = ...) -> tuple[bytes, _RetAddress]: ... + def recv(self, bufsize: int, flags: int = ...) -> bytes: ... + def settimeout(self, value: float | None) -> None: ... + def gettimeout(self) -> float | None: ... + def setblocking(self, flag: bool) -> None: ... + def __enter__(self) -> socket.socket: ... + def __exit__( + self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/unix_events.pyi b/mypy/typeshed/stdlib/asyncio/unix_events.pyi index e8e57a20a765..d4c1c546d2fc 100644 --- a/mypy/typeshed/stdlib/asyncio/unix_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/unix_events.pyi @@ -2,60 +2,59 @@ import sys import types from _typeshed import Self from socket import socket -from typing import Any, Callable, Type +from typing import Any, Callable from .base_events import Server from .events import AbstractEventLoop, BaseDefaultEventLoopPolicy, _ProtocolFactory, _SSLContext from .selector_events import BaseSelectorEventLoop +# This is also technically not available on Win, +# but other parts of typeshed need this defintion. +# So, it is special cased. class AbstractChildWatcher: def add_child_handler(self, pid: int, callback: Callable[..., Any], *args: Any) -> None: ... def remove_child_handler(self, pid: int) -> bool: ... def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... def close(self) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... if sys.version_info >= (3, 8): def is_active(self) -> bool: ... -class BaseChildWatcher(AbstractChildWatcher): - def __init__(self) -> None: ... - -class SafeChildWatcher(BaseChildWatcher): - def __enter__(self: Self) -> Self: ... - -class FastChildWatcher(BaseChildWatcher): - def __enter__(self: Self) -> Self: ... - -class _UnixSelectorEventLoop(BaseSelectorEventLoop): - if sys.version_info < (3, 7): - async def create_unix_server( - self, - protocol_factory: _ProtocolFactory, - path: str | None = ..., - *, - sock: socket | None = ..., - backlog: int = ..., - ssl: _SSLContext = ..., - ) -> Server: ... - -class _UnixDefaultEventLoopPolicy(BaseDefaultEventLoopPolicy): - def get_child_watcher(self) -> AbstractChildWatcher: ... - def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ... - -SelectorEventLoop = _UnixSelectorEventLoop - -DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy - -if sys.version_info >= (3, 8): - - from typing import Protocol - class _Warn(Protocol): - def __call__( - self, message: str, category: Type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ... - ) -> None: ... - class MultiLoopChildWatcher(AbstractChildWatcher): +if sys.platform != "win32": + class BaseChildWatcher(AbstractChildWatcher): + def __init__(self) -> None: ... + class SafeChildWatcher(BaseChildWatcher): def __enter__(self: Self) -> Self: ... - class ThreadedChildWatcher(AbstractChildWatcher): + class FastChildWatcher(BaseChildWatcher): def __enter__(self: Self) -> Self: ... - def __del__(self, _warn: _Warn = ...) -> None: ... + class _UnixSelectorEventLoop(BaseSelectorEventLoop): + if sys.version_info < (3, 7): + async def create_unix_server( + self, + protocol_factory: _ProtocolFactory, + path: str | None = ..., + *, + sock: socket | None = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + ) -> Server: ... + class _UnixDefaultEventLoopPolicy(BaseDefaultEventLoopPolicy): + def get_child_watcher(self) -> AbstractChildWatcher: ... + def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ... + SelectorEventLoop = _UnixSelectorEventLoop + + DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy + + if sys.version_info >= (3, 8): + + from typing import Protocol + class _Warn(Protocol): + def __call__( + self, message: str, category: type[Warning] | None = ..., stacklevel: int = ..., source: Any | None = ... + ) -> None: ... + class MultiLoopChildWatcher(AbstractChildWatcher): + def __enter__(self: Self) -> Self: ... + class ThreadedChildWatcher(AbstractChildWatcher): + def __enter__(self: Self) -> Self: ... + def __del__(self, _warn: _Warn = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/windows_events.pyi b/mypy/typeshed/stdlib/asyncio/windows_events.pyi index f0a206a4e139..e43a0eda8083 100644 --- a/mypy/typeshed/stdlib/asyncio/windows_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/windows_events.pyi @@ -1,77 +1,76 @@ import socket import sys from _typeshed import WriteableBuffer -from typing import IO, Any, Callable, ClassVar, NoReturn, Type +from typing import IO, Any, Callable, ClassVar, NoReturn +from typing_extensions import Literal from . import events, futures, proactor_events, selector_events, streams, windows_utils -__all__ = [ - "SelectorEventLoop", - "ProactorEventLoop", - "IocpProactor", - "DefaultEventLoopPolicy", - "WindowsSelectorEventLoopPolicy", - "WindowsProactorEventLoopPolicy", -] - -NULL: int -INFINITE: int -ERROR_CONNECTION_REFUSED: int -ERROR_CONNECTION_ABORTED: int -CONNECT_PIPE_INIT_DELAY: float -CONNECT_PIPE_MAX_DELAY: float - -class PipeServer: - def __init__(self, address: str) -> None: ... - def __del__(self) -> None: ... - def closed(self) -> bool: ... - def close(self) -> None: ... - -class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop): ... - -class ProactorEventLoop(proactor_events.BaseProactorEventLoop): - def __init__(self, proactor: IocpProactor | None = ...) -> None: ... - async def create_pipe_connection( - self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str - ) -> tuple[proactor_events._ProactorDuplexPipeTransport, streams.StreamReaderProtocol]: ... - async def start_serving_pipe( - self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str - ) -> list[PipeServer]: ... - -class IocpProactor: - def __init__(self, concurrency: int = ...) -> None: ... - def __repr__(self) -> str: ... - def __del__(self) -> None: ... - def set_loop(self, loop: events.AbstractEventLoop) -> None: ... - def select(self, timeout: int | None = ...) -> list[futures.Future[Any]]: ... - def recv(self, conn: socket.socket, nbytes: int, flags: int = ...) -> futures.Future[bytes]: ... - if sys.version_info >= (3, 7): - def recv_into(self, conn: socket.socket, buf: WriteableBuffer, flags: int = ...) -> futures.Future[Any]: ... - def send(self, conn: socket.socket, buf: WriteableBuffer, flags: int = ...) -> futures.Future[Any]: ... - def accept(self, listener: socket.socket) -> futures.Future[Any]: ... - def connect(self, conn: socket.socket, address: bytes) -> futures.Future[Any]: ... +if sys.platform == "win32": if sys.version_info >= (3, 7): - def sendfile(self, sock: socket.socket, file: IO[bytes], offset: int, count: int) -> futures.Future[Any]: ... - def accept_pipe(self, pipe: socket.socket) -> futures.Future[Any]: ... - async def connect_pipe(self, address: bytes) -> windows_utils.PipeHandle: ... - def wait_for_handle(self, handle: windows_utils.PipeHandle, timeout: int | None = ...) -> bool: ... - def close(self) -> None: ... + __all__ = ( + "SelectorEventLoop", + "ProactorEventLoop", + "IocpProactor", + "DefaultEventLoopPolicy", + "WindowsSelectorEventLoopPolicy", + "WindowsProactorEventLoopPolicy", + ) + else: + __all__ = ["SelectorEventLoop", "ProactorEventLoop", "IocpProactor", "DefaultEventLoopPolicy"] -SelectorEventLoop = _WindowsSelectorEventLoop + NULL: Literal[0] + INFINITE: Literal[0xFFFFFFFF] + ERROR_CONNECTION_REFUSED: Literal[1225] + ERROR_CONNECTION_ABORTED: Literal[1236] + CONNECT_PIPE_INIT_DELAY: float + CONNECT_PIPE_MAX_DELAY: float + class PipeServer: + def __init__(self, address: str) -> None: ... + def __del__(self) -> None: ... + def closed(self) -> bool: ... + def close(self) -> None: ... + class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop): ... + class ProactorEventLoop(proactor_events.BaseProactorEventLoop): + def __init__(self, proactor: IocpProactor | None = ...) -> None: ... + async def create_pipe_connection( + self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str + ) -> tuple[proactor_events._ProactorDuplexPipeTransport, streams.StreamReaderProtocol]: ... + async def start_serving_pipe( + self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str + ) -> list[PipeServer]: ... + class IocpProactor: + def __init__(self, concurrency: int = ...) -> None: ... + def __del__(self) -> None: ... + def set_loop(self, loop: events.AbstractEventLoop) -> None: ... + def select(self, timeout: int | None = ...) -> list[futures.Future[Any]]: ... + def recv(self, conn: socket.socket, nbytes: int, flags: int = ...) -> futures.Future[bytes]: ... + if sys.version_info >= (3, 7): + def recv_into(self, conn: socket.socket, buf: WriteableBuffer, flags: int = ...) -> futures.Future[Any]: ... + def send(self, conn: socket.socket, buf: WriteableBuffer, flags: int = ...) -> futures.Future[Any]: ... + def accept(self, listener: socket.socket) -> futures.Future[Any]: ... + def connect(self, conn: socket.socket, address: bytes) -> futures.Future[Any]: ... + if sys.version_info >= (3, 7): + def sendfile(self, sock: socket.socket, file: IO[bytes], offset: int, count: int) -> futures.Future[Any]: ... + def accept_pipe(self, pipe: socket.socket) -> futures.Future[Any]: ... + async def connect_pipe(self, address: bytes) -> windows_utils.PipeHandle: ... + def wait_for_handle(self, handle: windows_utils.PipeHandle, timeout: int | None = ...) -> bool: ... + def close(self) -> None: ... + SelectorEventLoop = _WindowsSelectorEventLoop -if sys.version_info >= (3, 7): - class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): - _loop_factory: ClassVar[Type[SelectorEventLoop]] - def get_child_watcher(self) -> NoReturn: ... - def set_child_watcher(self, watcher: Any) -> NoReturn: ... - class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): - _loop_factory: ClassVar[Type[ProactorEventLoop]] - def get_child_watcher(self) -> NoReturn: ... - def set_child_watcher(self, watcher: Any) -> NoReturn: ... - DefaultEventLoopPolicy = WindowsSelectorEventLoopPolicy -else: - class _WindowsDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy): - _loop_factory: ClassVar[Type[SelectorEventLoop]] - def get_child_watcher(self) -> NoReturn: ... - def set_child_watcher(self, watcher: Any) -> NoReturn: ... - DefaultEventLoopPolicy = _WindowsDefaultEventLoopPolicy + if sys.version_info >= (3, 7): + class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[type[SelectorEventLoop]] + def get_child_watcher(self) -> NoReturn: ... + def set_child_watcher(self, watcher: Any) -> NoReturn: ... + class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[type[ProactorEventLoop]] + def get_child_watcher(self) -> NoReturn: ... + def set_child_watcher(self, watcher: Any) -> NoReturn: ... + DefaultEventLoopPolicy = WindowsSelectorEventLoopPolicy + else: + class _WindowsDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy): + _loop_factory: ClassVar[type[SelectorEventLoop]] + def get_child_watcher(self) -> NoReturn: ... + def set_child_watcher(self, watcher: Any) -> NoReturn: ... + DefaultEventLoopPolicy = _WindowsDefaultEventLoopPolicy diff --git a/mypy/typeshed/stdlib/asyncio/windows_utils.pyi b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi index bf9cdde25a78..3c96b76fc4a1 100644 --- a/mypy/typeshed/stdlib/asyncio/windows_utils.pyi +++ b/mypy/typeshed/stdlib/asyncio/windows_utils.pyi @@ -1,27 +1,28 @@ +import subprocess import sys from _typeshed import Self from types import TracebackType -from typing import Callable, Protocol, Type +from typing import Callable, Protocol +from typing_extensions import Literal -class _WarnFunction(Protocol): - def __call__(self, message: str, category: Type[Warning] = ..., stacklevel: int = ..., source: PipeHandle = ...) -> None: ... - -BUFSIZE: int -PIPE: int -STDOUT: int - -def pipe(*, duplex: bool = ..., overlapped: tuple[bool, bool] = ..., bufsize: int = ...) -> tuple[int, int]: ... - -class PipeHandle: - def __init__(self, handle: int) -> None: ... - def __repr__(self) -> str: ... - if sys.version_info >= (3, 8): - def __del__(self, _warn: _WarnFunction = ...) -> None: ... - else: - def __del__(self) -> None: ... - def __enter__(self: Self) -> Self: ... - def __exit__(self, t: type | None, v: BaseException | None, tb: TracebackType | None) -> None: ... - @property - def handle(self) -> int: ... - def fileno(self) -> int: ... - def close(self, *, CloseHandle: Callable[[int], None] = ...) -> None: ... +if sys.platform == "win32": + class _WarnFunction(Protocol): + def __call__( + self, message: str, category: type[Warning] = ..., stacklevel: int = ..., source: PipeHandle = ... + ) -> None: ... + BUFSIZE: Literal[8192] + PIPE = subprocess.PIPE + STDOUT = subprocess.STDOUT + def pipe(*, duplex: bool = ..., overlapped: tuple[bool, bool] = ..., bufsize: int = ...) -> tuple[int, int]: ... + class PipeHandle: + def __init__(self, handle: int) -> None: ... + if sys.version_info >= (3, 8): + def __del__(self, _warn: _WarnFunction = ...) -> None: ... + else: + def __del__(self) -> None: ... + def __enter__(self: Self) -> Self: ... + def __exit__(self, t: type | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + @property + def handle(self) -> int: ... + def fileno(self) -> int: ... + def close(self, *, CloseHandle: Callable[[int], None] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncore.pyi b/mypy/typeshed/stdlib/asyncore.pyi index e135221134a5..123da2677a7e 100644 --- a/mypy/typeshed/stdlib/asyncore.pyi +++ b/mypy/typeshed/stdlib/asyncore.pyi @@ -1,10 +1,10 @@ import sys from _typeshed import FileDescriptorLike from socket import socket -from typing import Any, Dict, Tuple, overload +from typing import Any, overload # cyclic dependence with asynchat -_maptype = Dict[int, Any] +_maptype = dict[int, Any] _socket = socket socket_map: _maptype # undocumented @@ -41,8 +41,8 @@ class dispatcher: def readable(self) -> bool: ... def writable(self) -> bool: ... def listen(self, num: int) -> None: ... - def bind(self, addr: Tuple[Any, ...] | str) -> None: ... - def connect(self, address: Tuple[Any, ...] | str) -> None: ... + def bind(self, addr: tuple[Any, ...] | str) -> None: ... + def connect(self, address: tuple[Any, ...] | str) -> None: ... def accept(self) -> tuple[_socket, Any] | None: ... def send(self, data: bytes) -> int: ... def recv(self, buffer_size: int) -> bytes: ... diff --git a/mypy/typeshed/stdlib/atexit.pyi b/mypy/typeshed/stdlib/atexit.pyi index 9395c60678b8..ba0c7dfaf6b1 100644 --- a/mypy/typeshed/stdlib/atexit.pyi +++ b/mypy/typeshed/stdlib/atexit.pyi @@ -7,5 +7,5 @@ _P = ParamSpec("_P") def _clear() -> None: ... def _ncallbacks() -> int: ... def _run_exitfuncs() -> None: ... -def register(func: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Callable[_P, _T]: ... # type: ignore +def register(func: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Callable[_P, _T]: ... def unregister(func: Callable[..., Any]) -> None: ... diff --git a/mypy/typeshed/stdlib/audioop.pyi b/mypy/typeshed/stdlib/audioop.pyi index 321bfe55c4b0..b08731b85b0b 100644 --- a/mypy/typeshed/stdlib/audioop.pyi +++ b/mypy/typeshed/stdlib/audioop.pyi @@ -1,7 +1,5 @@ -from typing import Tuple - -AdpcmState = Tuple[int, int] -RatecvState = Tuple[int, Tuple[Tuple[int, int], ...]] +AdpcmState = tuple[int, int] +RatecvState = tuple[int, tuple[tuple[int, int], ...]] class error(Exception): ... diff --git a/mypy/typeshed/stdlib/bdb.pyi b/mypy/typeshed/stdlib/bdb.pyi index 1d03ddf19a0e..d32dd446889d 100644 --- a/mypy/typeshed/stdlib/bdb.pyi +++ b/mypy/typeshed/stdlib/bdb.pyi @@ -1,11 +1,14 @@ from types import CodeType, FrameType, TracebackType -from typing import IO, Any, Callable, Iterable, Mapping, SupportsInt, Tuple, Type, TypeVar +from typing import IO, Any, Callable, Iterable, Mapping, SupportsInt, TypeVar +from typing_extensions import Literal + +__all__ = ["BdbQuit", "Bdb", "Breakpoint"] _T = TypeVar("_T") _TraceDispatch = Callable[[FrameType, str, Any], Any] # TODO: Recursive type -_ExcInfo = Tuple[Type[BaseException], BaseException, FrameType] +_ExcInfo = tuple[type[BaseException], BaseException, FrameType] -GENERATOR_AND_COROUTINE_FLAGS: int +GENERATOR_AND_COROUTINE_FLAGS: Literal[672] class BdbQuit(Exception): ... @@ -87,7 +90,6 @@ class Breakpoint: def disable(self) -> None: ... def bpprint(self, out: IO[str] | None = ...) -> None: ... def bpformat(self) -> str: ... - def __str__(self) -> str: ... def checkfuncname(b: Breakpoint, frame: FrameType) -> bool: ... def effective(file: str, line: int, frame: FrameType) -> tuple[Breakpoint, bool] | tuple[None, None]: ... diff --git a/mypy/typeshed/stdlib/binascii.pyi b/mypy/typeshed/stdlib/binascii.pyi index 962f5666b284..317bb9979b92 100644 --- a/mypy/typeshed/stdlib/binascii.pyi +++ b/mypy/typeshed/stdlib/binascii.pyi @@ -12,10 +12,13 @@ def a2b_base64(__data: str | bytes) -> bytes: ... def b2a_base64(__data: bytes, *, newline: bool = ...) -> bytes: ... def a2b_qp(data: str | bytes, header: bool = ...) -> bytes: ... def b2a_qp(data: bytes, quotetabs: bool = ..., istext: bool = ..., header: bool = ...) -> bytes: ... -def a2b_hqx(__data: str | bytes) -> bytes: ... -def rledecode_hqx(__data: bytes) -> bytes: ... -def rlecode_hqx(__data: bytes) -> bytes: ... -def b2a_hqx(__data: bytes) -> bytes: ... + +if sys.version_info < (3, 11): + def a2b_hqx(__data: str | bytes) -> bytes: ... + def rledecode_hqx(__data: bytes) -> bytes: ... + def rlecode_hqx(__data: bytes) -> bytes: ... + def b2a_hqx(__data: bytes) -> bytes: ... + def crc_hqx(__data: bytes, __crc: int) -> int: ... def crc32(__data: bytes, __crc: int = ...) -> int: ... def b2a_hex(__data: bytes) -> bytes: ... diff --git a/mypy/typeshed/stdlib/binhex.pyi b/mypy/typeshed/stdlib/binhex.pyi index 02d094faf923..e531ccd508bf 100644 --- a/mypy/typeshed/stdlib/binhex.pyi +++ b/mypy/typeshed/stdlib/binhex.pyi @@ -1,10 +1,13 @@ -from typing import IO, Any, Tuple, Union +from typing import IO, Any, Union +from typing_extensions import Literal + +__all__ = ["binhex", "hexbin", "Error"] class Error(Exception): ... -REASONABLY_LARGE: int -LINELEN: int -RUNCHAR: bytes +REASONABLY_LARGE: Literal[32768] +LINELEN: Literal[64] +RUNCHAR: Literal[b"\x90"] class FInfo: def __init__(self) -> None: ... @@ -12,7 +15,7 @@ class FInfo: Creator: str Flags: int -_FileInfoTuple = Tuple[str, FInfo, int, int] +_FileInfoTuple = tuple[str, FInfo, int, int] _FileHandleUnion = Union[str, IO[bytes]] def getfileinfo(name: str) -> _FileInfoTuple: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 1b2d3db12c3f..8abdf0afd727 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -23,13 +23,11 @@ from _typeshed import ( SupportsWrite, ) from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper -from types import CodeType, TracebackType +from types import CodeType, TracebackType, _Cell from typing import ( IO, AbstractSet, Any, - AsyncIterable, - AsyncIterator, BinaryIO, ByteString, Callable, @@ -51,8 +49,6 @@ from typing import ( SupportsFloat, SupportsInt, SupportsRound, - Tuple, - Type, TypeVar, Union, overload, @@ -73,28 +69,33 @@ _T2 = TypeVar("_T2") _T3 = TypeVar("_T3") _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") -_TT = TypeVar("_TT", bound="type") -_TBE = TypeVar("_TBE", bound="BaseException") _R = TypeVar("_R") # Return-type TypeVar +_SupportsNextT = TypeVar("_SupportsNextT", bound=SupportsNext[Any], covariant=True) +_SupportsAnextT = TypeVar("_SupportsAnextT", bound=SupportsAnext[Any], covariant=True) + +class _SupportsIter(Protocol[_T_co]): + def __iter__(self) -> _T_co: ... + +class _SupportsAiter(Protocol[_T_co]): + def __aiter__(self) -> _T_co: ... class object: __doc__: str | None __dict__: dict[str, Any] - __slots__: str | Iterable[str] __module__: str __annotations__: dict[str, Any] @property - def __class__(self: _T) -> Type[_T]: ... + def __class__(self: Self) -> type[Self]: ... # Ignore errors about type mismatch between property getter and setter @__class__.setter - def __class__(self, __type: Type[object]) -> None: ... # type: ignore # noqa: F811 + def __class__(self, __type: type[object]) -> None: ... # type: ignore # noqa: F811 def __init__(self) -> None: ... - def __new__(cls: Type[_T]) -> _T: ... + def __new__(cls: type[Self]) -> Self: ... 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 __str__(self) -> str: ... # noqa Y029 + def __repr__(self) -> str: ... # noqa Y029 def __hash__(self) -> int: ... def __format__(self, __format_spec: str) -> str: ... def __getattribute__(self, __name: str) -> Any: ... @@ -102,47 +103,45 @@ class object: def __sizeof__(self) -> int: ... # return type of pickle methods is rather hard to express in the current type system # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__ - def __reduce__(self) -> str | Tuple[Any, ...]: ... + def __reduce__(self) -> str | tuple[Any, ...]: ... if sys.version_info >= (3, 8): - def __reduce_ex__(self, __protocol: SupportsIndex) -> str | Tuple[Any, ...]: ... + def __reduce_ex__(self, __protocol: SupportsIndex) -> str | tuple[Any, ...]: ... else: - def __reduce_ex__(self, __protocol: int) -> str | Tuple[Any, ...]: ... + def __reduce_ex__(self, __protocol: int) -> str | tuple[Any, ...]: ... def __dir__(self) -> Iterable[str]: ... def __init_subclass__(cls) -> None: ... -class staticmethod(Generic[_R]): # Special, only valid as a decorator. +class staticmethod(Generic[_R]): __func__: Callable[..., _R] __isabstractmethod__: bool 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[..., _R]: ... + 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(Generic[_R]): # Special, only valid as a decorator. +class classmethod(Generic[_R]): __func__: Callable[..., _R] __isabstractmethod__: bool 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[..., _R]: ... + 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): +class type: __base__: type - __bases__: Tuple[type, ...] + __bases__: tuple[type, ...] __basicsize__: int __dict__: dict[str, Any] __dictoffset__: int __flags__: int __itemsize__: int __module__: str - __mro__: Tuple[type, ...] + __mro__: tuple[type, ...] __name__: str __qualname__: str __text_signature__: str | None @@ -150,25 +149,25 @@ class type(object): @overload 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: ... @overload - def __new__(cls: Type[_TT], __name: str, __bases: Tuple[type, ...], __namespace: dict[str, Any], **kwds: Any) -> _TT: ... + def __new__(cls: type[Self], __name: str, __bases: tuple[type, ...], __namespace: dict[str, Any], **kwds: Any) -> Self: ... def __call__(self, *args: Any, **kwds: Any) -> Any: ... - def __subclasses__(self: _TT) -> list[_TT]: ... + def __subclasses__(self: Self) -> list[Self]: ... # 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: ... @classmethod - def __prepare__(metacls, __name: str, __bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, object]: ... + 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: ... -class super(object): +class super: @overload def __init__(self, __t: Any, __obj: Any) -> None: ... @overload @@ -181,9 +180,9 @@ _NegativeInteger = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -1 class int: @overload - def __new__(cls: Type[_T], __x: str | bytes | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> _T: ... + def __new__(cls: type[Self], __x: str | bytes | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> Self: ... @overload - def __new__(cls: Type[_T], __x: str | bytes | bytearray, base: SupportsIndex) -> _T: ... + def __new__(cls: type[Self], __x: str | bytes | bytearray, base: SupportsIndex) -> Self: ... if sys.version_info >= (3, 8): def as_integer_ratio(self) -> tuple[int, Literal[1]]: ... @property @@ -201,8 +200,12 @@ class int: def to_bytes(self, length: SupportsIndex, byteorder: Literal["little", "big"], *, signed: bool = ...) -> bytes: ... @classmethod def from_bytes( - cls, bytes: Iterable[SupportsIndex] | SupportsBytes, byteorder: Literal["little", "big"], *, signed: bool = ... - ) -> int: ... # TODO buffer object argument + cls: type[Self], + bytes: Iterable[SupportsIndex] | SupportsBytes, # TODO buffer object argument + byteorder: Literal["little", "big"], + *, + signed: bool = ..., + ) -> Self: ... def __add__(self, __x: int) -> int: ... def __sub__(self, __x: int) -> int: ... def __mul__(self, __x: int) -> int: ... @@ -254,7 +257,6 @@ class int: 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: ... def __abs__(self) -> int: ... @@ -263,12 +265,12 @@ class int: def __index__(self) -> int: ... class float: - def __new__(cls: Type[_T], x: SupportsFloat | SupportsIndex | str | bytes | bytearray = ...) -> _T: ... + def __new__(cls: type[Self], x: SupportsFloat | SupportsIndex | str | bytes | bytearray = ...) -> Self: ... def as_integer_ratio(self) -> tuple[int, int]: ... def hex(self) -> str: ... def is_integer(self) -> bool: ... @classmethod - def fromhex(cls, __s: str) -> float: ... + def fromhex(cls: type[Self], __s: str) -> Self: ... @property def real(self) -> float: ... @property @@ -312,7 +314,6 @@ class float: def __ge__(self, __x: float) -> bool: ... def __neg__(self) -> float: ... def __pos__(self) -> float: ... - def __str__(self) -> str: ... def __int__(self) -> int: ... def __float__(self) -> float: ... def __abs__(self) -> float: ... @@ -321,9 +322,9 @@ class float: class complex: @overload - def __new__(cls: Type[_T], real: float = ..., imag: float = ...) -> _T: ... + def __new__(cls: type[Self], real: float = ..., imag: float = ...) -> Self: ... @overload - def __new__(cls: Type[_T], real: str | SupportsComplex | SupportsIndex | complex) -> _T: ... + def __new__(cls: type[Self], real: str | SupportsComplex | SupportsIndex | complex) -> Self: ... @property def real(self) -> float: ... @property @@ -343,26 +344,27 @@ class complex: def __ne__(self, __x: object) -> bool: ... def __neg__(self) -> complex: ... def __pos__(self) -> complex: ... - def __str__(self) -> str: ... def __abs__(self) -> float: ... def __hash__(self) -> int: ... def __bool__(self) -> bool: ... + if sys.version_info >= (3, 11): + def __complex__(self) -> complex: ... class _FormatMapMapping(Protocol): def __getitem__(self, __key: str) -> Any: ... class str(Sequence[str]): @overload - def __new__(cls: Type[_T], object: object = ...) -> _T: ... + def __new__(cls: type[Self], object: object = ...) -> Self: ... @overload - def __new__(cls: Type[_T], o: bytes, encoding: str = ..., errors: str = ...) -> _T: ... + def __new__(cls: type[Self], o: bytes, encoding: str = ..., errors: str = ...) -> Self: ... def capitalize(self) -> str: ... def casefold(self) -> str: ... def center(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... def count(self, x: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def encode(self, encoding: str = ..., errors: str = ...) -> bytes: ... def endswith( - self, __suffix: str | Tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __suffix: str | tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> bool: ... if sys.version_info >= (3, 8): def expandtabs(self, tabsize: SupportsIndex = ...) -> str: ... @@ -403,7 +405,7 @@ class str(Sequence[str]): def split(self, sep: str | None = ..., maxsplit: SupportsIndex = ...) -> list[str]: ... def splitlines(self, keepends: bool = ...) -> list[str]: ... def startswith( - self, __prefix: str | Tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __prefix: str | tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> bool: ... def strip(self, __chars: str | None = ...) -> str: ... def swapcase(self) -> str: ... @@ -422,7 +424,7 @@ class str(Sequence[str]): def __contains__(self, __o: str) -> bool: ... # type: ignore[override] def __eq__(self, __x: object) -> bool: ... def __ge__(self, __x: str) -> bool: ... - def __getitem__(self, __i: int | slice) -> str: ... + def __getitem__(self, __i: SupportsIndex | slice) -> str: ... def __gt__(self, __x: str) -> bool: ... def __hash__(self) -> int: ... def __iter__(self) -> Iterator[str]: ... @@ -432,22 +434,20 @@ class str(Sequence[str]): 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: ... def __getnewargs__(self) -> tuple[str]: ... class bytes(ByteString): @overload - def __new__(cls: Type[_T], __ints: Iterable[SupportsIndex]) -> _T: ... + def __new__(cls: type[Self], __ints: Iterable[SupportsIndex]) -> Self: ... @overload - def __new__(cls: Type[_T], __string: str, encoding: str, errors: str = ...) -> _T: ... + def __new__(cls: type[Self], __string: str, encoding: str, errors: str = ...) -> Self: ... @overload - def __new__(cls: Type[_T], __length: SupportsIndex) -> _T: ... + def __new__(cls: type[Self], __length: SupportsIndex) -> Self: ... @overload - def __new__(cls: Type[_T]) -> _T: ... + def __new__(cls: type[Self]) -> Self: ... @overload - def __new__(cls: Type[_T], __o: SupportsBytes) -> _T: ... + def __new__(cls: type[Self], __o: SupportsBytes) -> Self: ... def capitalize(self) -> bytes: ... def center(self, __width: SupportsIndex, __fillchar: bytes = ...) -> bytes: ... def count( @@ -455,7 +455,7 @@ class bytes(ByteString): ) -> int: ... def decode(self, encoding: str = ..., errors: str = ...) -> str: ... def endswith( - self, __suffix: bytes | Tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __suffix: bytes | tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> bool: ... if sys.version_info >= (3, 8): def expandtabs(self, tabsize: SupportsIndex = ...) -> bytes: ... @@ -502,7 +502,7 @@ class bytes(ByteString): def split(self, sep: bytes | None = ..., maxsplit: SupportsIndex = ...) -> list[bytes]: ... def splitlines(self, keepends: bool = ...) -> list[bytes]: ... def startswith( - self, __prefix: bytes | Tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __prefix: bytes | tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> bool: ... def strip(self, __bytes: bytes | None = ...) -> bytes: ... def swapcase(self) -> bytes: ... @@ -511,13 +511,11 @@ class bytes(ByteString): def upper(self) -> bytes: ... def zfill(self, __width: SupportsIndex) -> bytes: ... @classmethod - def fromhex(cls: Type[_T], __s: str) -> _T: ... + def fromhex(cls: type[Self], __s: str) -> Self: ... @staticmethod def maketrans(__frm: bytes, __to: bytes) -> bytes: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... def __hash__(self) -> int: ... @overload def __getitem__(self, __i: SupportsIndex) -> int: ... @@ -536,6 +534,8 @@ class bytes(ByteString): def __gt__(self, __x: bytes) -> bool: ... def __ge__(self, __x: bytes) -> bool: ... def __getnewargs__(self) -> tuple[bytes]: ... + if sys.version_info >= (3, 11): + def __bytes__(self) -> bytes: ... class bytearray(MutableSequence[int], ByteString): @overload @@ -555,7 +555,7 @@ class bytearray(MutableSequence[int], ByteString): def copy(self) -> bytearray: ... def decode(self, encoding: str = ..., errors: str = ...) -> str: ... def endswith( - self, __suffix: bytes | Tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __suffix: bytes | tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> bool: ... if sys.version_info >= (3, 8): def expandtabs(self, tabsize: SupportsIndex = ...) -> bytearray: ... @@ -604,7 +604,7 @@ class bytearray(MutableSequence[int], ByteString): def split(self, sep: bytes | None = ..., maxsplit: SupportsIndex = ...) -> list[bytearray]: ... def splitlines(self, keepends: bool = ...) -> list[bytearray]: ... def startswith( - self, __prefix: bytes | Tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... + self, __prefix: bytes | tuple[bytes, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> bool: ... def strip(self, __bytes: bytes | None = ...) -> bytearray: ... def swapcase(self) -> bytearray: ... @@ -613,13 +613,11 @@ class bytearray(MutableSequence[int], ByteString): def upper(self) -> bytearray: ... def zfill(self, __width: SupportsIndex) -> bytearray: ... @classmethod - def fromhex(cls, __string: str) -> bytearray: ... + def fromhex(cls: type[Self], __string: str) -> Self: ... @staticmethod def maketrans(__frm: bytes, __to: bytes) -> bytes: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... - def __str__(self) -> str: ... - def __repr__(self) -> str: ... __hash__: None # type: ignore[assignment] @overload def __getitem__(self, __i: SupportsIndex) -> int: ... @@ -647,25 +645,36 @@ class bytearray(MutableSequence[int], ByteString): @final class memoryview(Sized, Sequence[int]): - format: str - itemsize: int - shape: Tuple[int, ...] | None - strides: Tuple[int, ...] | None - suboffsets: Tuple[int, ...] | None - readonly: bool - ndim: int - - obj: bytes | bytearray - c_contiguous: bool - f_contiguous: bool - contiguous: bool - nbytes: int + @property + def format(self) -> str: ... + @property + def itemsize(self) -> int: ... + @property + def shape(self) -> tuple[int, ...] | None: ... + @property + def strides(self) -> tuple[int, ...] | None: ... + @property + def suboffsets(self) -> tuple[int, ...] | None: ... + @property + def readonly(self) -> bool: ... + @property + def ndim(self) -> int: ... + @property + def obj(self) -> bytes | bytearray: ... + @property + def c_contiguous(self) -> bool: ... + @property + def f_contiguous(self) -> bool: ... + @property + def contiguous(self) -> bool: ... + @property + def nbytes(self) -> 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: ... + def cast(self, format: str, shape: list[int] | tuple[int, ...] = ...) -> memoryview: ... @overload def __getitem__(self, __i: SupportsIndex) -> int: ... @overload @@ -692,7 +701,7 @@ class memoryview(Sized, Sequence[int]): @final class bool(int): - def __new__(cls: Type[_T], __o: object = ...) -> _T: ... + def __new__(cls: type[Self], __o: object = ...) -> Self: ... @overload def __and__(self, __x: bool) -> bool: ... @overload @@ -720,10 +729,13 @@ class bool(int): def __getnewargs__(self) -> tuple[int]: ... @final -class slice(object): - start: Any - step: Any - stop: Any +class slice: + @property + def start(self) -> Any: ... + @property + def step(self) -> Any: ... + @property + def stop(self) -> Any: ... @overload def __init__(self, __stop: Any) -> None: ... @overload @@ -732,59 +744,67 @@ class slice(object): 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[Self], __iterable: Iterable[_T_co] = ...) -> Self: ... def __len__(self) -> int: ... def __contains__(self, __x: object) -> bool: ... @overload - def __getitem__(self, __x: int) -> _T_co: ... + def __getitem__(self, __x: SupportsIndex) -> _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: ... +# Doesn't exist at runtime, but deleting this breaks mypy. See #2999 +@final class function: - # TODO not defined in builtins! - __name__: str - __module__: str + # Make sure this class definition stays roughly in line with `types.FunctionType` + __closure__: tuple[_Cell, ...] | None __code__: CodeType + __defaults__: tuple[Any, ...] | None + __dict__: dict[str, Any] + __globals__: dict[str, Any] + __name__: str __qualname__: str __annotations__: dict[str, Any] + __kwdefaults__: dict[str, Any] + __module__: str + # mypy uses `builtins.function.__get__` to represent methods, properties, and getset_descriptors so we type the return as Any. + def __get__(self, obj: object | None, type: type | None = ...) -> Any: ... class list(MutableSequence[_T], Generic[_T]): @overload def __init__(self) -> None: ... @overload def __init__(self, __iterable: Iterable[_T]) -> None: ... - def clear(self) -> None: ... def copy(self) -> list[_T]: ... def append(self, __object: _T) -> None: ... def extend(self, __iterable: Iterable[_T]) -> None: ... def pop(self, __index: SupportsIndex = ...) -> _T: ... + # Signature of `list.index` should be kept in line with `collections.UserList.index()` def index(self, __value: _T, __start: SupportsIndex = ..., __stop: SupportsIndex = ...) -> int: ... def count(self, __value: _T) -> int: ... def insert(self, __index: SupportsIndex, __object: _T) -> None: ... def remove(self, __value: _T) -> None: ... - def reverse(self) -> None: ... + # Signature of `list.sort` should be kept inline with `collections.UserList.sort()` @overload def sort(self: list[SupportsRichComparisonT], *, key: None = ..., reverse: bool = ...) -> None: ... @overload def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> None: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[_T]: ... - def __str__(self) -> str: ... __hash__: None # type: ignore[assignment] @overload def __getitem__(self, __i: SupportsIndex) -> _T: ... @@ -796,10 +816,10 @@ class list(MutableSequence[_T], Generic[_T]): 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 __iadd__(self: Self, __x: Iterable[_T]) -> Self: ... def __mul__(self, __n: SupportsIndex) -> list[_T]: ... def __rmul__(self, __n: SupportsIndex) -> list[_T]: ... - def __imul__(self: _S, __n: SupportsIndex) -> _S: ... + def __imul__(self: Self, __n: SupportsIndex) -> Self: ... def __contains__(self, __o: object) -> bool: ... def __reversed__(self) -> Iterator[_T]: ... def __gt__(self, __x: list[_T]) -> bool: ... @@ -810,6 +830,7 @@ class list(MutableSequence[_T], Generic[_T]): def __class_getitem__(cls, __item: Any) -> GenericAlias: ... class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): + # __init__ should be kept roughly in line with `collections.UserDict.__init__`, which has similar semantics @overload def __init__(self: dict[_KT, _VT]) -> None: ... @overload @@ -822,20 +843,14 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): # 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 __new__(cls: Type[_T1], *args: Any, **kwargs: Any) -> _T1: ... - def clear(self) -> None: ... + def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self: ... def copy(self) -> dict[_KT, _VT]: ... - def popitem(self) -> tuple[_KT, _VT]: ... - def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ... - @overload - def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... - @overload - 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[_KT, _VT]: ... def items(self) -> dict_items[_KT, _VT]: ... + # Signature of `dict.fromkeys` should be kept identical to `fromkeys` methods of `OrderedDict`/`ChainMap`/`UserDict` in `collections` + # TODO: the true signature of `dict.fromkeys` is not expressible in the current type system. + # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963. @classmethod @overload def fromkeys(cls, __iterable: Iterable[_T], __value: None = ...) -> dict[_T, Any | None]: ... @@ -849,18 +864,20 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def __iter__(self) -> Iterator[_KT]: ... if sys.version_info >= (3, 8): def __reversed__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... __hash__: None # type: ignore[assignment] if sys.version_info >= (3, 9): 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[misc] + # dict.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self: Self, __value: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self: Self, __value: Iterable[tuple[_KT, _VT]]) -> Self: ... class set(MutableSet[_T], Generic[_T]): 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: ... @@ -870,7 +887,6 @@ class set(MutableSet[_T], Generic[_T]): 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: ... @@ -879,7 +895,6 @@ class set(MutableSet[_T], Generic[_T]): def __len__(self) -> int: ... 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]: ... @@ -909,7 +924,6 @@ class frozenset(AbstractSet[_T_co], Generic[_T_co]): def __len__(self) -> int: ... 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]: ... @@ -921,7 +935,7 @@ class frozenset(AbstractSet[_T_co], Generic[_T_co]): if sys.version_info >= (3, 9): def __class_getitem__(cls, __item: Any) -> GenericAlias: ... -class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): +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]: ... @@ -930,9 +944,12 @@ class enumerate(Iterator[Tuple[int, _T]], Generic[_T]): @final class range(Sequence[int]): - start: int - stop: int - step: int + @property + def start(self) -> int: ... + @property + def stop(self) -> int: ... + @property + def step(self) -> int: ... @overload def __init__(self, __stop: SupportsIndex) -> None: ... @overload @@ -946,10 +963,9 @@ class range(Sequence[int]): def __getitem__(self, __i: SupportsIndex) -> int: ... @overload def __getitem__(self, __s: slice) -> range: ... - def __repr__(self) -> str: ... def __reversed__(self) -> Iterator[int]: ... -class property(object): +class property: fget: Callable[[Any], Any] | None fset: Callable[[Any, Any], None] | None fdel: Callable[[Any], None] | None @@ -995,7 +1011,7 @@ class _PathLike(Protocol[_AnyStr_co]): def __fspath__(self) -> _AnyStr_co: ... if sys.version_info >= (3, 10): - def aiter(__iterable: AsyncIterable[_T]) -> AsyncIterator[_T]: ... + def aiter(__async_iterable: _SupportsAiter[_SupportsAnextT]) -> _SupportsAnextT: ... @overload async def anext(__i: SupportsAnext[_T]) -> _T: ... @overload @@ -1073,12 +1089,12 @@ 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 help(request: object = ...) -> None: ... def hex(__number: int | SupportsIndex) -> str: ... def id(__obj: object) -> int: ... def input(__prompt: object = ...) -> str: ... @overload -def iter(__iterable: Iterable[_T]) -> Iterator[_T]: ... +def iter(__iterable: _SupportsIter[_SupportsNextT]) -> _SupportsNextT: ... @overload def iter(__function: Callable[[], _T | None], __sentinel: None) -> Iterator[_T]: ... @overload @@ -1087,15 +1103,15 @@ 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, ...], ...] + __obj: object, __class_or_tuple: type | types.UnionType | tuple[type | types.UnionType | tuple[Any, ...], ...] ) -> bool: ... def issubclass( - __cls: type, __class_or_tuple: type | types.UnionType | Tuple[type | types.UnionType | Tuple[Any, ...], ...] + __cls: type, __class_or_tuple: type | types.UnionType | tuple[type | types.UnionType | tuple[Any, ...], ...] ) -> bool: ... else: - def isinstance(__obj: object, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... - def issubclass(__cls: type, __class_or_tuple: type | Tuple[type | Tuple[Any, ...], ...]) -> bool: ... + def isinstance(__obj: object, __class_or_tuple: type | tuple[type | tuple[Any, ...], ...]) -> bool: ... + def issubclass(__cls: type, __class_or_tuple: type | tuple[type | tuple[Any, ...], ...]) -> bool: ... def len(__obj: Sized) -> int: ... def license() -> None: ... @@ -1382,19 +1398,21 @@ def round(number: SupportsRound[_T], ndigits: SupportsIndex) -> _T: ... # 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[SupportsRichComparisonT], *, key: None = ..., reverse: bool = ...) -> list[SupportsRichComparisonT]: ... +def sorted( + __iterable: Iterable[SupportsRichComparisonT], *, key: None = ..., reverse: bool = ... +) -> list[SupportsRichComparisonT]: ... @overload def sorted(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> list[_T]: ... if sys.version_info >= (3, 8): @overload - def sum(__iterable: Iterable[_T]) -> _T | int: ... + def sum(__iterable: Iterable[_T]) -> _T | Literal[0]: ... @overload def sum(__iterable: Iterable[_T], start: _S) -> _T | _S: ... else: @overload - def sum(__iterable: Iterable[_T]) -> _T | int: ... + def sum(__iterable: Iterable[_T]) -> _T | Literal[0]: ... @overload def sum(__iterable: Iterable[_T], __start: _S) -> _T | _S: ... @@ -1444,7 +1462,7 @@ class zip(Iterator[_T_co], Generic[_T_co]): __iter6: Iterable[Any], *iterables: Iterable[Any], strict: bool = ..., - ) -> zip[Tuple[Any, ...]]: ... + ) -> zip[tuple[Any, ...]]: ... else: @overload def __new__(cls, __iter1: Iterable[_T1]) -> zip[tuple[_T1]]: ... @@ -1475,7 +1493,7 @@ class zip(Iterator[_T_co], Generic[_T_co]): __iter5: Iterable[Any], __iter6: Iterable[Any], *iterables: Iterable[Any], - ) -> zip[Tuple[Any, ...]]: ... + ) -> zip[tuple[Any, ...]]: ... def __iter__(self) -> Iterator[_T_co]: ... def __next__(self) -> _T_co: ... @@ -1496,16 +1514,16 @@ class ellipsis: ... Ellipsis: ellipsis -class BaseException(object): - args: Tuple[Any, ...] +class BaseException: + args: tuple[Any, ...] __cause__: BaseException | None __context__: BaseException | None __suppress_context__: bool __traceback__: TracebackType | None + if sys.version_info >= (3, 11): + __note__: str | None 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: Self, __tb: TracebackType | None) -> Self: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ... @@ -1624,7 +1642,14 @@ class UnicodeEncodeError(UnicodeError): reason: str def __init__(self, __encoding: str, __object: str, __start: int, __end: int, __reason: str) -> None: ... -class UnicodeTranslateError(UnicodeError): ... +class UnicodeTranslateError(UnicodeError): + encoding: None + object: str + start: int + end: int + reason: str + def __init__(self, __object: str, __start: int, __end: int, __reason: str) -> None: ... + class Warning(Exception): ... class UserWarning(Warning): ... class DeprecationWarning(Warning): ... @@ -1639,3 +1664,19 @@ class ResourceWarning(Warning): ... if sys.version_info >= (3, 10): class EncodingWarning(Warning): ... + +if sys.version_info >= (3, 11): + _SplitCondition = type[BaseException] | tuple[type[BaseException], ...] | Callable[[BaseException], bool] + class BaseExceptionGroup(BaseException): + def __new__(cls, __message: str, __exceptions: Sequence[BaseException]) -> BaseExceptionGroup | ExceptionGroup: ... + @property + def message(self) -> str: ... + @property + def exceptions(self) -> tuple[BaseException, ...]: ... + def subgroup(self: Self, __condition: _SplitCondition) -> Self | None: ... + def split(self: Self, __condition: _SplitCondition) -> tuple[Self | None, Self | None]: ... + def derive(self: Self, __excs: Sequence[BaseException]) -> Self: ... + class ExceptionGroup(BaseExceptionGroup, Exception): + def __new__(cls, __message: str, __exceptions: Sequence[Exception]) -> ExceptionGroup: ... + @property + def exceptions(self) -> tuple[Exception, ...]: ... diff --git a/mypy/typeshed/stdlib/bz2.pyi b/mypy/typeshed/stdlib/bz2.pyi index c49832759fa8..69f13e4966b7 100644 --- a/mypy/typeshed/stdlib/bz2.pyi +++ b/mypy/typeshed/stdlib/bz2.pyi @@ -2,7 +2,7 @@ import _compression 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 import IO, Any, Iterable, Protocol, TextIO, overload from typing_extensions import Literal, SupportsIndex, final # The following attributes and methods are optional: @@ -16,8 +16,6 @@ class _WritableFileobj(Protocol): # def fileno(self) -> int: ... # def close(self) -> object: ... -_T = TypeVar("_T") - def compress(data: bytes, compresslevel: int = ...) -> bytes: ... def decompress(data: bytes) -> bytes: ... @@ -80,6 +78,15 @@ def open( errors: str | None = ..., newline: str | None = ..., ) -> TextIO: ... +@overload +def open( + filename: StrOrBytesPath | _ReadableFileobj | _WritableFileobj, + mode: str, + compresslevel: int = ..., + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., +) -> BZ2File | TextIO: ... class BZ2File(BaseStream, IO[bytes]): def __enter__(self: Self) -> Self: ... @@ -111,7 +118,7 @@ class BZ2File(BaseStream, IO[bytes]): ) -> None: ... def read(self, size: int | None = ...) -> bytes: ... def read1(self, size: int = ...) -> bytes: ... - def readline(self, size: SupportsIndex = ...) -> bytes: ... # type: ignore + def readline(self, size: SupportsIndex = ...) -> bytes: ... # type: ignore[override] def readinto(self, b: WriteableBuffer) -> int: ... def readlines(self, size: SupportsIndex = ...) -> list[bytes]: ... def seek(self, offset: int, whence: int = ...) -> int: ... @@ -119,13 +126,13 @@ class BZ2File(BaseStream, IO[bytes]): def writelines(self, seq: Iterable[ReadableBuffer]) -> None: ... @final -class BZ2Compressor(object): +class BZ2Compressor: def __init__(self, compresslevel: int = ...) -> None: ... def compress(self, __data: bytes) -> bytes: ... def flush(self) -> bytes: ... @final -class BZ2Decompressor(object): +class BZ2Decompressor: def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... @property def eof(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/cProfile.pyi b/mypy/typeshed/stdlib/cProfile.pyi index f4a7ab50cc11..e79524aa793e 100644 --- a/mypy/typeshed/stdlib/cProfile.pyi +++ b/mypy/typeshed/stdlib/cProfile.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Self, StrOrBytesPath from types import CodeType -from typing import Any, Callable, Tuple, TypeVar +from typing import Any, Callable, TypeVar def run(statement: str, filename: str | None = ..., sort: str | int = ...) -> None: ... def runctx( @@ -9,7 +9,7 @@ def runctx( ) -> None: ... _T = TypeVar("_T") -_Label = Tuple[str, int, str] +_Label = tuple[str, int, str] class Profile: stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]] # undocumented diff --git a/mypy/typeshed/stdlib/calendar.pyi b/mypy/typeshed/stdlib/calendar.pyi index 26073fb7281b..108356610322 100644 --- a/mypy/typeshed/stdlib/calendar.pyi +++ b/mypy/typeshed/stdlib/calendar.pyi @@ -1,17 +1,43 @@ import datetime import sys from time import struct_time -from typing import Any, Iterable, Optional, Sequence, Tuple - -_LocaleType = Tuple[Optional[str], Optional[str]] +from typing import Any, Iterable, Optional, Sequence +from typing_extensions import Literal + +__all__ = [ + "IllegalMonthError", + "IllegalWeekdayError", + "setfirstweekday", + "firstweekday", + "isleap", + "leapdays", + "weekday", + "monthrange", + "monthcalendar", + "prmonth", + "month", + "prcal", + "calendar", + "timegm", + "month_name", + "month_abbr", + "day_name", + "day_abbr", + "Calendar", + "TextCalendar", + "HTMLCalendar", + "LocaleTextCalendar", + "LocaleHTMLCalendar", + "weekheader", +] + +_LocaleType = tuple[Optional[str], Optional[str]] class IllegalMonthError(ValueError): def __init__(self, month: int) -> None: ... - def __str__(self) -> str: ... class IllegalWeekdayError(ValueError): def __init__(self, weekday: int) -> None: ... - def __str__(self) -> str: ... def isleap(year: int) -> bool: ... def leapdays(y1: int, y2: int) -> int: ... @@ -97,7 +123,7 @@ c: TextCalendar def setfirstweekday(firstweekday: int) -> None: ... def format(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ... def formatstring(cols: int, colwidth: int = ..., spacing: int = ...) -> str: ... -def timegm(tuple: Tuple[int, ...] | struct_time) -> int: ... +def timegm(tuple: tuple[int, ...] | struct_time) -> int: ... # Data attributes day_name: Sequence[str] @@ -105,13 +131,12 @@ day_abbr: Sequence[str] month_name: Sequence[str] month_abbr: Sequence[str] -# Below constants are not in docs or __all__, but enough people have used them -# they are now effectively public. +MONDAY: Literal[0] +TUESDAY: Literal[1] +WEDNESDAY: Literal[2] +THURSDAY: Literal[3] +FRIDAY: Literal[4] +SATURDAY: Literal[5] +SUNDAY: Literal[6] -MONDAY: int -TUESDAY: int -WEDNESDAY: int -THURSDAY: int -FRIDAY: int -SATURDAY: int -SUNDAY: int +EPOCH: Literal[1970] diff --git a/mypy/typeshed/stdlib/cgi.pyi b/mypy/typeshed/stdlib/cgi.pyi index 3821de46ed75..c78228c09ceb 100644 --- a/mypy/typeshed/stdlib/cgi.pyi +++ b/mypy/typeshed/stdlib/cgi.pyi @@ -1,10 +1,8 @@ import sys -from _typeshed import SupportsGetItem, SupportsItemAccess +from _typeshed import Self, SupportsGetItem, SupportsItemAccess from builtins import type as _type from collections.abc import Iterable, Iterator, Mapping -from typing import IO, Any, Protocol, TypeVar - -_T = TypeVar("_T", bound=FieldStorage) +from typing import IO, Any, Protocol def parse( fp: IO[Any] | None = ..., @@ -53,11 +51,10 @@ class MiniFieldStorage: name: Any value: Any def __init__(self, name: Any, value: Any) -> None: ... - def __repr__(self) -> str: ... _list = list -class FieldStorage(object): +class FieldStorage: FieldStorageClass: _type | None keep_blank_values: int strict_parsing: int @@ -94,9 +91,8 @@ class FieldStorage(object): max_num_fields: int | None = ..., separator: str = ..., ) -> None: ... - def __enter__(self: _T) -> _T: ... + def __enter__(self: Self) -> Self: ... def __exit__(self, *args: Any) -> None: ... - def __repr__(self) -> str: ... def __iter__(self) -> Iterator[str]: ... def __getitem__(self, key: str) -> Any: ... def getvalue(self, key: str, default: Any = ...) -> Any: ... diff --git a/mypy/typeshed/stdlib/cgitb.pyi b/mypy/typeshed/stdlib/cgitb.pyi index 7576740fc1c0..3a551e310b81 100644 --- a/mypy/typeshed/stdlib/cgitb.pyi +++ b/mypy/typeshed/stdlib/cgitb.pyi @@ -1,8 +1,8 @@ from _typeshed import StrOrBytesPath from types import FrameType, TracebackType -from typing import IO, Any, Callable, Optional, Tuple, Type +from typing import IO, Any, Callable, Optional -_ExcInfo = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_ExcInfo = tuple[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]] def reset() -> str: ... # undocumented def small(text: str) -> str: ... # undocumented @@ -24,7 +24,7 @@ class Hook: # undocumented file: IO[str] | None = ..., format: str = ..., ) -> None: ... - def __call__(self, etype: Type[BaseException] | None, evalue: BaseException | None, etb: TracebackType | None) -> None: ... + def __call__(self, etype: type[BaseException] | None, evalue: BaseException | None, etb: TracebackType | None) -> None: ... def handle(self, info: _ExcInfo | None = ...) -> None: ... def handler(info: _ExcInfo | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/cmd.pyi b/mypy/typeshed/stdlib/cmd.pyi index f6d818591a4e..82b2a7bc8a86 100644 --- a/mypy/typeshed/stdlib/cmd.pyi +++ b/mypy/typeshed/stdlib/cmd.pyi @@ -1,4 +1,10 @@ from typing import IO, Any, Callable +from typing_extensions import Literal + +__all__ = ["Cmd"] + +PROMPT: Literal["(Cmd) "] +IDENTCHARS: str # Too big to be `Literal` class Cmd: prompt: str diff --git a/mypy/typeshed/stdlib/codecs.pyi b/mypy/typeshed/stdlib/codecs.pyi index ebd6911c3e63..41f6eae50ebc 100644 --- a/mypy/typeshed/stdlib/codecs.pyi +++ b/mypy/typeshed/stdlib/codecs.pyi @@ -2,9 +2,14 @@ import sys import types from _typeshed import Self from abc import abstractmethod -from typing import IO, Any, BinaryIO, Callable, Generator, Iterable, Iterator, Protocol, TextIO, Tuple, Type, TypeVar, overload +from typing import IO, Any, BinaryIO, Callable, Generator, Iterable, Iterator, Protocol, TextIO, overload from typing_extensions import Literal +BOM32_BE: Literal[b"\xfe\xff"] +BOM32_LE: Literal[b"\xff\xfe"] +BOM64_BE: Literal[b"\x00\x00\xfe\xff"] +BOM64_LE: Literal[b"\xff\xfe\x00\x00"] + # TODO: this only satisfies the most common interface, where # bytes is the raw form and str is the cooked form. # In the long run, both should become template parameters maybe? @@ -53,11 +58,11 @@ _BytesToBytesEncodingT = Literal[ @overload def encode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... @overload -def encode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> str: ... # type: ignore +def encode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> str: ... # type: ignore[misc] @overload def encode(obj: str, encoding: str = ..., errors: str = ...) -> bytes: ... @overload -def decode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... # type: ignore +def decode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... # type: ignore[misc] @overload def decode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = ...) -> str: ... @overload @@ -66,7 +71,7 @@ def lookup(__encoding: str) -> CodecInfo: ... def utf_16_be_decode(__data: bytes, __errors: str | None = ..., __final: bool = ...) -> tuple[str, int]: ... # undocumented def utf_16_be_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... # undocumented -class CodecInfo(Tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): +class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): @property def encode(self) -> _Encoder: ... @property @@ -110,16 +115,16 @@ def iterdecode(iterator: Iterable[bytes], encoding: str, errors: str = ...) -> G if sys.version_info >= (3, 10): def unregister(__search_function: Callable[[str], CodecInfo | None]) -> None: ... -BOM: bytes -BOM_BE: bytes -BOM_LE: bytes -BOM_UTF8: bytes -BOM_UTF16: bytes -BOM_UTF16_BE: bytes -BOM_UTF16_LE: bytes -BOM_UTF32: bytes -BOM_UTF32_BE: bytes -BOM_UTF32_LE: bytes +BOM: Literal[b"\xff\xfe", b"\xfe\xff"] # depends on `sys.byteorder` +BOM_BE: Literal[b"\xfe\xff"] +BOM_LE: Literal[b"\xff\xfe"] +BOM_UTF8: Literal[b"\xef\xbb\xbf"] +BOM_UTF16: Literal[b"\xff\xfe", b"\xfe\xff"] # depends on `sys.byteorder` +BOM_UTF16_BE: Literal[b"\xfe\xff"] +BOM_UTF16_LE: Literal[b"\xff\xfe"] +BOM_UTF32: Literal[b"\xff\xfe\x00\x00", b"\x00\x00\xfe\xff"] # depends on `sys.byteorder` +BOM_UTF32_BE: Literal[b"\x00\x00\xfe\xff"] +BOM_UTF32_LE: Literal[b"\xff\xfe\x00\x00"] # It is expected that different actions be taken depending on which of the # three subclasses of `UnicodeError` is actually ...ed. However, the Union @@ -181,7 +186,7 @@ class StreamWriter(Codec): def writelines(self, list: Iterable[str]) -> None: ... def reset(self) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... class StreamReader(Codec): @@ -192,12 +197,10 @@ class StreamReader(Codec): def readlines(self, sizehint: int | None = ..., keepends: bool = ...) -> list[str]: ... def reset(self) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... def __iter__(self) -> Iterator[str]: ... def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... -_T = TypeVar("_T", bound=StreamReaderWriter) - # Doesn't actually inherit from TextIO, but wraps a BinaryIO to provide text reading and writing # and delegates attributes to the underlying binary stream with __getattr__. class StreamReaderWriter(TextIO): @@ -206,7 +209,7 @@ class StreamReaderWriter(TextIO): def readline(self, size: int | None = ...) -> str: ... def readlines(self, sizehint: int | None = ...) -> list[str]: ... def __next__(self) -> str: ... - def __iter__(self: _T) -> _T: ... + def __iter__(self: Self) -> Self: ... # This actually returns None, but that's incompatible with the supertype def write(self, data: str) -> int: ... def writelines(self, list: Iterable[str]) -> None: ... @@ -214,7 +217,7 @@ class StreamReaderWriter(TextIO): # Same as write() def seek(self, offset: int, whence: int = ...) -> int: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, typ: Type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None) -> None: ... def __getattr__(self, name: str) -> Any: ... # These methods don't actually exist directly, but they are needed to satisfy the TextIO # interface. At runtime, they are delegated through __getattr__. @@ -228,8 +231,6 @@ class StreamReaderWriter(TextIO): def tell(self) -> int: ... def writable(self) -> bool: ... -_SRT = TypeVar("_SRT", bound=StreamRecoder) - class StreamRecoder(BinaryIO): def __init__( self, @@ -244,13 +245,13 @@ class StreamRecoder(BinaryIO): def readline(self, size: int | None = ...) -> bytes: ... def readlines(self, sizehint: int | None = ...) -> list[bytes]: ... def __next__(self) -> bytes: ... - def __iter__(self: _SRT) -> _SRT: ... + def __iter__(self: Self) -> Self: ... def write(self, data: bytes) -> int: ... def writelines(self, list: Iterable[bytes]) -> int: ... # type: ignore # it's supposed to return None def reset(self) -> None: ... def __getattr__(self, name: str) -> Any: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, type: Type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... + def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... # These methods don't actually exist directly, but they are needed to satisfy the BinaryIO # interface. At runtime, they are delegated through __getattr__. def seek(self, offset: int, whence: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index 66a76941beee..32f996c6e0c5 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -1,8 +1,11 @@ import sys from _collections_abc import dict_items, dict_keys, dict_values -from _typeshed import Self -from typing import Any, Dict, Generic, NoReturn, Tuple, Type, TypeVar, overload -from typing_extensions import final +from _typeshed import Self, SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT +from typing import Any, Generic, NoReturn, TypeVar, overload +from typing_extensions import SupportsIndex, final + +if sys.version_info >= (3, 9): + from types import GenericAlias if sys.version_info >= (3, 10): from typing import Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Reversible, Sequence @@ -11,6 +14,8 @@ else: _S = TypeVar("_S") _T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") _KT = TypeVar("_KT") _VT = TypeVar("_VT") _KT_co = TypeVar("_KT_co", covariant=True) @@ -25,16 +30,26 @@ if sys.version_info >= (3, 7): rename: bool = ..., module: str | None = ..., defaults: Iterable[Any] | None = ..., - ) -> Type[Tuple[Any, ...]]: ... + ) -> type[tuple[Any, ...]]: ... else: def namedtuple( typename: str, field_names: str | Iterable[str], *, verbose: bool = ..., rename: bool = ..., module: str | None = ... - ) -> Type[Tuple[Any, ...]]: ... + ) -> type[tuple[Any, ...]]: ... -class UserDict(MutableMapping[_KT, _VT]): +class UserDict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): data: dict[_KT, _VT] - def __init__(self, __dict: Mapping[_KT, _VT] | None = ..., **kwargs: _VT) -> None: ... + # __init__ should be kept roughly in line with `dict.__init__`, which has the same semantics + @overload + def __init__(self: UserDict[_KT, _VT], __dict: None = ...) -> None: ... + @overload + def __init__(self: UserDict[str, _VT], __dict: None = ..., **kwargs: _VT) -> None: ... + @overload + def __init__(self, __dict: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, __iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + @overload + def __init__(self: UserDict[str, str], __iterable: Iterable[list[str]]) -> None: ... def __len__(self) -> int: ... def __getitem__(self, key: _KT) -> _VT: ... def __setitem__(self, key: _KT, item: _VT) -> None: ... @@ -42,41 +57,59 @@ class UserDict(MutableMapping[_KT, _VT]): def __iter__(self) -> Iterator[_KT]: ... def __contains__(self, key: object) -> bool: ... def copy(self: Self) -> Self: ... + # `UserDict.fromkeys` has the same semantics as `dict.fromkeys`, so should be kept in line with `dict.fromkeys`. + # TODO: Much like `dict.fromkeys`, the true signature of `UserDict.fromkeys` is inexpressible in the current type system. + # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963. + @classmethod + @overload + def fromkeys(cls, iterable: Iterable[_T], value: None = ...) -> UserDict[_T, Any | None]: ... @classmethod - def fromkeys(cls: Type[Self], iterable: Iterable[_KT], value: _VT | None = ...) -> Self: ... + @overload + def fromkeys(cls, iterable: Iterable[_T], value: _S) -> UserDict[_T, _S]: ... + if sys.version_info >= (3, 9): + def __or__(self, other: UserDict[_T1, _T2] | dict[_T1, _T2]) -> UserDict[_KT | _T1, _VT | _T2]: ... + def __ror__(self, other: UserDict[_T1, _T2] | dict[_T1, _T2]) -> UserDict[_KT | _T1, _VT | _T2]: ... # type: ignore[misc] + # UserDict.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self: Self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self: Self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... class UserList(MutableSequence[_T]): data: list[_T] def __init__(self, initlist: Iterable[_T] | None = ...) -> None: ... - def __lt__(self, other: object) -> bool: ... - def __le__(self, other: object) -> bool: ... - def __gt__(self, other: object) -> bool: ... - def __ge__(self, other: object) -> bool: ... + def __lt__(self, other: list[_T] | UserList[_T]) -> bool: ... + def __le__(self, other: list[_T] | UserList[_T]) -> bool: ... + def __gt__(self, other: list[_T] | UserList[_T]) -> bool: ... + def __ge__(self, other: list[_T] | UserList[_T]) -> bool: ... def __contains__(self, item: object) -> bool: ... def __len__(self) -> int: ... @overload - def __getitem__(self, i: int) -> _T: ... + def __getitem__(self, i: SupportsIndex) -> _T: ... @overload def __getitem__(self: Self, i: slice) -> Self: ... @overload - def __setitem__(self, i: int, o: _T) -> None: ... + def __setitem__(self, i: SupportsIndex, o: _T) -> None: ... @overload def __setitem__(self, i: slice, o: Iterable[_T]) -> None: ... - def __delitem__(self, i: int | slice) -> None: ... - def __add__(self: _S, other: Iterable[_T]) -> _S: ... - def __iadd__(self: _S, other: Iterable[_T]) -> _S: ... - def __mul__(self: _S, n: int) -> _S: ... - def __imul__(self: _S, n: int) -> _S: ... + def __delitem__(self, i: SupportsIndex | slice) -> None: ... + def __add__(self: Self, other: Iterable[_T]) -> Self: ... + def __iadd__(self: Self, other: Iterable[_T]) -> Self: ... + def __mul__(self: Self, n: int) -> Self: ... + def __imul__(self: Self, n: int) -> Self: ... def append(self, item: _T) -> None: ... def insert(self, i: int, item: _T) -> None: ... def pop(self, i: int = ...) -> _T: ... def remove(self, item: _T) -> None: ... - def clear(self) -> None: ... - def copy(self: _S) -> _S: ... + def copy(self: Self) -> Self: ... def count(self, item: _T) -> int: ... - def index(self, item: _T, *args: Any) -> int: ... - def reverse(self) -> None: ... - def sort(self, *args: Any, **kwds: Any) -> None: ... + # All arguments are passed to `list.index` at runtime, so the signature should be kept in line with `list.index`. + def index(self, item: _T, __start: SupportsIndex = ..., __stop: SupportsIndex = ...) -> int: ... + # All arguments are passed to `list.sort` at runtime, so the signature should be kept in line with `list.sort`. + @overload + def sort(self: UserList[SupportsRichComparisonT], *, key: None = ..., reverse: bool = ...) -> None: ... + @overload + def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> None: ... def extend(self, other: Iterable[_T]) -> None: ... _UserStringT = TypeVar("_UserStringT", bound=UserString) @@ -95,22 +128,22 @@ class UserString(Sequence[str]): def __contains__(self, char: object) -> bool: ... def __len__(self) -> int: ... # It should return a str to implement Sequence correctly, but it doesn't. - def __getitem__(self: _UserStringT, i: int | slice) -> _UserStringT: ... # type: ignore - def __iter__(self: _UserStringT) -> Iterator[_UserStringT]: ... # type: ignore - def __reversed__(self: _UserStringT) -> Iterator[_UserStringT]: ... # type: ignore - def __add__(self: _UserStringT, other: object) -> _UserStringT: ... - def __mul__(self: _UserStringT, n: int) -> _UserStringT: ... - def __mod__(self: _UserStringT, args: Any) -> _UserStringT: ... - def capitalize(self: _UserStringT) -> _UserStringT: ... - def casefold(self: _UserStringT) -> _UserStringT: ... - def center(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... + def __getitem__(self: Self, i: SupportsIndex | slice) -> Self: ... # type: ignore[override] + def __iter__(self: _UserStringT) -> Iterator[_UserStringT]: ... # type: ignore[override] + def __reversed__(self: _UserStringT) -> Iterator[_UserStringT]: ... # type: ignore[override] + def __add__(self: Self, other: object) -> Self: ... + def __mul__(self: Self, n: int) -> Self: ... + def __mod__(self: Self, args: Any) -> Self: ... + def capitalize(self: Self) -> Self: ... + def casefold(self: Self) -> Self: ... + def center(self: Self, width: int, *args: Any) -> Self: ... def count(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... if sys.version_info >= (3, 8): def encode(self: UserString, encoding: str | None = ..., errors: str | None = ...) -> bytes: ... else: - def encode(self: _UserStringT, encoding: str | None = ..., errors: str | None = ...) -> _UserStringT: ... - def endswith(self, suffix: str | Tuple[str, ...], start: int | None = ..., end: int | None = ...) -> bool: ... - def expandtabs(self: _UserStringT, tabsize: int = ...) -> _UserStringT: ... + def encode(self: Self, encoding: str | None = ..., errors: str | None = ...) -> Self: ... + def endswith(self, suffix: str | tuple[str, ...], start: int | None = ..., end: int | None = ...) -> bool: ... + def expandtabs(self: Self, tabsize: int = ...) -> Self: ... def find(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... def format(self, *args: Any, **kwds: Any) -> str: ... def format_map(self, mapping: Mapping[str, Any]) -> str: ... @@ -126,10 +159,12 @@ class UserString(Sequence[str]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... + if sys.version_info >= (3, 7): + def isascii(self) -> bool: ... def join(self, seq: Iterable[str]) -> str: ... - def ljust(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... - def lower(self: _UserStringT) -> _UserStringT: ... - def lstrip(self: _UserStringT, chars: str | None = ...) -> _UserStringT: ... + def ljust(self: Self, width: int, *args: Any) -> Self: ... + def lower(self: Self) -> Self: ... + def lstrip(self: Self, chars: str | None = ...) -> Self: ... @staticmethod @overload def maketrans(x: dict[int, _T] | dict[str, _T] | dict[str | int, _T]) -> dict[int, _T]: ... @@ -138,24 +173,24 @@ class UserString(Sequence[str]): def maketrans(x: str, y: str, z: str = ...) -> dict[int, int | None]: ... def partition(self, sep: str) -> tuple[str, str, str]: ... if sys.version_info >= (3, 9): - def removeprefix(self: _UserStringT, __prefix: str | UserString) -> _UserStringT: ... - def removesuffix(self: _UserStringT, __suffix: str | UserString) -> _UserStringT: ... - def replace(self: _UserStringT, old: str | UserString, new: str | UserString, maxsplit: int = ...) -> _UserStringT: ... + def removeprefix(self: Self, __prefix: str | UserString) -> Self: ... + def removesuffix(self: Self, __suffix: str | UserString) -> Self: ... + def replace(self: Self, old: str | UserString, new: str | UserString, maxsplit: int = ...) -> Self: ... def rfind(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... def rindex(self, sub: str | UserString, start: int = ..., end: int = ...) -> int: ... - def rjust(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... + def rjust(self: Self, width: int, *args: Any) -> Self: ... def rpartition(self, sep: str) -> tuple[str, str, str]: ... - def rstrip(self: _UserStringT, chars: str | None = ...) -> _UserStringT: ... + def rstrip(self: Self, chars: str | None = ...) -> Self: ... def split(self, sep: str | None = ..., maxsplit: int = ...) -> list[str]: ... def rsplit(self, sep: str | None = ..., maxsplit: int = ...) -> list[str]: ... def splitlines(self, keepends: bool = ...) -> list[str]: ... - def startswith(self, prefix: str | Tuple[str, ...], start: int | None = ..., end: int | None = ...) -> bool: ... - def strip(self: _UserStringT, chars: str | None = ...) -> _UserStringT: ... - def swapcase(self: _UserStringT) -> _UserStringT: ... - def title(self: _UserStringT) -> _UserStringT: ... - def translate(self: _UserStringT, *args: Any) -> _UserStringT: ... - def upper(self: _UserStringT) -> _UserStringT: ... - def zfill(self: _UserStringT, width: int) -> _UserStringT: ... + def startswith(self, prefix: str | tuple[str, ...], start: int | None = ..., end: int | None = ...) -> bool: ... + def strip(self: Self, chars: str | None = ...) -> Self: ... + def swapcase(self: Self) -> Self: ... + def title(self: Self) -> Self: ... + def translate(self: Self, *args: Any) -> Self: ... + def upper(self: Self) -> Self: ... + def zfill(self: Self, width: int) -> Self: ... class deque(MutableSequence[_T], Generic[_T]): @property @@ -163,56 +198,43 @@ class deque(MutableSequence[_T], Generic[_T]): def __init__(self, iterable: Iterable[_T] = ..., maxlen: int | None = ...) -> None: ... def append(self, __x: _T) -> None: ... def appendleft(self, __x: _T) -> None: ... - def clear(self) -> None: ... - def copy(self: _S) -> _S: ... + def copy(self: Self) -> Self: ... 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 pop(self) -> _T: ... # type: ignore[override] def popleft(self) -> _T: ... def remove(self, __value: _T) -> None: ... - def reverse(self) -> None: ... def rotate(self, __n: int = ...) -> None: ... - def __copy__(self: _S) -> _S: ... + def __copy__(self: Self) -> Self: ... 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: ... - @overload - def __getitem__(self, __s: slice) -> MutableSequence[_T]: ... - @overload - def __setitem__(self, __i: int, __x: _T) -> None: ... - @overload - def __setitem__(self, __s: slice, __o: Iterable[_T]) -> None: ... - @overload - def __delitem__(self, __i: int) -> None: ... - @overload - def __delitem__(self, __s: slice) -> None: ... + # These methods of deque don't take slices, unlike MutableSequence, hence the type: ignores + def __getitem__(self, __index: SupportsIndex) -> _T: ... # type: ignore[override] + def __setitem__(self, __i: SupportsIndex, __x: _T) -> None: ... # type: ignore[override] + def __delitem__(self, __i: SupportsIndex) -> None: ... # type: ignore[override] 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: _S, __other: _S) -> _S: ... - def __mul__(self: _S, __other: int) -> _S: ... - def __imul__(self: _S, __other: int) -> _S: ... + def __reduce__(self: Self) -> tuple[type[Self], tuple[()], None, Iterator[_T]]: ... + def __iadd__(self: Self, __iterable: Iterable[_T]) -> Self: ... + def __add__(self: Self, __other: Self) -> Self: ... + def __mul__(self: Self, __other: int) -> Self: ... + def __imul__(self: Self, __other: int) -> Self: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, __item: Any) -> GenericAlias: ... -class Counter(Dict[_T, int], Generic[_T]): +class Counter(dict[_T, int], Generic[_T]): @overload def __init__(self, __iterable: None = ..., **kwargs: int) -> None: ... @overload - def __init__(self, __mapping: Mapping[_T, int]) -> None: ... + def __init__(self, __mapping: SupportsKeysAndGetItem[_T, int]) -> None: ... @overload def __init__(self, __iterable: Iterable[_T]) -> None: ... def copy(self: Self) -> Self: ... def elements(self) -> Iterator[_T]: ... def most_common(self, n: int | None = ...) -> list[tuple[_T, int]]: ... @classmethod - def fromkeys(cls, iterable: Any, v: int | None = ...) -> NoReturn: ... # type: ignore + def fromkeys(cls, iterable: Any, v: int | None = ...) -> NoReturn: ... # type: ignore[override] @overload def subtract(self, __iterable: None = ...) -> None: ... @overload @@ -225,7 +247,7 @@ class Counter(Dict[_T, int], Generic[_T]): # Dict.update. Not sure if we should use '# type: ignore' instead # and omit the type from the union. @overload - def update(self, __m: Mapping[_T, int], **kwargs: int) -> None: ... + def update(self, __m: SupportsKeysAndGetItem[_T, int], **kwargs: int) -> None: ... @overload def update(self, __m: Iterable[_T] | Iterable[tuple[_T, int]], **kwargs: int) -> None: ... @overload @@ -233,27 +255,29 @@ class Counter(Dict[_T, int], Generic[_T]): def __add__(self, other: Counter[_T]) -> Counter[_T]: ... def __sub__(self, other: Counter[_T]) -> Counter[_T]: ... def __and__(self, other: Counter[_T]) -> Counter[_T]: ... - def __or__(self, other: Counter[_T]) -> Counter[_T]: ... # type: ignore + def __or__(self, other: Counter[_T]) -> Counter[_T]: ... # type: ignore[override] def __pos__(self) -> Counter[_T]: ... def __neg__(self) -> Counter[_T]: ... def __iadd__(self, other: Counter[_T]) -> Counter[_T]: ... def __isub__(self, other: Counter[_T]) -> Counter[_T]: ... def __iand__(self, other: Counter[_T]) -> Counter[_T]: ... - def __ior__(self, other: Counter[_T]) -> Counter[_T]: ... # type: ignore + def __ior__(self, other: Counter[_T]) -> Counter[_T]: ... # type: ignore[override] + if sys.version_info >= (3, 10): + def total(self) -> int: ... @final class _OrderedDictKeysView(dict_keys[_KT_co, _VT_co], Reversible[_KT_co]): # type: ignore[misc] def __reversed__(self) -> Iterator[_KT_co]: ... @final -class _OrderedDictItemsView(dict_items[_KT_co, _VT_co], Reversible[Tuple[_KT_co, _VT_co]]): # type: ignore[misc] +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]]: ... @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]): +class OrderedDict(dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): def popitem(self, last: bool = ...) -> tuple[_KT, _VT]: ... def move_to_end(self, key: _KT, last: bool = ...) -> None: ... def copy(self: Self) -> Self: ... @@ -261,8 +285,17 @@ class OrderedDict(Dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): def keys(self) -> _OrderedDictKeysView[_KT, _VT]: ... def items(self) -> _OrderedDictItemsView[_KT, _VT]: ... def values(self) -> _OrderedDictValuesView[_KT, _VT]: ... + # `fromkeys` is actually inherited from `dict` at runtime, so the signature should be kept in line with `dict.fromkeys`. + # Ideally we would not redefine it here, but the true signature of `dict.fromkeys` is not expressible in the current type system. + # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963. + @classmethod + @overload + def fromkeys(cls, __iterable: Iterable[_T], __value: None = ...) -> OrderedDict[_T, Any | None]: ... + @classmethod + @overload + def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> OrderedDict[_T, _S]: ... -class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): +class defaultdict(dict[_KT, _VT], Generic[_KT, _VT]): default_factory: Callable[[], _VT] | None @overload def __init__(self, **kwargs: _VT) -> None: ... @@ -271,9 +304,11 @@ class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): @overload 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: SupportsKeysAndGetItem[_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: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT + ) -> None: ... @overload def __init__(self, __default_factory: Callable[[], _VT] | None, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ... @overload @@ -281,8 +316,8 @@ class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): 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: ... + def __copy__(self: Self) -> Self: ... + def copy(self: Self) -> Self: ... class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): maps: list[MutableMapping[_KT, _VT]] @@ -301,3 +336,19 @@ class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def pop(self, key: _KT) -> _VT: ... @overload def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... + def copy(self: Self) -> Self: ... + # All arguments to `fromkeys` are passed to `dict.fromkeys` at runtime, so the signature should be kept in line with `dict.fromkeys`. + @classmethod + @overload + def fromkeys(cls, iterable: Iterable[_T], __value: None = ...) -> ChainMap[_T, Any | None]: ... + @classmethod + @overload + def fromkeys(cls, __iterable: Iterable[_T], __value: _S) -> ChainMap[_T, _S]: ... + if sys.version_info >= (3, 9): + def __or__(self, other: Mapping[_T1, _T2]) -> ChainMap[_KT | _T1, _VT | _T2]: ... + def __ror__(self, other: Mapping[_T1, _T2]) -> ChainMap[_KT | _T1, _VT | _T2]: ... + # ChainMap.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self: Self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self: Self, other: Iterable[tuple[_KT, _VT]]) -> Self: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi index fd7333420b39..9e2365b49481 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi @@ -4,19 +4,20 @@ from _typeshed import Self from abc import abstractmethod from collections.abc import Container, Iterable, Iterator, Sequence from logging import Logger -from typing import Any, Callable, Generic, Protocol, Set, TypeVar, overload +from typing import Any, Callable, Generic, Protocol, TypeVar, overload +from typing_extensions import Literal, ParamSpec, SupportsIndex if sys.version_info >= (3, 9): from types import GenericAlias -FIRST_COMPLETED: str -FIRST_EXCEPTION: str -ALL_COMPLETED: str -PENDING: str -RUNNING: str -CANCELLED: str -CANCELLED_AND_NOTIFIED: str -FINISHED: str +FIRST_COMPLETED: Literal["FIRST_COMPLETED"] +FIRST_EXCEPTION: Literal["FIRST_EXCEPTION"] +ALL_COMPLETED: Literal["ALL_COMPLETED"] +PENDING: Literal["PENDING"] +RUNNING: Literal["RUNNING"] +CANCELLED: Literal["CANCELLED"] +CANCELLED_AND_NOTIFIED: Literal["CANCELLED_AND_NOTIFIED"] +FINISHED: Literal["FINISHED"] _FUTURE_STATES: list[str] _STATE_TO_DESCRIPTION_MAP: dict[str, str] LOGGER: Logger @@ -32,8 +33,8 @@ if sys.version_info >= (3, 7): class BrokenExecutor(RuntimeError): ... _T = TypeVar("_T") - _T_co = TypeVar("_T_co", covariant=True) +_P = ParamSpec("_P") # Copied over Collection implementation as it does not exist in Python 2 and <3.6. # Also to solve pytype issues with _Collection. @@ -59,9 +60,9 @@ class Future(Generic[_T]): class Executor: if sys.version_info >= (3, 9): - def submit(self, __fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ... + def submit(self, __fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... else: - def submit(self, fn: Callable[..., _T], *args: Any, **kwargs: Any) -> Future[_T]: ... + def submit(self, fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ... def map( self, fn: Callable[..., _T], *iterables: Iterable[Any], timeout: float | None = ..., chunksize: int = ... ) -> Iterator[_T]: ... @@ -75,13 +76,13 @@ class Executor: def as_completed(fs: Iterable[Future[_T]], timeout: float | None = ...) -> Iterator[Future[_T]]: ... # Ideally this would be a namedtuple, but mypy doesn't support generic tuple types. See #1976 -class DoneAndNotDoneFutures(Sequence[Set[Future[_T]]]): +class DoneAndNotDoneFutures(Sequence[set[Future[_T]]]): done: set[Future[_T]] not_done: set[Future[_T]] def __new__(_cls, done: set[Future[_T]], not_done: set[Future[_T]]) -> DoneAndNotDoneFutures[_T]: ... def __len__(self) -> int: ... @overload - def __getitem__(self, i: int) -> set[Future[_T]]: ... + def __getitem__(self, i: SupportsIndex) -> set[Future[_T]]: ... @overload def __getitem__(self, s: slice) -> DoneAndNotDoneFutures[_T]: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/process.pyi b/mypy/typeshed/stdlib/concurrent/futures/process.pyi index cc48f48f0023..900c46e19f1c 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/process.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/process.pyi @@ -5,7 +5,7 @@ from multiprocessing.context import BaseContext, Process from multiprocessing.queues import Queue, SimpleQueue from threading import Lock, Semaphore, Thread from types import TracebackType -from typing import Any, Callable, Generic, Tuple, TypeVar +from typing import Any, Callable, Generic, TypeVar from weakref import ref from ._base import Executor, Future @@ -31,13 +31,12 @@ _MAX_WINDOWS_WORKERS: int class _RemoteTraceback(Exception): tb: str def __init__(self, tb: TracebackType) -> None: ... - def __str__(self) -> str: ... class _ExceptionWithTraceback: exc: BaseException tb: TracebackType def __init__(self, exc: BaseException, tb: TracebackType) -> None: ... - def __reduce__(self) -> str | Tuple[Any, ...]: ... + def __reduce__(self) -> str | tuple[Any, ...]: ... def _rebuild_exc(exc: Exception, tb: str) -> Exception: ... @@ -84,7 +83,7 @@ if sys.version_info >= (3, 7): ) -> None: ... def _on_queue_feeder_error(self, e: Exception, obj: _CallItem) -> None: ... -def _get_chunks(*iterables: Any, chunksize: int) -> Generator[Tuple[Any, ...], None, None]: ... +def _get_chunks(*iterables: Any, chunksize: int) -> Generator[tuple[Any, ...], None, None]: ... def _process_chunk(fn: Callable[..., Any], chunk: tuple[Any, None, None]) -> Generator[Any, None, None]: ... def _sendback_result( result_queue: SimpleQueue[_WorkItem[Any]], work_id: int, result: Any | None = ..., exception: Exception | None = ... @@ -95,7 +94,7 @@ if sys.version_info >= (3, 7): call_queue: Queue[_CallItem], result_queue: SimpleQueue[_ResultItem], initializer: Callable[..., None] | None, - initargs: Tuple[Any, ...], + initargs: tuple[Any, ...], ) -> None: ... else: @@ -139,7 +138,7 @@ else: class ProcessPoolExecutor(Executor): _mp_context: BaseContext | None = ... _initializer: Callable[..., None] | None = ... - _initargs: Tuple[Any, ...] = ... + _initargs: tuple[Any, ...] = ... _executor_manager_thread: _ThreadWakeup _processes: MutableMapping[int, Process] _shutdown_thread: bool @@ -158,7 +157,7 @@ class ProcessPoolExecutor(Executor): max_workers: int | None = ..., mp_context: BaseContext | None = ..., initializer: Callable[..., None] | None = ..., - initargs: Tuple[Any, ...] = ..., + initargs: tuple[Any, ...] = ..., ) -> None: ... else: def __init__(self, max_workers: int | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi index 5ad5b65d3bec..f27c43c3403c 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/thread.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/thread.pyi @@ -1,8 +1,8 @@ import queue import sys -from collections.abc import Iterable, Mapping, Set # equivalent to typing.AbstractSet, not builtins.set +from collections.abc import Iterable, Mapping, Set as AbstractSet from threading import Lock, Semaphore, Thread -from typing import Any, Callable, Generic, Tuple, TypeVar +from typing import Any, Callable, Generic, TypeVar from weakref import ref from ._base import Executor, Future @@ -33,7 +33,7 @@ if sys.version_info >= (3, 7): executor_reference: ref[Any], work_queue: queue.SimpleQueue[Any], initializer: Callable[..., None], - initargs: Tuple[Any, ...], + initargs: tuple[Any, ...], ) -> None: ... else: @@ -46,13 +46,13 @@ if sys.version_info >= (3, 7): class ThreadPoolExecutor(Executor): _max_workers: int _idle_semaphore: Semaphore - _threads: Set[Thread] + _threads: AbstractSet[Thread] _broken: bool _shutdown: bool _shutdown_lock: Lock _thread_name_prefix: str | None = ... _initializer: Callable[..., None] | None = ... - _initargs: Tuple[Any, ...] = ... + _initargs: tuple[Any, ...] = ... if sys.version_info >= (3, 7): _work_queue: queue.SimpleQueue[_WorkItem[Any]] else: @@ -63,7 +63,7 @@ class ThreadPoolExecutor(Executor): max_workers: int | None = ..., thread_name_prefix: str = ..., initializer: Callable[..., None] | None = ..., - initargs: Tuple[Any, ...] = ..., + initargs: tuple[Any, ...] = ..., ) -> None: ... else: def __init__(self, max_workers: int | None = ..., thread_name_prefix: str = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/configparser.pyi b/mypy/typeshed/stdlib/configparser.pyi index a0efa30416dd..7dfbe77c725f 100644 --- a/mypy/typeshed/stdlib/configparser.pyi +++ b/mypy/typeshed/stdlib/configparser.pyi @@ -1,14 +1,14 @@ import sys from _typeshed import StrOrBytesPath, StrPath, SupportsWrite from collections.abc import Callable, ItemsView, Iterable, Iterator, Mapping, MutableMapping, Sequence -from typing import Any, ClassVar, Dict, Optional, Pattern, Type, TypeVar, overload +from typing import Any, ClassVar, Optional, Pattern, TypeVar, overload from typing_extensions import Literal # Internal type aliases _section = Mapping[str, str] _parser = MutableMapping[str, _section] _converter = Callable[[str], Any] -_converters = Dict[str, _converter] +_converters = dict[str, _converter] _T = TypeVar("_T") if sys.version_info >= (3, 7): @@ -16,8 +16,8 @@ if sys.version_info >= (3, 7): else: _Path = StrPath -DEFAULTSECT: str -MAX_INTERPOLATION_DEPTH: int +DEFAULTSECT: Literal["DEFAULT"] +MAX_INTERPOLATION_DEPTH: Literal[10] class Interpolation: def before_get(self, parser: _parser, section: str, option: str, value: str, defaults: _section) -> str: ... @@ -47,7 +47,7 @@ class RawConfigParser(_parser): def __init__( self, defaults: Mapping[str, str | None] | None = ..., - dict_type: Type[Mapping[str, str]] = ..., + dict_type: type[Mapping[str, str]] = ..., allow_no_value: Literal[True] = ..., *, delimiters: Sequence[str] = ..., @@ -63,7 +63,7 @@ class RawConfigParser(_parser): def __init__( self, defaults: _section | None = ..., - dict_type: Type[Mapping[str, str]] = ..., + dict_type: type[Mapping[str, str]] = ..., allow_no_value: bool = ..., *, delimiters: Sequence[str] = ..., @@ -122,7 +122,7 @@ class RawConfigParser(_parser): fallback: _T = ..., ) -> _T: ... # This is incompatible with MutableMapping so we ignore the type - @overload # type: ignore + @overload # type: ignore[override] def get(self, section: str, option: str, *, raw: bool = ..., vars: _section | None = ...) -> str: ... @overload def get(self, section: str, option: str, *, raw: bool = ..., vars: _section | None = ..., fallback: _T) -> str | _T: ... @@ -137,7 +137,9 @@ class RawConfigParser(_parser): def optionxform(self, optionstr: str) -> str: ... class ConfigParser(RawConfigParser): ... -class SafeConfigParser(ConfigParser): ... + +if sys.version_info < (3, 11): + class SafeConfigParser(ConfigParser): ... class SectionProxy(MutableMapping[str, str]): def __init__(self, parser: RawConfigParser, name: str) -> None: ... @@ -151,7 +153,16 @@ class SectionProxy(MutableMapping[str, str]): def parser(self) -> RawConfigParser: ... @property def name(self) -> str: ... - def get(self, option: str, fallback: str | None = ..., *, raw: bool = ..., vars: _section | None = ..., _impl: Any | None = ..., **kwargs: Any) -> str: ... # type: ignore + def get( # type: ignore[override] + self, + option: str, + fallback: str | None = ..., + *, + raw: bool = ..., + vars: _section | None = ..., + _impl: Any | None = ..., + **kwargs: Any, + ) -> str: ... # These are partially-applied version of the methods with the same names in # RawConfigParser; the stubs should be kept updated together @overload diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index 9d968e092ca5..9164227fa92a 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -1,25 +1,27 @@ import sys from _typeshed import Self, StrOrBytesPath from types import TracebackType -from typing import ( +from typing import ( # noqa Y027 IO, Any, + AsyncGenerator, AsyncIterator, Awaitable, Callable, ContextManager, + Generator, Generic, Iterator, Optional, - Type, + Protocol, TypeVar, overload, ) -from typing_extensions import ParamSpec, Protocol +from typing_extensions import ParamSpec AbstractContextManager = ContextManager if sys.version_info >= (3, 7): - from typing import AsyncContextManager + from typing import AsyncContextManager # noqa Y022 AbstractAsyncContextManager = AsyncContextManager @@ -29,17 +31,47 @@ _T_io = TypeVar("_T_io", bound=Optional[IO[str]]) _F = TypeVar("_F", bound=Callable[..., Any]) _P = ParamSpec("_P") -_ExitFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], bool] +_ExitFunc = Callable[[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]], bool] _CM_EF = TypeVar("_CM_EF", AbstractContextManager[Any], _ExitFunc) -class _GeneratorContextManager(AbstractContextManager[_T_co]): +class ContextDecorator: def __call__(self, func: _F) -> _F: ... -# type ignore to deal with incomplete ParamSpec support in mypy -def contextmanager(func: Callable[_P, Iterator[_T]]) -> Callable[_P, _GeneratorContextManager[_T]]: ... # type: ignore +class _GeneratorContextManager(AbstractContextManager[_T_co], ContextDecorator, Generic[_T_co]): + # In Python <= 3.6, __init__ and all instance attributes are defined directly on this class. + # In Python >= 3.7, __init__ and all instance attributes are inherited from _GeneratorContextManagerBase + # _GeneratorContextManagerBase is more trouble than it's worth to include in the stub; see #6676 + def __init__(self, func: Callable[..., Iterator[_T_co]], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ... + gen: Generator[_T_co, Any, Any] + func: Callable[..., Generator[_T_co, Any, Any]] + args: tuple[Any, ...] + kwds: dict[str, Any] + +def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ... + +if sys.version_info >= (3, 10): + _AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]]) + class AsyncContextDecorator: + def __call__(self, func: _AF) -> _AF: ... + class _AsyncGeneratorContextManager(AbstractAsyncContextManager[_T_co], AsyncContextDecorator, Generic[_T_co]): + # __init__ and these attributes are actually defined in the base class _GeneratorContextManagerBase, + # which is more trouble than it's worth to include in the stub (see #6676) + def __init__(self, func: Callable[..., AsyncIterator[_T_co]], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ... + gen: AsyncGenerator[_T_co, Any] + func: Callable[..., AsyncGenerator[_T_co, Any]] + args: tuple[Any, ...] + kwds: dict[str, Any] + +elif sys.version_info >= (3, 7): + class _AsyncGeneratorContextManager(AbstractAsyncContextManager[_T_co], Generic[_T_co]): + def __init__(self, func: Callable[..., AsyncIterator[_T_co]], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ... + gen: AsyncGenerator[_T_co, Any] + func: Callable[..., AsyncGenerator[_T_co, Any]] + args: tuple[Any, ...] + kwds: dict[str, Any] if sys.version_info >= (3, 7): - def asynccontextmanager(func: Callable[_P, AsyncIterator[_T]]) -> Callable[_P, AbstractAsyncContextManager[_T]]: ... # type: ignore + def asynccontextmanager(func: Callable[_P, AsyncIterator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ... class _SupportsClose(Protocol): def close(self) -> object: ... @@ -55,14 +87,11 @@ if sys.version_info >= (3, 10): _SupportsAcloseT = TypeVar("_SupportsAcloseT", bound=_SupportsAclose) class aclosing(AbstractAsyncContextManager[_SupportsAcloseT]): def __init__(self, thing: _SupportsAcloseT) -> None: ... - _AF = TypeVar("_AF", bound=Callable[..., Awaitable[Any]]) - class AsyncContextDecorator: - def __call__(self, func: _AF) -> _AF: ... class suppress(AbstractContextManager[None]): - def __init__(self, *exceptions: Type[BaseException]) -> None: ... + def __init__(self, *exceptions: type[BaseException]) -> None: ... def __exit__( - self, exctype: Type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None + self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None ) -> bool: ... class redirect_stdout(AbstractContextManager[_T_io]): @@ -71,9 +100,6 @@ class redirect_stdout(AbstractContextManager[_T_io]): class redirect_stderr(AbstractContextManager[_T_io]): def __init__(self, new_target: _T_io) -> None: ... -class ContextDecorator: - def __call__(self, func: _F) -> _F: ... - class ExitStack(AbstractContextManager[ExitStack]): def __init__(self) -> None: ... def enter_context(self, cm: AbstractContextManager[_T]) -> _T: ... @@ -83,11 +109,11 @@ class ExitStack(AbstractContextManager[ExitStack]): def close(self) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None + self, __exc_type: type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None ) -> bool: ... if sys.version_info >= (3, 7): - _ExitCoroFunc = Callable[[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]], Awaitable[bool]] + _ExitCoroFunc = Callable[[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]], Awaitable[bool]] _CallbackCoroFunc = Callable[..., Awaitable[Any]] _ACM_EF = TypeVar("_ACM_EF", AbstractAsyncContextManager[Any], _ExitCoroFunc) class AsyncExitStack(AbstractAsyncContextManager[AsyncExitStack]): @@ -102,7 +128,7 @@ if sys.version_info >= (3, 7): def aclose(self) -> Awaitable[None]: ... def __aenter__(self: Self) -> Awaitable[Self]: ... def __aexit__( - self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None + self, __exc_type: type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None ) -> Awaitable[bool]: ... if sys.version_info >= (3, 10): diff --git a/mypy/typeshed/stdlib/contextvars.pyi b/mypy/typeshed/stdlib/contextvars.pyi index e97f62188dcb..d1c8ee08b1ad 100644 --- a/mypy/typeshed/stdlib/contextvars.pyi +++ b/mypy/typeshed/stdlib/contextvars.pyi @@ -1,12 +1,15 @@ import sys from typing import Any, Callable, ClassVar, Generic, Iterator, Mapping, TypeVar, overload +from typing_extensions import ParamSpec, final if sys.version_info >= (3, 9): from types import GenericAlias _T = TypeVar("_T") _D = TypeVar("_D") +_P = ParamSpec("_P") +@final class ContextVar(Generic[_T]): def __init__(self, name: str, *, default: _T = ...) -> None: ... @property @@ -20,6 +23,7 @@ class ContextVar(Generic[_T]): if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... +@final class Token(Generic[_T]): @property def var(self) -> ContextVar[_T]: ... @@ -33,14 +37,15 @@ def copy_context() -> Context: ... # It doesn't make sense to make this generic, because for most Contexts each ContextVar will have # a different value. +@final class Context(Mapping[ContextVar[Any], Any]): def __init__(self) -> None: ... @overload - def get(self, __key: ContextVar[Any]) -> Any | None: ... + def get(self, __key: ContextVar[_T]) -> _T | None: ... @overload - def get(self, __key: ContextVar[Any], __default: Any | None) -> Any: ... - def run(self, callable: Callable[..., _T], *args: Any, **kwargs: Any) -> _T: ... + def get(self, __key: ContextVar[_T], __default: _D) -> _T | _D: ... + def run(self, callable: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> _T: ... def copy(self) -> Context: ... - def __getitem__(self, key: ContextVar[Any]) -> Any: ... + def __getitem__(self, key: ContextVar[_T]) -> _T: ... def __iter__(self) -> Iterator[ContextVar[Any]]: ... def __len__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/copyreg.pyi b/mypy/typeshed/stdlib/copyreg.pyi index 320097b3a204..6097670833c0 100644 --- a/mypy/typeshed/stdlib/copyreg.pyi +++ b/mypy/typeshed/stdlib/copyreg.pyi @@ -1,7 +1,7 @@ -from typing import Any, Callable, Hashable, Optional, SupportsInt, Tuple, TypeVar, Union +from typing import Any, Callable, Hashable, Optional, SupportsInt, TypeVar, Union _TypeT = TypeVar("_TypeT", bound=type) -_Reduce = Union[Tuple[Callable[..., _TypeT], Tuple[Any, ...]], Tuple[Callable[..., _TypeT], Tuple[Any, ...], Optional[Any]]] +_Reduce = Union[tuple[Callable[..., _TypeT], tuple[Any, ...]], tuple[Callable[..., _TypeT], tuple[Any, ...], Optional[Any]]] __all__: list[str] diff --git a/mypy/typeshed/stdlib/crypt.pyi b/mypy/typeshed/stdlib/crypt.pyi index 27e30433f702..a8342859e770 100644 --- a/mypy/typeshed/stdlib/crypt.pyi +++ b/mypy/typeshed/stdlib/crypt.pyi @@ -1,20 +1,18 @@ import sys -class _Method: ... +if sys.platform != "win32": + class _Method: ... + METHOD_CRYPT: _Method + METHOD_MD5: _Method + METHOD_SHA256: _Method + METHOD_SHA512: _Method + if sys.version_info >= (3, 7): + METHOD_BLOWFISH: _Method -METHOD_CRYPT: _Method -METHOD_MD5: _Method -METHOD_SHA256: _Method -METHOD_SHA512: _Method -if sys.version_info >= (3, 7): - METHOD_BLOWFISH: _Method + methods: list[_Method] -methods: list[_Method] - -if sys.version_info >= (3, 7): - def mksalt(method: _Method | None = ..., *, rounds: int | None = ...) -> str: ... - -else: - def mksalt(method: _Method | None = ...) -> str: ... - -def crypt(word: str, salt: str | _Method | None = ...) -> str: ... + if sys.version_info >= (3, 7): + def mksalt(method: _Method | None = ..., *, rounds: int | None = ...) -> str: ... + else: + def mksalt(method: _Method | None = ...) -> str: ... + def crypt(word: str, salt: str | _Method | None = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi index 0b69cb2272d3..13dd603d04a2 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi @@ -18,10 +18,10 @@ from _csv import ( writer as writer, ) from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence -from typing import Any, Generic, Type, TypeVar, overload +from typing import Any, Generic, TypeVar, overload if sys.version_info >= (3, 8): - from typing import Dict as _DictReadMapping + from builtins import dict as _DictReadMapping else: from collections import OrderedDict as _DictReadMapping @@ -100,8 +100,8 @@ class DictWriter(Generic[_T]): def writerow(self, rowdict: Mapping[_T, Any]) -> Any: ... def writerows(self, rowdicts: Iterable[Mapping[_T, Any]]) -> None: ... -class Sniffer(object): +class Sniffer: preferred: list[str] def __init__(self) -> None: ... - def sniff(self, sample: str, delimiters: str | None = ...) -> Type[Dialect]: ... + def sniff(self, sample: str, delimiters: str | None = ...) -> type[Dialect]: ... def has_header(self, sample: str) -> bool: ... diff --git a/mypy/typeshed/stdlib/ctypes/__init__.pyi b/mypy/typeshed/stdlib/ctypes/__init__.pyi index bbe083f5d4c4..00e1e25cf0b7 100644 --- a/mypy/typeshed/stdlib/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/ctypes/__init__.pyi @@ -1,5 +1,6 @@ import sys -from _typeshed import ReadableBuffer, WriteableBuffer +from _typeshed import ReadableBuffer, Self, WriteableBuffer +from abc import abstractmethod from typing import ( Any, Callable, @@ -10,8 +11,6 @@ from typing import ( Mapping, Optional, Sequence, - Tuple, - Type, TypeVar, Union as _UnionT, overload, @@ -28,12 +27,12 @@ RTLD_GLOBAL: int RTLD_LOCAL: int DEFAULT_MODE: int -class CDLL(object): +class CDLL: _func_flags_: ClassVar[int] _func_restype_: ClassVar[_CData] _name: str _handle: int - _FuncPtr: Type[_FuncPointer] + _FuncPtr: type[_FuncPointer] if sys.version_info >= (3, 8): def __init__( self, @@ -58,7 +57,7 @@ if sys.platform == "win32": class PyDLL(CDLL): ... class LibraryLoader(Generic[_DLLT]): - def __init__(self, dlltype: Type[_DLLT]) -> None: ... + def __init__(self, dlltype: type[_DLLT]) -> None: ... def __getattr__(self, name: str) -> _DLLT: ... def __getitem__(self, name: str) -> _DLLT: ... def LoadLibrary(self, name: str) -> _DLLT: ... @@ -76,42 +75,42 @@ class _CDataMeta(type): # By default mypy complains about the following two methods, because strictly speaking cls # might not be a Type[_CT]. However this can never actually happen, because the only class that # uses _CDataMeta as its metaclass is _CData. So it's safe to ignore the errors here. - def __mul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore - def __rmul__(cls: Type[_CT], other: int) -> Type[Array[_CT]]: ... # type: ignore + def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] + def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] class _CData(metaclass=_CDataMeta): _b_base: int _b_needsfree_: bool _objects: Mapping[Any, int] | None @classmethod - def from_buffer(cls: Type[_CT], source: WriteableBuffer, offset: int = ...) -> _CT: ... + def from_buffer(cls: type[Self], source: WriteableBuffer, offset: int = ...) -> Self: ... @classmethod - def from_buffer_copy(cls: Type[_CT], source: ReadableBuffer, offset: int = ...) -> _CT: ... + def from_buffer_copy(cls: type[Self], source: ReadableBuffer, offset: int = ...) -> Self: ... @classmethod - def from_address(cls: Type[_CT], address: int) -> _CT: ... + def from_address(cls: type[Self], address: int) -> Self: ... @classmethod - def from_param(cls: Type[_CT], obj: Any) -> _CT | _CArgObject: ... + def from_param(cls: type[Self], obj: Any) -> Self | _CArgObject: ... @classmethod - def in_dll(cls: Type[_CT], library: CDLL, name: str) -> _CT: ... + def in_dll(cls: type[Self], library: CDLL, name: str) -> Self: ... class _CanCastTo(_CData): ... class _PointerLike(_CanCastTo): ... -_ECT = Callable[[Optional[Type[_CData]], _FuncPointer, Tuple[_CData, ...]], _CData] -_PF = _UnionT[Tuple[int], Tuple[int, str], Tuple[int, str, Any]] +_ECT = Callable[[Optional[type[_CData]], _FuncPointer, tuple[_CData, ...]], _CData] +_PF = _UnionT[tuple[int], tuple[int, str], tuple[int, str, Any]] class _FuncPointer(_PointerLike, _CData): - restype: Type[_CData] | Callable[[int], Any] | None - argtypes: Sequence[Type[_CData]] + restype: type[_CData] | Callable[[int], Any] | None + argtypes: Sequence[type[_CData]] errcheck: _ECT @overload def __init__(self, address: int) -> None: ... @overload def __init__(self, callable: Callable[..., Any]) -> None: ... @overload - def __init__(self, func_spec: tuple[str | int, CDLL], paramflags: Tuple[_PF, ...] = ...) -> None: ... + def __init__(self, func_spec: tuple[str | int, CDLL], paramflags: tuple[_PF, ...] = ...) -> None: ... @overload - def __init__(self, vtlb_index: int, name: str, paramflags: Tuple[_PF, ...] = ..., iid: pointer[c_int] = ...) -> None: ... + def __init__(self, vtlb_index: int, name: str, paramflags: tuple[_PF, ...] = ..., iid: pointer[c_int] = ...) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... class _NamedFuncPointer(_FuncPointer): @@ -120,15 +119,15 @@ class _NamedFuncPointer(_FuncPointer): class ArgumentError(Exception): ... def CFUNCTYPE( - restype: Type[_CData] | None, *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ... -) -> Type[_FuncPointer]: ... + restype: type[_CData] | None, *argtypes: type[_CData], use_errno: bool = ..., use_last_error: bool = ... +) -> type[_FuncPointer]: ... if sys.platform == "win32": def WINFUNCTYPE( - restype: Type[_CData] | None, *argtypes: Type[_CData], use_errno: bool = ..., use_last_error: bool = ... - ) -> Type[_FuncPointer]: ... + restype: type[_CData] | None, *argtypes: type[_CData], use_errno: bool = ..., use_last_error: bool = ... + ) -> type[_FuncPointer]: ... -def PYFUNCTYPE(restype: Type[_CData] | None, *argtypes: Type[_CData]) -> Type[_FuncPointer]: ... +def PYFUNCTYPE(restype: type[_CData] | None, *argtypes: type[_CData]) -> type[_FuncPointer]: ... class _CArgObject: ... @@ -142,12 +141,12 @@ _CVoidPLike = _UnionT[_PointerLike, Array[Any], _CArgObject, int] _CVoidConstPLike = _UnionT[_CVoidPLike, bytes] def addressof(obj: _CData) -> int: ... -def alignment(obj_or_type: _CData | Type[_CData]) -> int: ... +def alignment(obj_or_type: _CData | type[_CData]) -> int: ... def byref(obj: _CData, offset: int = ...) -> _CArgObject: ... _CastT = TypeVar("_CastT", bound=_CanCastTo) -def cast(obj: _CData | _CArgObject | int, typ: Type[_CastT]) -> _CastT: ... +def cast(obj: _CData | _CArgObject | int, typ: type[_CastT]) -> _CastT: ... def create_string_buffer(init: int | bytes, size: int | None = ...) -> Array[c_char]: ... c_buffer = create_string_buffer @@ -157,7 +156,7 @@ def create_unicode_buffer(init: int | str, size: int | None = ...) -> Array[c_wc if sys.platform == "win32": def DllCanUnloadNow() -> int: ... def DllGetClassObject(rclsid: Any, riid: Any, ppv: Any) -> int: ... # TODO not documented - def FormatError(code: int) -> str: ... + def FormatError(code: int = ...) -> str: ... def GetLastError() -> int: ... def get_errno() -> int: ... @@ -167,13 +166,13 @@ if sys.platform == "win32": def memmove(dst: _CVoidPLike, src: _CVoidConstPLike, count: int) -> None: ... def memset(dst: _CVoidPLike, c: int, count: int) -> None: ... -def POINTER(type: Type[_CT]) -> Type[pointer[_CT]]: ... +def POINTER(type: type[_CT]) -> type[pointer[_CT]]: ... # The real ctypes.pointer is a function, not a class. The stub version of pointer behaves like # ctypes._Pointer in that it is the base class for all pointer types. Unlike the real _Pointer, # it can be instantiated directly (to mimic the behavior of the real pointer function). class pointer(Generic[_CT], _PointerLike, _CData): - _type_: Type[_CT] + _type_: type[_CT] contents: _CT def __init__(self, arg: _CT = ...) -> None: ... @overload @@ -191,7 +190,7 @@ def set_errno(value: int) -> int: ... if sys.platform == "win32": def set_last_error(value: int) -> int: ... -def sizeof(obj_or_type: _CData | Type[_CData]) -> int: ... +def sizeof(obj_or_type: _CData | type[_CData]) -> int: ... def string_at(address: _CVoidConstPLike, size: int = ...) -> bytes: ... if sys.platform == "win32": @@ -252,7 +251,7 @@ class _CField: size: int class _StructUnionMeta(_CDataMeta): - _fields_: Sequence[tuple[str, Type[_CData]] | tuple[str, Type[_CData], int]] + _fields_: Sequence[tuple[str, type[_CData]] | tuple[str, type[_CData], int]] _pack_: int _anonymous_: Sequence[str] def __getattr__(self, name: str) -> _CField: ... @@ -268,8 +267,16 @@ class BigEndianStructure(Structure): ... class LittleEndianStructure(Structure): ... class Array(Generic[_CT], _CData): - _length_: int - _type_: Type[_CT] + @property + @abstractmethod + def _length_(self) -> int: ... + @_length_.setter + def _length_(self, value: int) -> None: ... + @property + @abstractmethod + def _type_(self) -> type[_CT]: ... + @_type_.setter + def _type_(self, value: type[_CT]) -> None: ... raw: bytes # Note: only available if _CT == c_char value: Any # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise # TODO These methods cannot be annotated correctly at the moment. diff --git a/mypy/typeshed/stdlib/curses/__init__.pyi b/mypy/typeshed/stdlib/curses/__init__.pyi index 73e84fba3763..aef2d9b95ed5 100644 --- a/mypy/typeshed/stdlib/curses/__init__.pyi +++ b/mypy/typeshed/stdlib/curses/__init__.pyi @@ -1,15 +1,17 @@ -from _curses import * # noqa: F403 -from _curses import _CursesWindow as _CursesWindow +import sys from typing import Any, Callable, TypeVar -_T = TypeVar("_T") +if sys.platform != "win32": + from _curses import * # noqa: F403 + from _curses import _CursesWindow as _CursesWindow -# available after calling `curses.initscr()` -LINES: int -COLS: int + _T = TypeVar("_T") -# available after calling `curses.start_color()` -COLORS: int -COLOR_PAIRS: int + # available after calling `curses.initscr()` + LINES: int + COLS: int -def wrapper(__func: Callable[..., _T], *arg: Any, **kwds: Any) -> _T: ... + # available after calling `curses.start_color()` + COLORS: int + COLOR_PAIRS: int + def wrapper(__func: Callable[..., _T], *arg: Any, **kwds: Any) -> _T: ... diff --git a/mypy/typeshed/stdlib/curses/ascii.pyi b/mypy/typeshed/stdlib/curses/ascii.pyi index 66efbe36a7df..25de8f605bda 100644 --- a/mypy/typeshed/stdlib/curses/ascii.pyi +++ b/mypy/typeshed/stdlib/curses/ascii.pyi @@ -1,62 +1,63 @@ +import sys from typing import TypeVar -_CharT = TypeVar("_CharT", str, int) +if sys.platform != "win32": + _CharT = TypeVar("_CharT", str, int) -NUL: int -SOH: int -STX: int -ETX: int -EOT: int -ENQ: int -ACK: int -BEL: int -BS: int -TAB: int -HT: int -LF: int -NL: int -VT: int -FF: int -CR: int -SO: int -SI: int -DLE: int -DC1: int -DC2: int -DC3: int -DC4: int -NAK: int -SYN: int -ETB: int -CAN: int -EM: int -SUB: int -ESC: int -FS: int -GS: int -RS: int -US: int -SP: int -DEL: int + NUL: int + SOH: int + STX: int + ETX: int + EOT: int + ENQ: int + ACK: int + BEL: int + BS: int + TAB: int + HT: int + LF: int + NL: int + VT: int + FF: int + CR: int + SO: int + SI: int + DLE: int + DC1: int + DC2: int + DC3: int + DC4: int + NAK: int + SYN: int + ETB: int + CAN: int + EM: int + SUB: int + ESC: int + FS: int + GS: int + RS: int + US: int + SP: int + DEL: int -controlnames: list[int] - -def isalnum(c: str | int) -> bool: ... -def isalpha(c: str | int) -> bool: ... -def isascii(c: str | int) -> bool: ... -def isblank(c: str | int) -> bool: ... -def iscntrl(c: str | int) -> bool: ... -def isdigit(c: str | int) -> bool: ... -def isgraph(c: str | int) -> bool: ... -def islower(c: str | int) -> bool: ... -def isprint(c: str | int) -> bool: ... -def ispunct(c: str | int) -> bool: ... -def isspace(c: str | int) -> bool: ... -def isupper(c: str | int) -> bool: ... -def isxdigit(c: str | int) -> bool: ... -def isctrl(c: str | int) -> bool: ... -def ismeta(c: str | int) -> bool: ... -def ascii(c: _CharT) -> _CharT: ... -def ctrl(c: _CharT) -> _CharT: ... -def alt(c: _CharT) -> _CharT: ... -def unctrl(c: str | int) -> str: ... + controlnames: list[int] + def isalnum(c: str | int) -> bool: ... + def isalpha(c: str | int) -> bool: ... + def isascii(c: str | int) -> bool: ... + def isblank(c: str | int) -> bool: ... + def iscntrl(c: str | int) -> bool: ... + def isdigit(c: str | int) -> bool: ... + def isgraph(c: str | int) -> bool: ... + def islower(c: str | int) -> bool: ... + def isprint(c: str | int) -> bool: ... + def ispunct(c: str | int) -> bool: ... + def isspace(c: str | int) -> bool: ... + def isupper(c: str | int) -> bool: ... + def isxdigit(c: str | int) -> bool: ... + def isctrl(c: str | int) -> bool: ... + def ismeta(c: str | int) -> bool: ... + def ascii(c: _CharT) -> _CharT: ... + def ctrl(c: _CharT) -> _CharT: ... + def alt(c: _CharT) -> _CharT: ... + def unctrl(c: str | int) -> str: ... diff --git a/mypy/typeshed/stdlib/curses/panel.pyi b/mypy/typeshed/stdlib/curses/panel.pyi index 138e4a9f727e..ed13a6e050e9 100644 --- a/mypy/typeshed/stdlib/curses/panel.pyi +++ b/mypy/typeshed/stdlib/curses/panel.pyi @@ -1,20 +1,23 @@ -from _curses import _CursesWindow +import sys -class _Curses_Panel: # type is (note the space in the class name) - def above(self) -> _Curses_Panel: ... - def below(self) -> _Curses_Panel: ... - def bottom(self) -> None: ... - def hidden(self) -> bool: ... - def hide(self) -> None: ... - def move(self, y: int, x: int) -> None: ... - def replace(self, win: _CursesWindow) -> None: ... - def set_userptr(self, obj: object) -> None: ... - def show(self) -> None: ... - def top(self) -> None: ... - def userptr(self) -> object: ... - def window(self) -> _CursesWindow: ... +if sys.platform != "win32": + from _curses import _CursesWindow -def bottom_panel() -> _Curses_Panel: ... -def new_panel(__win: _CursesWindow) -> _Curses_Panel: ... -def top_panel() -> _Curses_Panel: ... -def update_panels() -> _Curses_Panel: ... + version: str + class _Curses_Panel: # type is (note the space in the class name) + def above(self) -> _Curses_Panel: ... + def below(self) -> _Curses_Panel: ... + def bottom(self) -> None: ... + def hidden(self) -> bool: ... + def hide(self) -> None: ... + def move(self, y: int, x: int) -> None: ... + def replace(self, win: _CursesWindow) -> None: ... + def set_userptr(self, obj: object) -> None: ... + def show(self) -> None: ... + def top(self) -> None: ... + def userptr(self) -> object: ... + def window(self) -> _CursesWindow: ... + def bottom_panel() -> _Curses_Panel: ... + def new_panel(__win: _CursesWindow) -> _Curses_Panel: ... + def top_panel() -> _Curses_Panel: ... + def update_panels() -> _Curses_Panel: ... diff --git a/mypy/typeshed/stdlib/curses/textpad.pyi b/mypy/typeshed/stdlib/curses/textpad.pyi index 578a579fda38..eb6879603853 100644 --- a/mypy/typeshed/stdlib/curses/textpad.pyi +++ b/mypy/typeshed/stdlib/curses/textpad.pyi @@ -1,11 +1,12 @@ -from _curses import _CursesWindow +import sys from typing import Callable -def rectangle(win: _CursesWindow, uly: int, ulx: int, lry: int, lrx: int) -> None: ... - -class Textbox: - stripspaces: bool - def __init__(self, win: _CursesWindow, insert_mode: bool = ...) -> None: ... - def edit(self, validate: Callable[[int], int] | None = ...) -> str: ... - def do_command(self, ch: str | int) -> None: ... - def gather(self) -> str: ... +if sys.platform != "win32": + from _curses import _CursesWindow + def rectangle(win: _CursesWindow, uly: int, ulx: int, lry: int, lrx: int) -> None: ... + class Textbox: + stripspaces: bool + def __init__(self, win: _CursesWindow, insert_mode: bool = ...) -> None: ... + def edit(self, validate: Callable[[int], int] | None = ...) -> str: ... + def do_command(self, ch: str | int) -> None: ... + def gather(self) -> str: ... diff --git a/mypy/typeshed/stdlib/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index 59efbe77aed6..0678bd3845ae 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -1,7 +1,7 @@ import sys import types -from typing import Any, Callable, Generic, Iterable, Mapping, Tuple, Type, TypeVar, overload -from typing_extensions import Protocol +from builtins import type as Type # alias to avoid name clashes with fields named "type" +from typing import Any, Callable, Generic, Iterable, Mapping, Protocol, TypeVar, overload if sys.version_info >= (3, 9): from types import GenericAlias @@ -21,15 +21,15 @@ def asdict(obj: Any) -> dict[str, Any]: ... @overload def asdict(obj: Any, *, dict_factory: Callable[[list[tuple[str, Any]]], _T]) -> _T: ... @overload -def astuple(obj: Any) -> Tuple[Any, ...]: ... +def astuple(obj: Any) -> tuple[Any, ...]: ... @overload def astuple(obj: Any, *, tuple_factory: Callable[[list[Any]], _T]) -> _T: ... if sys.version_info >= (3, 10): @overload - def dataclass(__cls: Type[_T]) -> Type[_T]: ... + def dataclass(__cls: type[_T]) -> type[_T]: ... @overload - def dataclass(__cls: None) -> Callable[[Type[_T]], Type[_T]]: ... + def dataclass(__cls: None) -> Callable[[type[_T]], type[_T]]: ... @overload def dataclass( *, @@ -42,28 +42,28 @@ if sys.version_info >= (3, 10): match_args: bool = ..., kw_only: bool = ..., slots: bool = ..., - ) -> Callable[[Type[_T]], Type[_T]]: ... + ) -> Callable[[type[_T]], type[_T]]: ... elif sys.version_info >= (3, 8): # cls argument is now positional-only @overload - def dataclass(__cls: Type[_T]) -> Type[_T]: ... + def dataclass(__cls: type[_T]) -> type[_T]: ... @overload - def dataclass(__cls: None) -> Callable[[Type[_T]], Type[_T]]: ... + def dataclass(__cls: None) -> Callable[[type[_T]], type[_T]]: ... @overload def dataclass( *, init: bool = ..., repr: bool = ..., eq: bool = ..., order: bool = ..., unsafe_hash: bool = ..., frozen: bool = ... - ) -> Callable[[Type[_T]], Type[_T]]: ... + ) -> Callable[[type[_T]], type[_T]]: ... else: @overload - def dataclass(_cls: Type[_T]) -> Type[_T]: ... + def dataclass(_cls: type[_T]) -> type[_T]: ... @overload - def dataclass(_cls: None) -> Callable[[Type[_T]], Type[_T]]: ... + def dataclass(_cls: None) -> Callable[[type[_T]], type[_T]]: ... @overload def dataclass( *, init: bool = ..., repr: bool = ..., eq: bool = ..., order: bool = ..., unsafe_hash: bool = ..., frozen: bool = ... - ) -> Callable[[Type[_T]], Type[_T]]: ... + ) -> Callable[[type[_T]], type[_T]]: ... # See https://github.com/python/mypy/issues/10750 class _DefaultFactory(Protocol[_T_co]): @@ -173,7 +173,7 @@ else: metadata: Mapping[Any, Any] | None = ..., ) -> Any: ... -def fields(class_or_instance: Any) -> Tuple[Field[Any], ...]: ... +def fields(class_or_instance: Any) -> tuple[Field[Any], ...]: ... def is_dataclass(obj: Any) -> bool: ... class FrozenInstanceError(AttributeError): ... @@ -192,7 +192,7 @@ if sys.version_info >= (3, 10): cls_name: str, fields: Iterable[str | tuple[str, type] | tuple[str, type, Field[Any]]], *, - bases: Tuple[type, ...] = ..., + bases: tuple[type, ...] = ..., namespace: dict[str, Any] | None = ..., init: bool = ..., repr: bool = ..., @@ -201,6 +201,7 @@ if sys.version_info >= (3, 10): unsafe_hash: bool = ..., frozen: bool = ..., match_args: bool = ..., + kw_only: bool = ..., slots: bool = ..., ) -> type: ... @@ -209,7 +210,7 @@ else: cls_name: str, fields: Iterable[str | tuple[str, type] | tuple[str, type, Field[Any]]], *, - bases: Tuple[type, ...] = ..., + bases: tuple[type, ...] = ..., namespace: dict[str, Any] | None = ..., init: bool = ..., repr: bool = ..., diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index bd4d47e051ec..2c6a06739cf3 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -1,13 +1,13 @@ import sys +from _typeshed import Self from time import struct_time -from typing import ClassVar, NamedTuple, NoReturn, SupportsAbs, Type, TypeVar, overload -from typing_extensions import final +from typing import ClassVar, NamedTuple, NoReturn, SupportsAbs, TypeVar, overload +from typing_extensions import Literal, final -_S = TypeVar("_S") _D = TypeVar("_D", bound=date) -MINYEAR: int -MAXYEAR: int +MINYEAR: Literal[1] +MAXYEAR: Literal[9999] class tzinfo: def tzname(self, __dt: datetime | None) -> str | None: ... @@ -36,19 +36,19 @@ class date: min: ClassVar[date] max: ClassVar[date] resolution: ClassVar[timedelta] - def __new__(cls: Type[_S], year: int, month: int, day: int) -> _S: ... + def __new__(cls: type[Self], year: int, month: int, day: int) -> Self: ... @classmethod - def fromtimestamp(cls: Type[_S], __timestamp: float) -> _S: ... + def fromtimestamp(cls: type[Self], __timestamp: float) -> Self: ... @classmethod - def today(cls: Type[_S]) -> _S: ... + def today(cls: type[Self]) -> Self: ... @classmethod - def fromordinal(cls: Type[_S], __n: int) -> _S: ... + def fromordinal(cls: type[Self], __n: int) -> Self: ... if sys.version_info >= (3, 7): @classmethod - def fromisoformat(cls: Type[_S], __date_string: str) -> _S: ... + def fromisoformat(cls: type[Self], __date_string: str) -> Self: ... if sys.version_info >= (3, 8): @classmethod - def fromisocalendar(cls: Type[_S], year: int, week: int, day: int) -> _S: ... + def fromisocalendar(cls: type[Self], year: int, week: int, day: int) -> Self: ... @property def year(self) -> int: ... @property @@ -56,7 +56,7 @@ class date: @property def day(self) -> int: ... def ctime(self) -> str: ... - def strftime(self, fmt: str) -> str: ... + def strftime(self, __format: str) -> str: ... def __format__(self, __fmt: str) -> str: ... def isoformat(self) -> str: ... def timetuple(self) -> struct_time: ... @@ -67,10 +67,10 @@ class date: def __ge__(self, __other: date) -> bool: ... def __gt__(self, __other: date) -> bool: ... if sys.version_info >= (3, 8): - def __add__(self: _S, __other: timedelta) -> _S: ... - def __radd__(self: _S, __other: timedelta) -> _S: ... + def __add__(self: Self, __other: timedelta) -> Self: ... + def __radd__(self: Self, __other: timedelta) -> Self: ... @overload - def __sub__(self: _D, __other: timedelta) -> _D: ... + def __sub__(self: Self, __other: timedelta) -> Self: ... @overload def __sub__(self, __other: datetime) -> NoReturn: ... @overload @@ -98,7 +98,7 @@ class time: max: ClassVar[time] resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], + cls: type[Self], hour: int = ..., minute: int = ..., second: int = ..., @@ -106,7 +106,7 @@ class time: tzinfo: _tzinfo | None = ..., *, fold: int = ..., - ) -> _S: ... + ) -> Self: ... @property def hour(self) -> int: ... @property @@ -127,8 +127,8 @@ class time: def isoformat(self, timespec: str = ...) -> str: ... if sys.version_info >= (3, 7): @classmethod - def fromisoformat(cls: Type[_S], __time_string: str) -> _S: ... - def strftime(self, fmt: str) -> str: ... + def fromisoformat(cls: type[Self], __time_string: str) -> Self: ... + def strftime(self, __format: str) -> str: ... def __format__(self, __fmt: str) -> str: ... def utcoffset(self) -> timedelta | None: ... def tzname(self) -> str | None: ... @@ -152,7 +152,7 @@ class timedelta(SupportsAbs[timedelta]): max: ClassVar[timedelta] resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], + cls: type[Self], days: float = ..., seconds: float = ..., microseconds: float = ..., @@ -160,7 +160,7 @@ class timedelta(SupportsAbs[timedelta]): minutes: float = ..., hours: float = ..., weeks: float = ..., - ) -> _S: ... + ) -> Self: ... @property def days(self) -> int: ... @property @@ -199,7 +199,7 @@ class datetime(date): max: ClassVar[datetime] resolution: ClassVar[timedelta] def __new__( - cls: Type[_S], + cls: type[Self], year: int, month: int, day: int, @@ -210,7 +210,7 @@ class datetime(date): tzinfo: _tzinfo | None = ..., *, fold: int = ..., - ) -> _S: ... + ) -> Self: ... @property def hour(self) -> int: ... @property @@ -227,26 +227,26 @@ class datetime(date): # but it is named "timestamp" in the C implementation and "t" in the Python implementation, # so it is only truly *safe* to pass it as a positional argument. @classmethod - def fromtimestamp(cls: Type[_S], __timestamp: float, tz: _tzinfo | None = ...) -> _S: ... + def fromtimestamp(cls: type[Self], __timestamp: float, tz: _tzinfo | None = ...) -> Self: ... @classmethod - def utcfromtimestamp(cls: Type[_S], __t: float) -> _S: ... + def utcfromtimestamp(cls: type[Self], __t: float) -> Self: ... if sys.version_info >= (3, 8): @classmethod - def now(cls: Type[_S], tz: _tzinfo | None = ...) -> _S: ... + def now(cls: type[Self], tz: _tzinfo | None = ...) -> Self: ... else: @overload @classmethod - def now(cls: Type[_S], tz: None = ...) -> _S: ... + def now(cls: type[Self], tz: None = ...) -> Self: ... @overload @classmethod def now(cls, tz: _tzinfo) -> datetime: ... @classmethod - def utcnow(cls: Type[_S]) -> _S: ... + def utcnow(cls: type[Self]) -> Self: ... @classmethod def combine(cls, date: _date, time: _time, tzinfo: _tzinfo | None = ...) -> datetime: ... if sys.version_info >= (3, 7): @classmethod - def fromisoformat(cls: Type[_S], __date_string: str) -> _S: ... + def fromisoformat(cls: type[Self], __date_string: str) -> Self: ... def timestamp(self) -> float: ... def utctimetuple(self) -> struct_time: ... def date(self) -> _date: ... @@ -266,7 +266,7 @@ class datetime(date): fold: int = ..., ) -> datetime: ... if sys.version_info >= (3, 8): - def astimezone(self: _S, tz: _tzinfo | None = ...) -> _S: ... + def astimezone(self: Self, tz: _tzinfo | None = ...) -> Self: ... else: def astimezone(self, tz: _tzinfo | None = ...) -> datetime: ... def ctime(self) -> str: ... @@ -276,13 +276,13 @@ class datetime(date): def utcoffset(self) -> timedelta | None: ... def tzname(self) -> str | None: ... def dst(self) -> timedelta | None: ... - def __le__(self, __other: datetime) -> bool: ... # type: ignore - def __lt__(self, __other: datetime) -> bool: ... # type: ignore - def __ge__(self, __other: datetime) -> bool: ... # type: ignore - def __gt__(self, __other: datetime) -> bool: ... # type: ignore + def __le__(self, __other: datetime) -> bool: ... # type: ignore[override] + def __lt__(self, __other: datetime) -> bool: ... # type: ignore[override] + def __ge__(self, __other: datetime) -> bool: ... # type: ignore[override] + def __gt__(self, __other: datetime) -> bool: ... # type: ignore[override] if sys.version_info >= (3, 8): @overload # type: ignore[override] - def __sub__(self: _D, __other: timedelta) -> _D: ... + def __sub__(self: Self, __other: timedelta) -> Self: ... @overload def __sub__(self: _D, __other: _D) -> timedelta: ... else: diff --git a/mypy/typeshed/stdlib/dbm/__init__.pyi b/mypy/typeshed/stdlib/dbm/__init__.pyi index 9b9f92ccaa86..7947e6e20016 100644 --- a/mypy/typeshed/stdlib/dbm/__init__.pyi +++ b/mypy/typeshed/stdlib/dbm/__init__.pyi @@ -1,6 +1,6 @@ from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Tuple, Type, Union +from typing import Iterator, MutableMapping, Union from typing_extensions import Literal _KeyType = Union[str, bytes] @@ -82,12 +82,12 @@ class _Database(MutableMapping[_KeyType, bytes]): def __del__(self) -> 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: ... class _error(Exception): ... -error = Tuple[Type[_error], Type[OSError]] +error: tuple[type[_error], type[OSError]] def whichdb(filename: str) -> str: ... def open(file: str, flag: _TFlags = ..., mode: int = ...) -> _Database: ... diff --git a/mypy/typeshed/stdlib/dbm/dumb.pyi b/mypy/typeshed/stdlib/dbm/dumb.pyi index 0a941b070754..e040f23ce2b0 100644 --- a/mypy/typeshed/stdlib/dbm/dumb.pyi +++ b/mypy/typeshed/stdlib/dbm/dumb.pyi @@ -1,6 +1,6 @@ from _typeshed import Self from types import TracebackType -from typing import Iterator, MutableMapping, Type, Union +from typing import Iterator, MutableMapping, Union _KeyType = Union[str, bytes] _ValueType = Union[str, bytes] @@ -20,7 +20,7 @@ class _Database(MutableMapping[_KeyType, bytes]): def __del__(self) -> 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 open(file: str, flag: str = ..., mode: int = ...) -> _Database: ... diff --git a/mypy/typeshed/stdlib/dbm/gnu.pyi b/mypy/typeshed/stdlib/dbm/gnu.pyi index 7cec827e8992..ef4706b97f74 100644 --- a/mypy/typeshed/stdlib/dbm/gnu.pyi +++ b/mypy/typeshed/stdlib/dbm/gnu.pyi @@ -1,11 +1,13 @@ from _typeshed import Self from types import TracebackType -from typing import Type, TypeVar, Union, overload +from typing import TypeVar, Union, overload _T = TypeVar("_T") _KeyType = Union[str, bytes] _ValueType = Union[str, bytes] +open_flags: str + class error(OSError): ... # Actual typename gdbm, not exposed by the implementation @@ -22,7 +24,7 @@ class _gdbm: def __len__(self) -> int: ... 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: ... @overload def get(self, k: _KeyType) -> bytes | None: ... @@ -31,7 +33,7 @@ class _gdbm: def keys(self) -> list[bytes]: ... def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... # Don't exist at runtime - __new__: None # type: ignore - __init__: None # type: ignore + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] def open(__filename: str, __flags: str = ..., __mode: int = ...) -> _gdbm: ... diff --git a/mypy/typeshed/stdlib/dbm/ndbm.pyi b/mypy/typeshed/stdlib/dbm/ndbm.pyi index a4b35a309dbd..c49ad82c53d4 100644 --- a/mypy/typeshed/stdlib/dbm/ndbm.pyi +++ b/mypy/typeshed/stdlib/dbm/ndbm.pyi @@ -1,6 +1,6 @@ from _typeshed import Self from types import TracebackType -from typing import Type, TypeVar, Union, overload +from typing import TypeVar, Union, overload _T = TypeVar("_T") _KeyType = Union[str, bytes] @@ -20,7 +20,7 @@ class _dbm: def __del__(self) -> 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: ... @overload def get(self, k: _KeyType) -> bytes | None: ... @@ -29,7 +29,7 @@ class _dbm: def keys(self) -> list[bytes]: ... def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ... # Don't exist at runtime - __new__: None # type: ignore - __init__: None # type: ignore + __new__: None # type: ignore[assignment] + __init__: None # type: ignore[assignment] def open(__filename: str, __flags: str = ..., __mode: int = ...) -> _dbm: ... diff --git a/mypy/typeshed/stdlib/decimal.pyi b/mypy/typeshed/stdlib/decimal.pyi index 30c8e973348d..a7fe060a4132 100644 --- a/mypy/typeshed/stdlib/decimal.pyi +++ b/mypy/typeshed/stdlib/decimal.pyi @@ -1,15 +1,16 @@ import numbers +import sys +from _typeshed import Self from types import TracebackType -from typing import Any, Container, NamedTuple, Sequence, Tuple, Type, TypeVar, Union, overload +from typing import Any, Container, NamedTuple, Sequence, Union, overload _Decimal = Union[Decimal, int] -_DecimalNew = Union[Decimal, float, str, Tuple[int, Sequence[int], int]] +_DecimalNew = Union[Decimal, float, str, tuple[int, Sequence[int], int]] _ComparableNum = Union[Decimal, float, numbers.Rational] -_DecimalT = TypeVar("_DecimalT", bound=Decimal) class DecimalTuple(NamedTuple): sign: int - digits: Tuple[int, ...] + digits: tuple[int, ...] exponent: int ROUND_DOWN: str @@ -21,6 +22,8 @@ ROUND_UP: str ROUND_HALF_DOWN: str ROUND_05UP: str +if sys.version_info >= (3, 7): + HAVE_CONTEXTVAR: bool HAVE_THREADS: bool MAX_EMAX: int MAX_PREC: int @@ -46,8 +49,8 @@ def setcontext(__context: Context) -> None: ... def getcontext() -> Context: ... def localcontext(ctx: Context | None = ...) -> _ContextManager: ... -class Decimal(object): - def __new__(cls: Type[_DecimalT], value: _DecimalNew = ..., context: Context | None = ...) -> _DecimalT: ... +class Decimal: + def __new__(cls: type[Self], value: _DecimalNew = ..., context: Context | None = ...) -> Self: ... @classmethod def from_float(cls, __f: float) -> Decimal: ... def __bool__(self) -> bool: ... @@ -77,7 +80,6 @@ class Decimal(object): 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 remainder_near(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... @@ -143,21 +145,21 @@ class Decimal(object): def rotate(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def scaleb(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... def shift(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __reduce__(self) -> tuple[Type[Decimal], tuple[str]]: ... + 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: ... -class _ContextManager(object): +class _ContextManager: new_context: Context saved_context: Context def __init__(self, new_context: Context) -> None: ... def __enter__(self) -> Context: ... - def __exit__(self, t: Type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... -_TrapType = Type[DecimalException] +_TrapType = type[DecimalException] -class Context(object): +class Context: prec: int rounding: str Emin: int @@ -181,7 +183,7 @@ class Context(object): # __setattr__() only allows to set a specific set of attributes, # already defined above. def __delattr__(self, __name: str) -> None: ... - def __reduce__(self) -> tuple[Type[Context], Tuple[Any, ...]]: ... + def __reduce__(self) -> tuple[type[Context], tuple[Any, ...]]: ... def clear_flags(self) -> None: ... def clear_traps(self) -> None: ... def copy(self) -> Context: ... diff --git a/mypy/typeshed/stdlib/difflib.pyi b/mypy/typeshed/stdlib/difflib.pyi index 7c4ae8e2f246..ad96aa1c94e2 100644 --- a/mypy/typeshed/stdlib/difflib.pyi +++ b/mypy/typeshed/stdlib/difflib.pyi @@ -1,11 +1,10 @@ import sys -from typing import Any, AnyStr, Callable, Generic, Iterable, Iterator, NamedTuple, Sequence, TypeVar, Union, overload +from typing import Any, AnyStr, Callable, Generic, Iterable, Iterator, NamedTuple, Sequence, TypeVar, overload if sys.version_info >= (3, 9): from types import GenericAlias _T = TypeVar("_T") -_JunkCallback = Union[Callable[[str], bool], Callable[[str], bool]] class Match(NamedTuple): a: int @@ -34,16 +33,14 @@ class SequenceMatcher(Generic[_T]): # mypy thinks the signatures of the overloads overlap, but the types still work fine @overload -def get_close_matches( # type: ignore - word: AnyStr, possibilities: Iterable[AnyStr], n: int = ..., cutoff: float = ... -) -> list[AnyStr]: ... +def get_close_matches(word: AnyStr, possibilities: Iterable[AnyStr], n: int = ..., cutoff: float = ...) -> list[AnyStr]: ... # type: ignore[misc] @overload def get_close_matches( word: Sequence[_T], possibilities: Iterable[Sequence[_T]], n: int = ..., cutoff: float = ... ) -> list[Sequence[_T]]: ... class Differ: - def __init__(self, linejunk: _JunkCallback | None = ..., charjunk: _JunkCallback | None = ...) -> None: ... + def __init__(self, linejunk: Callable[[str], bool] | None = ..., charjunk: Callable[[str], bool] | None = ...) -> None: ... def compare(self, a: Sequence[str], b: Sequence[str]) -> Iterator[str]: ... def IS_LINE_JUNK(line: str, pat: Any = ...) -> bool: ... # pat is undocumented @@ -69,16 +66,16 @@ def context_diff( lineterm: str = ..., ) -> Iterator[str]: ... def ndiff( - a: Sequence[str], b: Sequence[str], linejunk: _JunkCallback | None = ..., charjunk: _JunkCallback | None = ... + a: Sequence[str], b: Sequence[str], linejunk: Callable[[str], bool] | None = ..., charjunk: Callable[[str], bool] | None = ... ) -> Iterator[str]: ... -class HtmlDiff(object): +class HtmlDiff: def __init__( self, tabsize: int = ..., wrapcolumn: int | None = ..., - linejunk: _JunkCallback | None = ..., - charjunk: _JunkCallback | None = ..., + linejunk: Callable[[str], bool] | None = ..., + charjunk: Callable[[str], bool] | None = ..., ) -> None: ... def make_file( self, diff --git a/mypy/typeshed/stdlib/dis.pyi b/mypy/typeshed/stdlib/dis.pyi index a6ea3e950b95..8c423a424431 100644 --- a/mypy/typeshed/stdlib/dis.pyi +++ b/mypy/typeshed/stdlib/dis.pyi @@ -1,27 +1,40 @@ import sys import types -from opcode import ( - EXTENDED_ARG as EXTENDED_ARG, - HAVE_ARGUMENT as HAVE_ARGUMENT, - cmp_op as cmp_op, - hascompare as hascompare, - hasconst as hasconst, - hasfree as hasfree, - hasjabs as hasjabs, - hasjrel as hasjrel, - haslocal as haslocal, - hasname as hasname, - hasnargs as hasnargs, - opmap as opmap, - opname as opname, - stack_effect as stack_effect, -) +from opcode import * # `dis` re-exports it as a part of public API from typing import IO, Any, Callable, Iterator, NamedTuple, Union +__all__ = [ + "code_info", + "dis", + "disassemble", + "distb", + "disco", + "findlinestarts", + "findlabels", + "show_code", + "get_instructions", + "Instruction", + "Bytecode", + "cmp_op", + "hasconst", + "hasname", + "hasjrel", + "hasjabs", + "haslocal", + "hascompare", + "hasfree", + "opname", + "opmap", + "HAVE_ARGUMENT", + "EXTENDED_ARG", + "hasnargs", + "stack_effect", +] + # Strictly this should not have to include Callable, but mypy doesn't use FunctionType # for functions (python/mypy#3171) -_have_code = Union[types.MethodType, types.FunctionType, types.CodeType, type, Callable[..., Any]] -_have_code_or_string = Union[_have_code, str, bytes] +_HaveCodeType = Union[types.MethodType, types.FunctionType, types.CodeType, type, Callable[..., Any]] +_HaveCodeOrStringType = Union[_HaveCodeType, str, bytes] class Instruction(NamedTuple): opname: str @@ -36,9 +49,8 @@ class Instruction(NamedTuple): class Bytecode: codeobj: types.CodeType first_line: int - def __init__(self, x: _have_code_or_string, *, first_line: int | None = ..., current_offset: int | None = ...) -> None: ... + def __init__(self, x: _HaveCodeOrStringType, *, first_line: int | None = ..., current_offset: int | None = ...) -> None: ... def __iter__(self) -> Iterator[Instruction]: ... - def __repr__(self) -> str: ... def info(self) -> str: ... def dis(self) -> str: ... @classmethod @@ -46,19 +58,19 @@ class Bytecode: COMPILER_FLAG_NAMES: dict[int, str] -def findlabels(code: _have_code) -> list[int]: ... -def findlinestarts(code: _have_code) -> Iterator[tuple[int, int]]: ... +def findlabels(code: _HaveCodeType) -> list[int]: ... +def findlinestarts(code: _HaveCodeType) -> Iterator[tuple[int, int]]: ... def pretty_flags(flags: int) -> str: ... -def code_info(x: _have_code_or_string) -> str: ... +def code_info(x: _HaveCodeOrStringType) -> str: ... if sys.version_info >= (3, 7): - def dis(x: _have_code_or_string | None = ..., *, file: IO[str] | None = ..., depth: int | None = ...) -> None: ... + def dis(x: _HaveCodeOrStringType | None = ..., *, file: IO[str] | None = ..., depth: int | None = ...) -> None: ... else: - def dis(x: _have_code_or_string | None = ..., *, file: IO[str] | None = ...) -> None: ... + def dis(x: _HaveCodeOrStringType | None = ..., *, file: IO[str] | None = ...) -> None: ... def distb(tb: types.TracebackType | None = ..., *, file: IO[str] | None = ...) -> None: ... -def disassemble(co: _have_code, lasti: int = ..., *, file: IO[str] | None = ...) -> None: ... -def disco(co: _have_code, lasti: int = ..., *, file: IO[str] | None = ...) -> None: ... -def show_code(co: _have_code, *, file: IO[str] | None = ...) -> None: ... -def get_instructions(x: _have_code, *, first_line: int | None = ...) -> Iterator[Instruction]: ... +def disassemble(co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ...) -> None: ... +def disco(co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ...) -> None: ... +def show_code(co: _HaveCodeType, *, file: IO[str] | None = ...) -> None: ... +def get_instructions(x: _HaveCodeType, *, first_line: int | None = ...) -> Iterator[Instruction]: ... diff --git a/mypy/typeshed/stdlib/distutils/ccompiler.pyi b/mypy/typeshed/stdlib/distutils/ccompiler.pyi index d21de4691503..7c7023ed0b65 100644 --- a/mypy/typeshed/stdlib/distutils/ccompiler.pyi +++ b/mypy/typeshed/stdlib/distutils/ccompiler.pyi @@ -1,6 +1,6 @@ -from typing import Any, Callable, Optional, Tuple, Union +from typing import Any, Callable, Optional, Union -_Macro = Union[Tuple[str], Tuple[str, Optional[str]]] +_Macro = Union[tuple[str], tuple[str, Optional[str]]] def gen_lib_options( compiler: CCompiler, library_dirs: list[str], runtime_library_dirs: list[str], libraries: list[str] @@ -141,7 +141,7 @@ class CCompiler: def library_filename(self, libname: str, lib_type: str = ..., strip_dir: int = ..., output_dir: str = ...) -> str: ... def object_filenames(self, source_filenames: list[str], strip_dir: int = ..., output_dir: str = ...) -> list[str]: ... def shared_object_filename(self, basename: str, strip_dir: int = ..., output_dir: str = ...) -> str: ... - def execute(self, func: Callable[..., None], args: Tuple[Any, ...], msg: str | None = ..., level: int = ...) -> None: ... + def execute(self, func: Callable[..., None], args: tuple[Any, ...], msg: str | None = ..., level: int = ...) -> None: ... def spawn(self, cmd: list[str]) -> None: ... def mkpath(self, name: str, mode: int = ...) -> None: ... def move_file(self, src: str, dst: str) -> str: ... diff --git a/mypy/typeshed/stdlib/distutils/command/__init__.pyi b/mypy/typeshed/stdlib/distutils/command/__init__.pyi index e69de29bb2d1..a4b9b1c2bd1b 100644 --- a/mypy/typeshed/stdlib/distutils/command/__init__.pyi +++ b/mypy/typeshed/stdlib/distutils/command/__init__.pyi @@ -0,0 +1,40 @@ +from . import ( + bdist_dumb as bdist_dumb, + bdist_rpm as bdist_rpm, + build as build, + build_clib as build_clib, + build_ext as build_ext, + build_py as build_py, + build_scripts as build_scripts, + check as check, + clean as clean, + install as install, + install_data as install_data, + install_headers as install_headers, + install_lib as install_lib, + register as register, + sdist as sdist, + upload as upload, +) + +__all__ = [ + "build", + "build_py", + "build_ext", + "build_clib", + "build_scripts", + "clean", + "install", + "install_lib", + "install_headers", + "install_scripts", + "install_data", + "sdist", + "register", + "bdist", + "bdist_dumb", + "bdist_rpm", + "bdist_wininst", + "check", + "upload", +] diff --git a/mypy/typeshed/stdlib/distutils/command/check.pyi b/mypy/typeshed/stdlib/distutils/command/check.pyi index 9149b540f715..36895d2c16f1 100644 --- a/mypy/typeshed/stdlib/distutils/command/check.pyi +++ b/mypy/typeshed/stdlib/distutils/command/check.pyi @@ -5,7 +5,7 @@ from ..cmd import Command _Reporter = Any # really docutils.utils.Reporter # Only defined if docutils is installed. -class SilentReporter(_Reporter): # type: ignore +class SilentReporter(_Reporter): messages: Any def __init__( self, diff --git a/mypy/typeshed/stdlib/distutils/command/install.pyi b/mypy/typeshed/stdlib/distutils/command/install.pyi index 47fa8b08d1b2..661d256e6f07 100644 --- a/mypy/typeshed/stdlib/distutils/command/install.pyi +++ b/mypy/typeshed/stdlib/distutils/command/install.pyi @@ -1,9 +1,9 @@ -from typing import Any, Tuple +from typing import Any from ..cmd import Command HAS_USER_SITE: bool -SCHEME_KEYS: Tuple[str, ...] +SCHEME_KEYS: tuple[str, ...] INSTALL_SCHEMES: dict[str, dict[Any, Any]] class install(Command): diff --git a/mypy/typeshed/stdlib/distutils/core.pyi b/mypy/typeshed/stdlib/distutils/core.pyi index fc4cd81c4752..6564c9a86ded 100644 --- a/mypy/typeshed/stdlib/distutils/core.pyi +++ b/mypy/typeshed/stdlib/distutils/core.pyi @@ -1,7 +1,7 @@ from distutils.cmd import Command as Command from distutils.dist import Distribution as Distribution from distutils.extension import Extension as Extension -from typing import Any, Mapping, Type +from typing import Any, Mapping def setup( *, @@ -20,14 +20,14 @@ def setup( scripts: list[str] = ..., ext_modules: list[Extension] = ..., classifiers: list[str] = ..., - distclass: Type[Distribution] = ..., + distclass: type[Distribution] = ..., script_name: str = ..., script_args: list[str] = ..., options: Mapping[str, Any] = ..., license: str = ..., keywords: list[str] | str = ..., platforms: list[str] | str = ..., - cmdclass: Mapping[str, Type[Command]] = ..., + cmdclass: Mapping[str, type[Command]] = ..., data_files: list[tuple[str, list[str]]] = ..., package_dir: Mapping[str, str] = ..., obsoletes: list[str] = ..., diff --git a/mypy/typeshed/stdlib/distutils/dist.pyi b/mypy/typeshed/stdlib/distutils/dist.pyi index 5bb04b049995..c5b3afe7cc3b 100644 --- a/mypy/typeshed/stdlib/distutils/dist.pyi +++ b/mypy/typeshed/stdlib/distutils/dist.pyi @@ -1,6 +1,6 @@ from _typeshed import StrOrBytesPath, SupportsWrite from distutils.cmd import Command -from typing import IO, Any, Iterable, Mapping, Type +from typing import IO, Any, Iterable, Mapping class DistributionMetadata: def __init__(self, path: int | StrOrBytesPath | None = ...) -> None: ... @@ -50,7 +50,7 @@ class DistributionMetadata: def set_obsoletes(self, value: Iterable[str]) -> None: ... class Distribution: - cmdclass: dict[str, Type[Command]] + cmdclass: dict[str, type[Command]] metadata: DistributionMetadata def __init__(self, attrs: Mapping[str, Any] | None = ...) -> None: ... def get_option_dict(self, command: str) -> dict[str, tuple[str, str]]: ... diff --git a/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi index 06a0847e4687..dce8394b6289 100644 --- a/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi +++ b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi @@ -1,7 +1,7 @@ -from typing import Any, Iterable, List, Mapping, Optional, Tuple, overload +from typing import Any, Iterable, Mapping, Optional, overload -_Option = Tuple[str, Optional[str], str] -_GR = Tuple[List[str], OptionDummy] +_Option = tuple[str, Optional[str], str] +_GR = tuple[list[str], OptionDummy] def fancy_getopt( options: list[_Option], negative_opt: Mapping[_Option, _Option], object: Any, args: list[str] | None diff --git a/mypy/typeshed/stdlib/distutils/util.pyi b/mypy/typeshed/stdlib/distutils/util.pyi index 9b0915570ece..22d982e6949d 100644 --- a/mypy/typeshed/stdlib/distutils/util.pyi +++ b/mypy/typeshed/stdlib/distutils/util.pyi @@ -1,6 +1,7 @@ from _typeshed import StrPath from collections.abc import Callable, Container, Iterable, Mapping -from typing import Any, Tuple +from typing import Any +from typing_extensions import Literal def get_platform() -> str: ... def convert_path(pathname: str) -> str: ... @@ -9,9 +10,9 @@ def check_environ() -> None: ... def subst_vars(s: str, local_vars: Mapping[str, str]) -> None: ... def split_quoted(s: str) -> list[str]: ... def execute( - func: Callable[..., None], args: Tuple[Any, ...], msg: str | None = ..., verbose: bool = ..., dry_run: bool = ... + func: Callable[..., None], args: tuple[Any, ...], msg: str | None = ..., verbose: bool = ..., dry_run: bool = ... ) -> None: ... -def strtobool(val: str) -> bool: ... +def strtobool(val: str) -> Literal[0, 1]: ... def byte_compile( py_files: list[str], optimize: int = ..., diff --git a/mypy/typeshed/stdlib/distutils/version.pyi b/mypy/typeshed/stdlib/distutils/version.pyi index 9921dde39af6..210aa5cf718b 100644 --- a/mypy/typeshed/stdlib/distutils/version.pyi +++ b/mypy/typeshed/stdlib/distutils/version.pyi @@ -1,38 +1,36 @@ +from _typeshed import Self from abc import abstractmethod -from typing import Pattern, Tuple, TypeVar - -_T = TypeVar("_T", bound=Version) +from typing import Pattern class Version: - def __repr__(self) -> str: ... def __eq__(self, other: object) -> bool: ... - def __lt__(self: _T, other: _T | str) -> bool: ... - def __le__(self: _T, other: _T | str) -> bool: ... - def __gt__(self: _T, other: _T | str) -> bool: ... - def __ge__(self: _T, other: _T | str) -> bool: ... + def __lt__(self: Self, other: Self | str) -> bool: ... + def __le__(self: Self, other: Self | str) -> bool: ... + def __gt__(self: Self, other: Self | str) -> bool: ... + def __ge__(self: Self, other: Self | str) -> bool: ... @abstractmethod def __init__(self, vstring: str | None = ...) -> None: ... @abstractmethod - def parse(self: _T, vstring: str) -> _T: ... + def parse(self: Self, vstring: str) -> Self: ... @abstractmethod def __str__(self) -> str: ... @abstractmethod - def _cmp(self: _T, other: _T | str) -> bool: ... + def _cmp(self: Self, other: Self | str) -> bool: ... class StrictVersion(Version): version_re: Pattern[str] version: tuple[int, int, int] prerelease: tuple[str, int] | None def __init__(self, vstring: str | None = ...) -> None: ... - def parse(self: _T, vstring: str) -> _T: ... - def __str__(self) -> str: ... - def _cmp(self: _T, other: _T | str) -> bool: ... + def parse(self: Self, vstring: str) -> Self: ... + def __str__(self) -> str: ... # noqa Y029 + def _cmp(self: Self, other: Self | str) -> bool: ... class LooseVersion(Version): component_re: Pattern[str] vstring: str - version: Tuple[str | int, ...] + version: tuple[str | int, ...] def __init__(self, vstring: str | None = ...) -> None: ... - def parse(self: _T, vstring: str) -> _T: ... - def __str__(self) -> str: ... - def _cmp(self: _T, other: _T | str) -> bool: ... + def parse(self: Self, vstring: str) -> Self: ... + def __str__(self) -> str: ... # noqa Y029 + def _cmp(self: Self, other: Self | str) -> bool: ... diff --git a/mypy/typeshed/stdlib/doctest.pyi b/mypy/typeshed/stdlib/doctest.pyi index 9a9f83b0d8fe..31765ae4f80a 100644 --- a/mypy/typeshed/stdlib/doctest.pyi +++ b/mypy/typeshed/stdlib/doctest.pyi @@ -1,6 +1,6 @@ import types import unittest -from typing import Any, Callable, NamedTuple, Tuple, Type +from typing import Any, Callable, NamedTuple class TestResults(NamedTuple): failed: int @@ -86,7 +86,7 @@ class DocTestFinder: ) -> list[DocTest]: ... _Out = Callable[[str], Any] -_ExcInfo = Tuple[Type[BaseException], BaseException, types.TracebackType] +_ExcInfo = tuple[type[BaseException], BaseException, types.TracebackType] class DocTestRunner: DIVIDER: str diff --git a/mypy/typeshed/stdlib/email/_header_value_parser.pyi b/mypy/typeshed/stdlib/email/_header_value_parser.pyi index f1b08b5d5805..1b006c3f7959 100644 --- a/mypy/typeshed/stdlib/email/_header_value_parser.pyi +++ b/mypy/typeshed/stdlib/email/_header_value_parser.pyi @@ -1,11 +1,10 @@ import sys +from _typeshed import Self from email.errors import HeaderParseError, MessageDefect from email.policy import Policy -from typing import Any, Iterable, Iterator, List, Pattern, Type, TypeVar, Union +from typing import Any, Iterable, Iterator, Pattern, Union from typing_extensions import Final -_T = TypeVar("_T") - WSP: Final[set[str]] CFWS_LEADER: Final[set[str]] SPECIALS: Final[set[str]] @@ -23,7 +22,7 @@ def quote_string(value: Any) -> str: ... if sys.version_info >= (3, 7): rfc2047_matcher: Pattern[str] -class TokenList(List[Union[TokenList, Terminal]]): +class TokenList(list[Union[TokenList, Terminal]]): token_type: str | None syntactic_break: bool ew_combine_allowed: bool @@ -327,14 +326,14 @@ class Terminal(str): syntactic_break: bool token_type: str defects: list[MessageDefect] - def __new__(cls: Type[_T], value: str, token_type: str) -> _T: ... + def __new__(cls: type[Self], value: str, token_type: str) -> Self: ... def pprint(self) -> None: ... @property def all_defects(self) -> list[MessageDefect]: ... def pop_trailing_ws(self) -> None: ... @property def comments(self) -> list[str]: ... - def __getnewargs__(self) -> tuple[str, str]: ... # type: ignore + def __getnewargs__(self) -> tuple[str, str]: ... # type: ignore[override] class WhiteSpaceTerminal(Terminal): @property diff --git a/mypy/typeshed/stdlib/email/base64mime.pyi b/mypy/typeshed/stdlib/email/base64mime.pyi new file mode 100644 index 000000000000..a8030a978923 --- /dev/null +++ b/mypy/typeshed/stdlib/email/base64mime.pyi @@ -0,0 +1,7 @@ +def header_length(bytearray: str | bytes) -> int: ... +def header_encode(header_bytes: str | bytes, charset: str = ...) -> str: ... +def body_encode(s: bytes, maxlinelen: int = ..., eol: str = ...) -> str: ... +def decode(string: str | bytes) -> bytes: ... + +body_decode = decode +decodestring = decode diff --git a/mypy/typeshed/stdlib/email/charset.pyi b/mypy/typeshed/stdlib/email/charset.pyi index 4bf5d11690eb..298b763540db 100644 --- a/mypy/typeshed/stdlib/email/charset.pyi +++ b/mypy/typeshed/stdlib/email/charset.pyi @@ -17,7 +17,6 @@ class Charset: def header_encode(self, string: str) -> str: ... def header_encode_lines(self, string: str, maxlengths: Iterator[int]) -> list[str]: ... def body_encode(self, string: str) -> str: ... - def __str__(self) -> str: ... def __eq__(self, other: Any) -> bool: ... def __ne__(self, other: Any) -> bool: ... diff --git a/mypy/typeshed/stdlib/email/header.pyi b/mypy/typeshed/stdlib/email/header.pyi index 4bebd50c45e4..4490c16a4eb6 100644 --- a/mypy/typeshed/stdlib/email/header.pyi +++ b/mypy/typeshed/stdlib/email/header.pyi @@ -13,7 +13,6 @@ class Header: ) -> None: ... def append(self, s: bytes | str, charset: Charset | str | None = ..., errors: str = ...) -> None: ... def encode(self, splitchars: str = ..., maxlinelen: int | None = ..., linesep: str = ...) -> str: ... - def __str__(self) -> str: ... def __eq__(self, other: Any) -> bool: ... def __ne__(self, other: Any) -> bool: ... diff --git a/mypy/typeshed/stdlib/email/headerregistry.pyi b/mypy/typeshed/stdlib/email/headerregistry.pyi index 69e7bf315d9f..b84acab18ffe 100644 --- a/mypy/typeshed/stdlib/email/headerregistry.pyi +++ b/mypy/typeshed/stdlib/email/headerregistry.pyi @@ -1,5 +1,6 @@ import sys import types +from collections.abc import Iterable, Mapping from datetime import datetime as _datetime from email._header_value_parser import ( AddressList, @@ -12,28 +13,33 @@ from email._header_value_parser import ( ) from email.errors import MessageDefect from email.policy import Policy -from typing import Any, Iterable, Tuple, Type +from typing import Any, ClassVar +from typing_extensions import Literal class BaseHeader(str): + # max_count is actually more of an abstract ClassVar (not defined on the base class, but expected to be defined in subclasses) + max_count: ClassVar[Literal[1] | None] @property def name(self) -> str: ... @property - def defects(self) -> Tuple[MessageDefect, ...]: ... - @property - def max_count(self) -> int | None: ... + def defects(self) -> tuple[MessageDefect, ...]: ... def __new__(cls, name: str, value: Any) -> BaseHeader: ... def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect]) -> None: ... def fold(self, *, policy: Policy) -> str: ... class UnstructuredHeader: + max_count: ClassVar[Literal[1] | None] @staticmethod def value_parser(value: str) -> UnstructuredTokenList: ... @classmethod def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... -class UniqueUnstructuredHeader(UnstructuredHeader): ... +class UniqueUnstructuredHeader(UnstructuredHeader): + max_count: ClassVar[Literal[1]] class DateHeader: + max_count: ClassVar[Literal[1] | None] + def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect], datetime: _datetime) -> None: ... @property def datetime(self) -> _datetime: ... @staticmethod @@ -41,27 +47,43 @@ class DateHeader: @classmethod def parse(cls, value: str | _datetime, kwds: dict[str, Any]) -> None: ... -class UniqueDateHeader(DateHeader): ... +class UniqueDateHeader(DateHeader): + max_count: ClassVar[Literal[1]] class AddressHeader: + max_count: ClassVar[Literal[1] | None] + def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect], groups: Iterable[Group]) -> None: ... @property - def groups(self) -> Tuple[Group, ...]: ... + def groups(self) -> tuple[Group, ...]: ... @property - def addresses(self) -> Tuple[Address, ...]: ... + def addresses(self) -> tuple[Address, ...]: ... @staticmethod def value_parser(value: str) -> AddressList: ... @classmethod def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... -class UniqueAddressHeader(AddressHeader): ... +class UniqueAddressHeader(AddressHeader): + max_count: ClassVar[Literal[1]] class SingleAddressHeader(AddressHeader): @property def address(self) -> Address: ... -class UniqueSingleAddressHeader(SingleAddressHeader): ... +class UniqueSingleAddressHeader(SingleAddressHeader): + max_count: ClassVar[Literal[1]] class MIMEVersionHeader: + max_count: ClassVar[Literal[1]] + def init( + self, + name: str, + *, + parse_tree: TokenList, + defects: Iterable[MessageDefect], + version: str | None, + major: int | None, + minor: int | None, + ) -> None: ... @property def version(self) -> str | None: ... @property @@ -74,6 +96,8 @@ class MIMEVersionHeader: def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... class ParameterizedMIMEHeader: + max_count: ClassVar[Literal[1]] + def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect], params: Mapping[str, Any]) -> None: ... @property def params(self) -> types.MappingProxyType[str, Any]: ... @classmethod @@ -90,12 +114,15 @@ class ContentTypeHeader(ParameterizedMIMEHeader): def value_parser(value: str) -> ContentType: ... class ContentDispositionHeader(ParameterizedMIMEHeader): + # init is redefined but has the same signature as parent class, so is omitted from the stub @property - def content_disposition(self) -> str: ... + def content_disposition(self) -> str | None: ... @staticmethod def value_parser(value: str) -> ContentDisposition: ... class ContentTransferEncodingHeader: + max_count: ClassVar[Literal[1]] + def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect]) -> None: ... @property def cte(self) -> str: ... @classmethod @@ -106,6 +133,7 @@ class ContentTransferEncodingHeader: if sys.version_info >= (3, 8): from email._header_value_parser import MessageID class MessageIDHeader: + max_count: ClassVar[Literal[1]] @classmethod def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... @staticmethod @@ -113,10 +141,10 @@ if sys.version_info >= (3, 8): class HeaderRegistry: def __init__( - self, base_class: Type[BaseHeader] = ..., default_class: Type[BaseHeader] = ..., use_default_map: bool = ... + self, base_class: type[BaseHeader] = ..., default_class: type[BaseHeader] = ..., use_default_map: bool = ... ) -> None: ... - def map_to_type(self, name: str, cls: Type[BaseHeader]) -> None: ... - def __getitem__(self, name: str) -> Type[BaseHeader]: ... + def map_to_type(self, name: str, cls: type[BaseHeader]) -> None: ... + def __getitem__(self, name: str) -> type[BaseHeader]: ... def __call__(self, name: str, value: Any) -> BaseHeader: ... class Address: @@ -131,12 +159,10 @@ class Address: def __init__( self, display_name: str = ..., username: str | None = ..., domain: str | None = ..., addr_spec: str | None = ... ) -> None: ... - def __str__(self) -> str: ... class Group: @property def display_name(self) -> str | None: ... @property - def addresses(self) -> Tuple[Address, ...]: ... + def addresses(self) -> tuple[Address, ...]: ... def __init__(self, display_name: str | None = ..., addresses: Iterable[Address] | None = ...) -> None: ... - def __str__(self) -> str: ... diff --git a/mypy/typeshed/stdlib/email/message.pyi b/mypy/typeshed/stdlib/email/message.pyi index a1749a4cfc2e..5ce11e3d807e 100644 --- a/mypy/typeshed/stdlib/email/message.pyi +++ b/mypy/typeshed/stdlib/email/message.pyi @@ -2,14 +2,14 @@ from email.charset import Charset from email.contentmanager import ContentManager from email.errors import MessageDefect from email.policy import Policy -from typing import Any, Generator, Iterator, List, Optional, Sequence, Tuple, TypeVar, Union +from typing import Any, Generator, Iterator, Optional, Sequence, TypeVar, Union _T = TypeVar("_T") -_PayloadType = Union[List[Message], str, bytes] +_PayloadType = Union[list[Message], str, bytes] _CharsetType = Union[Charset, str, None] -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] -_ParamType = Union[str, Tuple[Optional[str], Optional[str], str]] +_ParamsType = Union[str, None, tuple[str, Optional[str], str]] +_ParamType = Union[str, tuple[Optional[str], Optional[str], str]] _HeaderType = Any class Message: @@ -17,7 +17,6 @@ class Message: preamble: str | None epilogue: str | None defects: list[MessageDefect] - def __str__(self) -> str: ... def is_multipart(self) -> bool: ... def set_unixfrom(self, unixfrom: str) -> None: ... def get_unixfrom(self) -> str | None: ... @@ -69,6 +68,9 @@ class Message: replace: bool = ..., ) -> None: ... def __init__(self, policy: Policy = ...) -> None: ... + # The following two methods are undocumented, but a source code comment states that they are public API + def set_raw(self, name: str, value: str) -> None: ... + def raw_items(self) -> Iterator[tuple[str, str]]: ... class MIMEPart(Message): def __init__(self, policy: Policy | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/email/mime/application.pyi b/mypy/typeshed/stdlib/email/mime/application.pyi index 11fc470e9dd1..d176cd613e27 100644 --- a/mypy/typeshed/stdlib/email/mime/application.pyi +++ b/mypy/typeshed/stdlib/email/mime/application.pyi @@ -1,8 +1,8 @@ from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy -from typing import Callable, Optional, Tuple, Union +from typing import Callable, Optional, Union -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] +_ParamsType = Union[str, None, tuple[str, Optional[str], str]] class MIMEApplication(MIMENonMultipart): def __init__( diff --git a/mypy/typeshed/stdlib/email/mime/audio.pyi b/mypy/typeshed/stdlib/email/mime/audio.pyi index ee6de410bf53..38657c932e2f 100644 --- a/mypy/typeshed/stdlib/email/mime/audio.pyi +++ b/mypy/typeshed/stdlib/email/mime/audio.pyi @@ -1,8 +1,8 @@ from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy -from typing import Callable, Optional, Tuple, Union +from typing import Callable, Optional, Union -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] +_ParamsType = Union[str, None, tuple[str, Optional[str], str]] class MIMEAudio(MIMENonMultipart): def __init__( diff --git a/mypy/typeshed/stdlib/email/mime/base.pyi b/mypy/typeshed/stdlib/email/mime/base.pyi index b88dfd492554..cb655607b032 100644 --- a/mypy/typeshed/stdlib/email/mime/base.pyi +++ b/mypy/typeshed/stdlib/email/mime/base.pyi @@ -1,8 +1,8 @@ import email.message from email.policy import Policy -from typing import Optional, Tuple, Union +from typing import Optional, Union -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] +_ParamsType = Union[str, None, tuple[str, Optional[str], str]] class MIMEBase(email.message.Message): def __init__(self, _maintype: str, _subtype: str, *, policy: Policy | None = ..., **_params: _ParamsType) -> None: ... diff --git a/mypy/typeshed/stdlib/email/mime/image.pyi b/mypy/typeshed/stdlib/email/mime/image.pyi index 886aa74d5fe5..0325d9e594da 100644 --- a/mypy/typeshed/stdlib/email/mime/image.pyi +++ b/mypy/typeshed/stdlib/email/mime/image.pyi @@ -1,8 +1,8 @@ from email.mime.nonmultipart import MIMENonMultipart from email.policy import Policy -from typing import Callable, Optional, Tuple, Union +from typing import Callable, Optional, Union -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] +_ParamsType = Union[str, None, tuple[str, Optional[str], str]] class MIMEImage(MIMENonMultipart): def __init__( diff --git a/mypy/typeshed/stdlib/email/mime/multipart.pyi b/mypy/typeshed/stdlib/email/mime/multipart.pyi index 6259ddf5ab8f..6c316c055329 100644 --- a/mypy/typeshed/stdlib/email/mime/multipart.pyi +++ b/mypy/typeshed/stdlib/email/mime/multipart.pyi @@ -1,9 +1,9 @@ from email.message import Message from email.mime.base import MIMEBase from email.policy import Policy -from typing import Optional, Sequence, Tuple, Union +from typing import Optional, Sequence, Union -_ParamsType = Union[str, None, Tuple[str, Optional[str], str]] +_ParamsType = Union[str, None, tuple[str, Optional[str], str]] class MIMEMultipart(MIMEBase): def __init__( diff --git a/mypy/typeshed/stdlib/email/parser.pyi b/mypy/typeshed/stdlib/email/parser.pyi index 574c927eeaf5..edff6f5b479b 100644 --- a/mypy/typeshed/stdlib/email/parser.pyi +++ b/mypy/typeshed/stdlib/email/parser.pyi @@ -1,10 +1,12 @@ import email.feedparser from email.message import Message from email.policy import Policy -from typing import BinaryIO, Callable, TextIO +from typing import BinaryIO, Callable, TextIO, TypeVar -FeedParser = email.feedparser.FeedParser -BytesFeedParser = email.feedparser.BytesFeedParser +_M = TypeVar("_M", bound=Message) + +FeedParser = email.feedparser.FeedParser[_M] +BytesFeedParser = email.feedparser.BytesFeedParser[_M] class Parser: def __init__(self, _class: Callable[[], Message] | None = ..., *, policy: Policy = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/email/policy.pyi b/mypy/typeshed/stdlib/email/policy.pyi index 72a54bcfbf08..15991c7e084b 100644 --- a/mypy/typeshed/stdlib/email/policy.pyi +++ b/mypy/typeshed/stdlib/email/policy.pyi @@ -1,17 +1,27 @@ -from abc import abstractmethod +from abc import ABCMeta, abstractmethod from email.contentmanager import ContentManager from email.errors import MessageDefect from email.header import Header from email.message import Message from typing import Any, Callable -class Policy: +class Policy(metaclass=ABCMeta): max_line_length: int | None linesep: str cte_type: str raise_on_defect: bool - mange_from: bool - def __init__(self, **kw: Any) -> None: ... + mangle_from_: bool + message_factory: Callable[[Policy], Message] | None + def __init__( + self, + *, + max_line_length: int | None = ..., + linesep: str = ..., + cte_type: str = ..., + raise_on_defect: bool = ..., + mangle_from_: bool = ..., + message_factory: Callable[[Policy], Message] | None = ..., + ) -> None: ... def clone(self, **kw: Any) -> Policy: ... def handle_defect(self, obj: Message, defect: MessageDefect) -> None: ... def register_defect(self, obj: Message, defect: MessageDefect) -> None: ... @@ -30,7 +40,7 @@ class Policy: class Compat32(Policy): def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: ... def header_store_parse(self, name: str, value: str) -> tuple[str, str]: ... - def header_fetch_parse(self, name: str, value: str) -> str | Header: ... # type: ignore + def header_fetch_parse(self, name: str, value: str) -> str | Header: ... # type: ignore[override] def fold(self, name: str, value: str) -> str: ... def fold_binary(self, name: str, value: str) -> bytes: ... @@ -41,6 +51,20 @@ class EmailPolicy(Policy): refold_source: str header_factory: Callable[[str, str], str] content_manager: ContentManager + def __init__( + self, + *, + max_line_length: int | None = ..., + linesep: str = ..., + cte_type: str = ..., + raise_on_defect: bool = ..., + mangle_from_: bool = ..., + message_factory: Callable[[Policy], Message] | None = ..., + utf8: bool = ..., + refold_source: str = ..., + header_factory: Callable[[str, str], str] = ..., + content_manager: ContentManager = ..., + ) -> None: ... def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: ... def header_store_parse(self, name: str, value: str) -> tuple[str, str]: ... def header_fetch_parse(self, name: str, value: str) -> str: ... diff --git a/mypy/typeshed/stdlib/email/quoprimime.pyi b/mypy/typeshed/stdlib/email/quoprimime.pyi new file mode 100644 index 000000000000..41c4bd8cca9e --- /dev/null +++ b/mypy/typeshed/stdlib/email/quoprimime.pyi @@ -0,0 +1,13 @@ +def header_check(octet: int) -> bool: ... +def body_check(octet: int) -> bool: ... +def header_length(bytearray: bytes) -> int: ... +def body_length(bytearray: bytes) -> int: ... +def unquote(s: str | bytes) -> str: ... +def quote(c: str | bytes) -> str: ... +def header_encode(header_bytes: bytes, charset: str = ...) -> str: ... +def body_encode(body: str, maxlinelen: int = ..., eol: str = ...) -> str: ... +def decode(encoded: str, eol: str = ...) -> str: ... +def header_decode(s: str) -> str: ... + +body_decode = decode +decodestring = decode diff --git a/mypy/typeshed/stdlib/email/utils.pyi b/mypy/typeshed/stdlib/email/utils.pyi index 3c07e98079fc..728a5a53f230 100644 --- a/mypy/typeshed/stdlib/email/utils.pyi +++ b/mypy/typeshed/stdlib/email/utils.pyi @@ -1,10 +1,10 @@ import datetime import sys from email.charset import Charset -from typing import Optional, Tuple, Union, overload +from typing import Optional, Union, overload -_ParamType = Union[str, Tuple[Optional[str], Optional[str], str]] -_PDTZ = Tuple[int, int, int, int, int, int, int, int, int, Optional[int]] +_ParamType = Union[str, tuple[Optional[str], Optional[str], str]] +_PDTZ = tuple[int, int, int, int, int, int, int, int, int, Optional[int]] def quote(str: str) -> str: ... def unquote(str: str) -> str: ... diff --git a/mypy/typeshed/stdlib/encodings/utf_8_sig.pyi b/mypy/typeshed/stdlib/encodings/utf_8_sig.pyi new file mode 100644 index 000000000000..bf52e8a6f3d3 --- /dev/null +++ b/mypy/typeshed/stdlib/encodings/utf_8_sig.pyi @@ -0,0 +1,27 @@ +import codecs + +class IncrementalEncoder(codecs.IncrementalEncoder): + def __init__(self, errors: str = ...) -> None: ... + def encode(self, input: str, final: bool = ...) -> bytes: ... + def reset(self) -> None: ... + def getstate(self) -> int: ... # type: ignore[override] + def setstate(self, state: int) -> None: ... # type: ignore[override] + +class IncrementalDecoder(codecs.BufferedIncrementalDecoder): + def __init__(self, errors: str = ...) -> None: ... + def _buffer_decode(self, input: bytes, errors: str | None, final: bool) -> tuple[str, int]: ... + def reset(self) -> None: ... + def getstate(self) -> tuple[bytes, int]: ... + def setstate(self, state: tuple[bytes, int]) -> None: ... + +class StreamWriter(codecs.StreamWriter): + def reset(self) -> None: ... + def encode(self, input: str, errors: str | None = ...) -> tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + def reset(self) -> None: ... + def decode(self, input: bytes, errors: str | None = ...) -> tuple[str, int]: ... + +def getregentry() -> codecs.CodecInfo: ... +def encode(input: str, errors: str | None = ...) -> tuple[bytes, int]: ... +def decode(input: bytes, errors: str | None = ...) -> tuple[str, int]: ... diff --git a/mypy/typeshed/stdlib/enum.pyi b/mypy/typeshed/stdlib/enum.pyi index 07fea104cec7..efc668720397 100644 --- a/mypy/typeshed/stdlib/enum.pyi +++ b/mypy/typeshed/stdlib/enum.pyi @@ -1,11 +1,29 @@ import sys import types +from _typeshed import Self from abc import ABCMeta from builtins import property as _builtins_property -from typing import Any, Iterator, Type, TypeVar +from collections.abc import Iterable, Iterator, Mapping +from typing import Any, TypeVar, Union, overload _T = TypeVar("_T") -_S = TypeVar("_S", bound=Type[Enum]) +_S = TypeVar("_S", bound=type[Enum]) + +# The following all work: +# >>> from enum import Enum +# >>> from string import ascii_lowercase +# >>> Enum('Foo', names='RED YELLOW GREEN') +# +# >>> Enum('Foo', names=[('RED', 1), ('YELLOW, 2)]) +# +# >>> Enum('Foo', names=((x for x in (ascii_lowercase[i], i)) for i in range(5))) +# +# >>> Enum('Foo', names={'RED': 1, 'YELLOW': 2}) +# +_EnumNames = Union[str, Iterable[str], Iterable[Iterable[Union[str, Any]]], Mapping[str, Any]] + +class _EnumDict(dict[str, Any]): + def __init__(self) -> None: ... # Note: EnumMeta actually subclasses type directly, not ABCMeta. # This is a temporary workaround to allow multiple creation of enums with builtins @@ -13,20 +31,78 @@ _S = TypeVar("_S", bound=Type[Enum]) # spurious inconsistent metaclass structure. See #1595. # Structurally: Iterable[T], Reversible[T], Container[T] where T is the enum itself class EnumMeta(ABCMeta): - def __iter__(self: Type[_T]) -> Iterator[_T]: ... - def __reversed__(self: Type[_T]) -> Iterator[_T]: ... - def __contains__(self: Type[Any], member: object) -> bool: ... - def __getitem__(self: Type[_T], name: str) -> _T: ... + if sys.version_info >= (3, 11): + def __new__( + metacls: type[Self], # type: ignore + cls: str, + bases: tuple[type, ...], + classdict: _EnumDict, + *, + boundary: FlagBoundary | None = ..., + _simple: bool = ..., + **kwds: Any, + ) -> Self: ... + elif sys.version_info >= (3, 9): + def __new__(metacls: type[Self], cls: str, bases: tuple[type, ...], classdict: _EnumDict, **kwds: Any) -> Self: ... # type: ignore + else: + def __new__(metacls: type[Self], cls: str, bases: tuple[type, ...], classdict: _EnumDict) -> Self: ... # type: ignore + def __iter__(self: type[_T]) -> Iterator[_T]: ... + def __reversed__(self: type[_T]) -> Iterator[_T]: ... + def __contains__(self: type[Any], member: object) -> bool: ... + def __getitem__(self: type[_T], name: str) -> _T: ... @_builtins_property - def __members__(self: Type[_T]) -> types.MappingProxyType[str, _T]: ... + def __members__(self: type[_T]) -> types.MappingProxyType[str, _T]: ... def __len__(self) -> int: ... + if sys.version_info >= (3, 11): + # Simple value lookup + @overload # type: ignore[override] + def __call__(cls: type[_T], value: Any, names: None = ...) -> _T: ... + # Functional Enum API + @overload + def __call__( + cls, + value: str, + names: _EnumNames, + *, + module: str | None = ..., + qualname: str | None = ..., + type: type | None = ..., + start: int = ..., + boundary: FlagBoundary | None = ..., + ) -> type[Enum]: ... + else: + @overload # type: ignore[override] + def __call__(cls: type[_T], value: Any, names: None = ...) -> _T: ... + @overload + def __call__( + cls, + value: str, + names: _EnumNames, + *, + module: str | None = ..., + qualname: str | None = ..., + type: type | None = ..., + start: int = ..., + ) -> type[Enum]: ... _member_names_: list[str] # undocumented _member_map_: dict[str, Enum] # undocumented _value2member_map_: dict[Any, Enum] # undocumented +if sys.version_info >= (3, 11): + # In 3.11 `EnumMeta` metaclass is renamed to `EnumType`, but old name also exists. + EnumType = EnumMeta + class Enum(metaclass=EnumMeta): - name: str - value: Any + if sys.version_info >= (3, 11): + @property + def name(self) -> str: ... + @property + def value(self) -> Any: ... + else: + @types.DynamicClassAttribute + def name(self) -> str: ... + @types.DynamicClassAttribute + def value(self) -> Any: ... _name_: str _value_: Any if sys.version_info >= (3, 7): @@ -37,17 +113,21 @@ class Enum(metaclass=EnumMeta): def _missing_(cls, value: object) -> Any: ... @staticmethod def _generate_next_value_(name: str, start: int, count: int, last_values: list[Any]) -> Any: ... - def __new__(cls: Type[_T], value: object) -> _T: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... + def __new__(cls: type[Self], value: object) -> Self: ... def __dir__(self) -> list[str]: ... def __format__(self, format_spec: str) -> str: ... def __hash__(self) -> Any: ... def __reduce_ex__(self, proto: object) -> Any: ... class IntEnum(int, Enum): - value: int - def __new__(cls: Type[_T], value: int | _T) -> _T: ... + _value_: int + if sys.version_info >= (3, 11): + @property + def value(self) -> int: ... + else: + @types.DynamicClassAttribute + def value(self) -> int: ... + def __new__(cls: type[Self], value: int | Self) -> Self: ... def unique(enumeration: _S) -> _S: ... @@ -55,33 +135,50 @@ _auto_null: Any # subclassing IntFlag so it picks up all implemented base functions, best modeling behavior of enum.auto() class auto(IntFlag): - value: Any - def __new__(cls: Type[_T]) -> _T: ... + _value_: Any + if sys.version_info >= (3, 11): + @property + def value(self) -> Any: ... + else: + @types.DynamicClassAttribute + def value(self) -> Any: ... + def __new__(cls: type[Self]) -> Self: ... class Flag(Enum): - name: str | None # type: ignore - value: int + _name_: str | None # type: ignore[assignment] + _value_: int + if sys.version_info >= (3, 11): + @property + def name(self) -> str | None: ... # type: ignore[override] + @property + def value(self) -> int: ... + else: + @types.DynamicClassAttribute + def name(self) -> str | None: ... # type: ignore[override] + @types.DynamicClassAttribute + def value(self) -> int: ... def __contains__(self: _T, other: _T) -> bool: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... def __bool__(self) -> bool: ... - def __or__(self: _T, other: _T) -> _T: ... - def __and__(self: _T, other: _T) -> _T: ... - def __xor__(self: _T, other: _T) -> _T: ... - def __invert__(self: _T) -> _T: ... + def __or__(self: Self, other: Self) -> Self: ... + def __and__(self: Self, other: Self) -> Self: ... + def __xor__(self: Self, other: Self) -> Self: ... + def __invert__(self: Self) -> Self: ... class IntFlag(int, Flag): - def __new__(cls: Type[_T], value: int | _T) -> _T: ... - def __or__(self: _T, other: int | _T) -> _T: ... - def __and__(self: _T, other: int | _T) -> _T: ... - def __xor__(self: _T, other: int | _T) -> _T: ... - def __ror__(self: _T, n: int | _T) -> _T: ... - def __rand__(self: _T, n: int | _T) -> _T: ... - def __rxor__(self: _T, n: int | _T) -> _T: ... + def __new__(cls: type[Self], value: int | Self) -> Self: ... + def __or__(self: Self, other: int | Self) -> Self: ... + def __and__(self: Self, other: int | Self) -> Self: ... + def __xor__(self: Self, other: int | Self) -> Self: ... + def __ror__(self: Self, n: int | Self) -> Self: ... + def __rand__(self: Self, n: int | Self) -> Self: ... + def __rxor__(self: Self, n: int | Self) -> Self: ... if sys.version_info >= (3, 11): class StrEnum(str, Enum): - def __new__(cls: Type[_T], value: int | _T) -> _T: ... + def __new__(cls: type[Self], value: str | Self) -> Self: ... + _value_: str + @property + def value(self) -> str: ... class FlagBoundary(StrEnum): STRICT: str CONFORM: str @@ -91,7 +188,10 @@ if sys.version_info >= (3, 11): CONFORM = FlagBoundary.CONFORM EJECT = FlagBoundary.EJECT KEEP = FlagBoundary.KEEP - class property(_builtins_property): ... + class property(types.DynamicClassAttribute): + def __set_name__(self, ownerclass: type[Enum], name: str) -> None: ... + name: str + clsname: str def global_enum(cls: _S) -> _S: ... def global_enum_repr(self: Enum) -> str: ... def global_flag_repr(self: Flag) -> str: ... diff --git a/mypy/typeshed/stdlib/fcntl.pyi b/mypy/typeshed/stdlib/fcntl.pyi index 141f9ee9360a..69863bf580fa 100644 --- a/mypy/typeshed/stdlib/fcntl.pyi +++ b/mypy/typeshed/stdlib/fcntl.pyi @@ -3,94 +3,114 @@ from _typeshed import FileDescriptorLike, ReadOnlyBuffer, WriteableBuffer from typing import Any, overload from typing_extensions import Literal -FASYNC: int -FD_CLOEXEC: int -DN_ACCESS: int -DN_ATTRIB: int -DN_CREATE: int -DN_DELETE: int -DN_MODIFY: int -DN_MULTISHOT: int -DN_RENAME: int -F_DUPFD: int -F_DUPFD_CLOEXEC: int -F_FULLFSYNC: int -F_EXLCK: int -F_GETFD: int -F_GETFL: int -F_GETLEASE: int -F_GETLK: int -F_GETLK64: int -F_GETOWN: int -F_NOCACHE: int -F_GETSIG: int -F_NOTIFY: int -F_RDLCK: int -F_SETFD: int -F_SETFL: int -F_SETLEASE: int -F_SETLK: int -F_SETLK64: int -F_SETLKW: int -F_SETLKW64: int -if sys.version_info >= (3, 9) and sys.platform == "linux": - F_OFD_GETLK: int - F_OFD_SETLK: int - F_OFD_SETLKW: int -F_SETOWN: int -F_SETSIG: int -F_SHLCK: int -F_UNLCK: int -F_WRLCK: int -I_ATMARK: int -I_CANPUT: int -I_CKBAND: int -I_FDINSERT: int -I_FIND: int -I_FLUSH: int -I_FLUSHBAND: int -I_GETBAND: int -I_GETCLTIME: int -I_GETSIG: int -I_GRDOPT: int -I_GWROPT: int -I_LINK: int -I_LIST: int -I_LOOK: int -I_NREAD: int -I_PEEK: int -I_PLINK: int -I_POP: int -I_PUNLINK: int -I_PUSH: int -I_RECVFD: int -I_SENDFD: int -I_SETCLTIME: int -I_SETSIG: int -I_SRDOPT: int -I_STR: int -I_SWROPT: int -I_UNLINK: int -LOCK_EX: int -LOCK_MAND: int -LOCK_NB: int -LOCK_READ: int -LOCK_RW: int -LOCK_SH: int -LOCK_UN: int -LOCK_WRITE: int +if sys.platform != "win32": + FASYNC: int + FD_CLOEXEC: int + F_DUPFD: int + F_DUPFD_CLOEXEC: int + F_GETFD: int + F_GETFL: int + F_GETLK: int + F_GETOWN: int + F_RDLCK: int + F_SETFD: int + F_SETFL: int + F_SETLK: int + F_SETLKW: int + F_SETOWN: int + F_UNLCK: int + F_WRLCK: int + if sys.platform == "darwin": + F_FULLFSYNC: int + F_NOCACHE: int + if sys.version_info >= (3, 9): + F_GETPATH: int + if sys.platform == "linux": + F_SETLKW64: int + F_SETSIG: int + F_SHLCK: int + F_SETLK64: int + F_SETLEASE: int + F_GETSIG: int + F_NOTIFY: int + F_EXLCK: int + F_GETLEASE: int + F_GETLK64: int + if sys.version_info >= (3, 8): + F_ADD_SEALS: int + F_GET_SEALS: int + F_SEAL_GROW: int + F_SEAL_SEAL: int + F_SEAL_SHRINK: int + F_SEAL_WRITE: int + if sys.version_info >= (3, 9): + F_OFD_GETLK: int + F_OFD_SETLK: int + F_OFD_SETLKW: int + if sys.version_info >= (3, 10): + F_GETPIPE_SZ: int + F_SETPIPE_SZ: int -@overload -def fcntl(__fd: FileDescriptorLike, __cmd: int, __arg: int = ...) -> int: ... -@overload -def fcntl(__fd: FileDescriptorLike, __cmd: int, __arg: bytes) -> bytes: ... -@overload -def ioctl(__fd: FileDescriptorLike, __request: int, __arg: int = ..., __mutate_flag: bool = ...) -> int: ... -@overload -def ioctl(__fd: FileDescriptorLike, __request: int, __arg: WriteableBuffer, __mutate_flag: Literal[True] = ...) -> int: ... -@overload -def ioctl(__fd: FileDescriptorLike, __request: int, __arg: WriteableBuffer, __mutate_flag: Literal[False]) -> bytes: ... -@overload -def ioctl(__fd: FileDescriptorLike, __request: int, __arg: ReadOnlyBuffer, __mutate_flag: bool = ...) -> bytes: ... -def flock(__fd: FileDescriptorLike, __operation: int) -> None: ... -def lockf(__fd: FileDescriptorLike, __cmd: int, __len: int = ..., __start: int = ..., __whence: int = ...) -> Any: ... + DN_ACCESS: int + DN_ATTRIB: int + DN_CREATE: int + DN_DELETE: int + DN_MODIFY: int + DN_MULTISHOT: int + DN_RENAME: int + + LOCK_EX: int + LOCK_NB: int + LOCK_SH: int + LOCK_UN: int + if sys.platform == "linux": + LOCK_MAND: int + LOCK_READ: int + LOCK_RW: int + LOCK_WRITE: int + + # These are highly problematic, they might be present or not, depends on the specific OS. + if sys.platform == "linux": + I_ATMARK: int + I_CANPUT: int + I_CKBAND: int + I_FDINSERT: int + I_FIND: int + I_FLUSH: int + I_FLUSHBAND: int + I_GETBAND: int + I_GETCLTIME: int + I_GETSIG: int + I_GRDOPT: int + I_GWROPT: int + I_LINK: int + I_LIST: int + I_LOOK: int + I_NREAD: int + I_PEEK: int + I_PLINK: int + I_POP: int + I_PUNLINK: int + I_PUSH: int + I_RECVFD: int + I_SENDFD: int + I_SETCLTIME: int + I_SETSIG: int + I_SRDOPT: int + I_STR: int + I_SWROPT: int + I_UNLINK: int + @overload + def fcntl(__fd: FileDescriptorLike, __cmd: int, __arg: int = ...) -> int: ... + @overload + def fcntl(__fd: FileDescriptorLike, __cmd: int, __arg: bytes) -> bytes: ... + @overload + def ioctl(__fd: FileDescriptorLike, __request: int, __arg: int = ..., __mutate_flag: bool = ...) -> int: ... + @overload + def ioctl(__fd: FileDescriptorLike, __request: int, __arg: WriteableBuffer, __mutate_flag: Literal[True] = ...) -> int: ... + @overload + def ioctl(__fd: FileDescriptorLike, __request: int, __arg: WriteableBuffer, __mutate_flag: Literal[False]) -> bytes: ... + @overload + def ioctl(__fd: FileDescriptorLike, __request: int, __arg: ReadOnlyBuffer, __mutate_flag: bool = ...) -> bytes: ... + def flock(__fd: FileDescriptorLike, __operation: int) -> None: ... + def lockf(__fd: FileDescriptorLike, __cmd: int, __len: int = ..., __start: int = ..., __whence: int = ...) -> Any: ... diff --git a/mypy/typeshed/stdlib/filecmp.pyi b/mypy/typeshed/stdlib/filecmp.pyi index 1c3d0a142a33..994809099c6b 100644 --- a/mypy/typeshed/stdlib/filecmp.pyi +++ b/mypy/typeshed/stdlib/filecmp.pyi @@ -2,11 +2,15 @@ import sys from _typeshed import StrOrBytesPath from os import PathLike from typing import Any, AnyStr, Callable, Generic, Iterable, Sequence +from typing_extensions import Literal if sys.version_info >= (3, 9): from types import GenericAlias +__all__ = ["clear_cache", "cmp", "dircmp", "cmpfiles", "DEFAULT_IGNORES"] + DEFAULT_IGNORES: list[str] +BUFSIZE: Literal[8192] def cmp(f1: StrOrBytesPath, f2: StrOrBytesPath, shallow: int | bool = ...) -> bool: ... def cmpfiles( diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index 3c14b736ca50..576822059560 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -85,7 +85,8 @@ class FileInput(Iterable[AnyStr], Generic[AnyStr]): def __exit__(self, type: Any, value: Any, traceback: Any) -> None: ... def __iter__(self) -> Iterator[AnyStr]: ... def __next__(self) -> AnyStr: ... - def __getitem__(self, i: int) -> AnyStr: ... + if sys.version_info < (3, 11): + def __getitem__(self, i: int) -> AnyStr: ... def nextfile(self) -> None: ... def readline(self) -> AnyStr: ... def filename(self) -> str: ... diff --git a/mypy/typeshed/stdlib/formatter.pyi b/mypy/typeshed/stdlib/formatter.pyi index 7c3b97688dbd..f5d8348d08a1 100644 --- a/mypy/typeshed/stdlib/formatter.pyi +++ b/mypy/typeshed/stdlib/formatter.pyi @@ -1,8 +1,8 @@ -from typing import IO, Any, Iterable, Tuple +from typing import IO, Any, Iterable AS_IS: None -_FontType = Tuple[str, bool, bool, bool] -_StylesType = Tuple[Any, ...] +_FontType = tuple[str, bool, bool, bool] +_StylesType = tuple[Any, ...] class NullFormatter: writer: NullWriter | None @@ -68,7 +68,7 @@ class NullWriter: def new_font(self, font: _FontType) -> None: ... def new_margin(self, margin: int, level: int) -> None: ... def new_spacing(self, spacing: str | None) -> None: ... - def new_styles(self, styles: Tuple[Any, ...]) -> None: ... + def new_styles(self, styles: tuple[Any, ...]) -> None: ... def send_paragraph(self, blankline: int) -> None: ... def send_line_break(self) -> None: ... def send_hor_rule(self, *args: Any, **kw: Any) -> None: ... @@ -81,7 +81,7 @@ class AbstractWriter(NullWriter): def new_font(self, font: _FontType) -> None: ... def new_margin(self, margin: int, level: int) -> None: ... def new_spacing(self, spacing: str | None) -> None: ... - def new_styles(self, styles: Tuple[Any, ...]) -> None: ... + def new_styles(self, styles: tuple[Any, ...]) -> None: ... def send_paragraph(self, blankline: int) -> None: ... def send_line_break(self) -> None: ... def send_hor_rule(self, *args: Any, **kw: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/fractions.pyi b/mypy/typeshed/stdlib/fractions.pyi index 3c6808651275..56a6f0c078d2 100644 --- a/mypy/typeshed/stdlib/fractions.pyi +++ b/mypy/typeshed/stdlib/fractions.pyi @@ -1,11 +1,11 @@ import sys +from _typeshed import Self from decimal import Decimal from numbers import Integral, Rational, Real -from typing import Type, TypeVar, Union, overload +from typing import Union, overload from typing_extensions import Literal _ComparableNum = Union[int, float, Decimal, Real] -_T = TypeVar("_T") if sys.version_info < (3, 9): @overload @@ -20,10 +20,10 @@ if sys.version_info < (3, 9): class Fraction(Rational): @overload def __new__( - cls: Type[_T], numerator: int | Rational = ..., denominator: int | Rational | None = ..., *, _normalize: bool = ... - ) -> _T: ... + cls: type[Self], numerator: int | Rational = ..., denominator: int | Rational | None = ..., *, _normalize: bool = ... + ) -> Self: ... @overload - def __new__(cls: Type[_T], __value: float | Decimal | str, *, _normalize: bool = ...) -> _T: ... + def __new__(cls: type[Self], __value: float | Decimal | str, *, _normalize: bool = ...) -> Self: ... @classmethod def from_float(cls, f: float) -> Fraction: ... @classmethod @@ -134,6 +134,8 @@ class Fraction(Rational): def __le__(self, other: _ComparableNum) -> bool: ... def __ge__(self, other: _ComparableNum) -> bool: ... def __bool__(self) -> bool: ... + if sys.version_info >= (3, 11): + def __int__(self) -> int: ... # Not actually defined within fractions.py, but provides more useful # overrides @property diff --git a/mypy/typeshed/stdlib/ftplib.pyi b/mypy/typeshed/stdlib/ftplib.pyi index 3f4f892bb516..f9df2a0fcc48 100644 --- a/mypy/typeshed/stdlib/ftplib.pyi +++ b/mypy/typeshed/stdlib/ftplib.pyi @@ -3,14 +3,16 @@ from _typeshed import Self, SupportsRead, SupportsReadline from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, Callable, Iterable, Iterator, TextIO, Tuple, Type +from typing import Any, Callable, Iterable, Iterator, TextIO from typing_extensions import Literal -MSG_OOB: int -FTP_PORT: int -MAXLINE: int -CRLF: str -B_CRLF: bytes +__all__ = ["FTP", "error_reply", "error_temp", "error_perm", "error_proto", "all_errors"] + +MSG_OOB: Literal[1] +FTP_PORT: Literal[21] +MAXLINE: Literal[8192] +CRLF: Literal["\r\n"] +B_CRLF: Literal[b"\r\n"] class Error(Exception): ... class error_reply(Error): ... @@ -18,7 +20,7 @@ class error_temp(Error): ... class error_perm(Error): ... class error_proto(Error): ... -all_errors: Tuple[Type[Exception], ...] +all_errors: tuple[type[Exception], ...] class FTP: debugging: int @@ -33,13 +35,9 @@ class FTP: lastresp: str file: TextIO | None encoding: str - - # The following variable is intentionally left undocumented. - # See https://bugs.python.org/issue43285 for relevant discussion - # trust_server_pasv_ipv4_address: bool 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: ... source_address: tuple[str, int] | None if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index b5e52bf59920..6a8a990b37fa 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -1,7 +1,7 @@ import sys import types -from _typeshed import SupportsItems, SupportsLessThan -from typing import Any, Callable, Generic, Hashable, Iterable, NamedTuple, Sequence, Sized, Tuple, Type, TypeVar, overload +from _typeshed import Self, SupportsAllComparisons, SupportsItems +from typing import Any, Callable, Generic, Hashable, Iterable, NamedTuple, Sequence, Sized, TypeVar, overload from typing_extensions import final if sys.version_info >= (3, 9): @@ -44,15 +44,15 @@ WRAPPER_UPDATES: Sequence[str] def update_wrapper(wrapper: _T, wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> _T: ... def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ... -def total_ordering(cls: Type[_T]) -> Type[_T]: ... -def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsLessThan]: ... +def total_ordering(cls: type[_T]) -> type[_T]: ... +def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsAllComparisons]: ... class partial(Generic[_T]): func: Callable[..., _T] - args: Tuple[Any, ...] + args: tuple[Any, ...] keywords: dict[str, Any] - def __init__(self, func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> _T: ... + def __new__(cls: type[Self], __func: Callable[..., _T], *args: Any, **kwargs: Any) -> Self: ... + def __call__(__self, *args: Any, **kwargs: Any) -> _T: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -61,13 +61,13 @@ _Descriptor = Any class partialmethod(Generic[_T]): func: Callable[..., _T] | _Descriptor - args: Tuple[Any, ...] + args: tuple[Any, ...] keywords: dict[str, Any] @overload def __init__(self, __func: Callable[..., _T], *args: Any, **keywords: Any) -> None: ... @overload def __init__(self, __func: _Descriptor, *args: Any, **keywords: Any) -> None: ... - def __get__(self, obj: Any, cls: Type[Any]) -> Callable[..., _T]: ... + def __get__(self, obj: Any, cls: type[Any]) -> Callable[..., _T]: ... @property def __isabstractmethod__(self) -> bool: ... if sys.version_info >= (3, 9): @@ -79,16 +79,16 @@ class _SingleDispatchCallable(Generic[_T]): # @fun.register(complex) # def _(arg, verbose=False): ... @overload - def register(self, cls: Type[Any], func: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + def register(self, cls: type[Any], func: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... # @fun.register # def _(arg: int, verbose=False): @overload def register(self, cls: Callable[..., _T], func: None = ...) -> Callable[..., _T]: ... # fun.register(int, lambda x: x) @overload - def register(self, cls: Type[Any], func: Callable[..., _T]) -> Callable[..., _T]: ... + def register(self, cls: type[Any], func: Callable[..., _T]) -> Callable[..., _T]: ... def _clear_cache(self) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> _T: ... + def __call__(__self, *args: Any, **kwargs: Any) -> _T: ... def singledispatch(func: Callable[..., _T]) -> _SingleDispatchCallable[_T]: ... @@ -98,21 +98,21 @@ if sys.version_info >= (3, 8): func: Callable[..., _T] def __init__(self, func: Callable[..., _T]) -> None: ... @overload - def register(self, cls: Type[Any], method: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... + def register(self, cls: type[Any], method: None = ...) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... @overload def register(self, cls: Callable[..., _T], method: None = ...) -> Callable[..., _T]: ... @overload - def register(self, cls: Type[Any], method: Callable[..., _T]) -> Callable[..., _T]: ... + def register(self, cls: type[Any], method: Callable[..., _T]) -> Callable[..., _T]: ... def __call__(self, *args: Any, **kwargs: Any) -> _T: ... class cached_property(Generic[_T]): func: Callable[[Any], _T] attrname: str | None def __init__(self, func: Callable[[Any], _T]) -> None: ... @overload - def __get__(self, instance: None, owner: Type[Any] | None = ...) -> cached_property[_T]: ... + def __get__(self, instance: None, owner: type[Any] | None = ...) -> cached_property[_T]: ... @overload - def __get__(self, instance: object, owner: Type[Any] | None = ...) -> _T: ... - def __set_name__(self, owner: Type[Any], name: str) -> None: ... + def __get__(self, instance: object, owner: type[Any] | None = ...) -> _T: ... + def __set_name__(self, owner: type[Any], name: str) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -120,10 +120,10 @@ if sys.version_info >= (3, 9): def cache(__user_function: Callable[..., _T]) -> _lru_cache_wrapper[_T]: ... def _make_key( - args: Tuple[Hashable, ...], + args: tuple[Hashable, ...], kwds: SupportsItems[Any, Any], typed: bool, - kwd_mark: Tuple[object, ...] = ..., + kwd_mark: tuple[object, ...] = ..., fasttypes: set[type] = ..., tuple: type = ..., type: Any = ..., diff --git a/mypy/typeshed/stdlib/gc.pyi b/mypy/typeshed/stdlib/gc.pyi index 39d2776783ef..7c15e0f5b0a2 100644 --- a/mypy/typeshed/stdlib/gc.pyi +++ b/mypy/typeshed/stdlib/gc.pyi @@ -1,12 +1,16 @@ import sys -from typing import Any - -DEBUG_COLLECTABLE: int -DEBUG_LEAK: int -DEBUG_SAVEALL: int -DEBUG_STATS: int -DEBUG_UNCOLLECTABLE: int -callbacks: list[Any] +from typing import Any, Callable +from typing_extensions import Literal + +DEBUG_COLLECTABLE: Literal[2] +DEBUG_LEAK: Literal[38] +DEBUG_SAVEALL: Literal[32] +DEBUG_STATS: Literal[1] +DEBUG_UNCOLLECTABLE: Literal[4] + +_CallbackType = Callable[[Literal["start", "stop"], dict[str, int]], object] + +callbacks: list[_CallbackType] garbage: list[Any] def collect(generation: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/genericpath.pyi b/mypy/typeshed/stdlib/genericpath.pyi index 56683e323178..f9518750d3f1 100644 --- a/mypy/typeshed/stdlib/genericpath.pyi +++ b/mypy/typeshed/stdlib/genericpath.pyi @@ -1,6 +1,6 @@ import os -from _typeshed import BytesPath, StrOrBytesPath, StrPath, SupportsLessThanT -from typing import Sequence, Tuple, overload +from _typeshed import BytesPath, StrOrBytesPath, StrPath, SupportsRichComparisonT +from typing import Sequence, overload from typing_extensions import Literal # All overloads can return empty string. Ideally, Literal[""] would be a valid @@ -11,9 +11,9 @@ def commonprefix(m: Sequence[StrPath]) -> str: ... @overload def commonprefix(m: Sequence[BytesPath]) -> bytes | Literal[""]: ... @overload -def commonprefix(m: Sequence[list[SupportsLessThanT]]) -> Sequence[SupportsLessThanT]: ... +def commonprefix(m: Sequence[list[SupportsRichComparisonT]]) -> Sequence[SupportsRichComparisonT]: ... @overload -def commonprefix(m: Sequence[Tuple[SupportsLessThanT, ...]]) -> Sequence[SupportsLessThanT]: ... +def commonprefix(m: Sequence[tuple[SupportsRichComparisonT, ...]]) -> Sequence[SupportsRichComparisonT]: ... def exists(path: StrOrBytesPath | int) -> bool: ... def getsize(filename: StrOrBytesPath | int) -> int: ... def isfile(path: StrOrBytesPath | int) -> bool: ... diff --git a/mypy/typeshed/stdlib/gettext.pyi b/mypy/typeshed/stdlib/gettext.pyi index b408d3f7485c..1a6a9958d9f0 100644 --- a/mypy/typeshed/stdlib/gettext.pyi +++ b/mypy/typeshed/stdlib/gettext.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import StrPath -from typing import IO, Any, Container, Iterable, Sequence, Type, TypeVar, overload +from typing import IO, Any, Container, Iterable, Sequence, TypeVar, overload from typing_extensions import Literal class NullTranslations: @@ -16,8 +16,9 @@ class NullTranslations: def npgettext(self, context: str, msgid1: str, msgid2: str, n: int) -> str: ... def info(self) -> Any: ... def charset(self) -> Any: ... - def output_charset(self) -> Any: ... - def set_output_charset(self, charset: str) -> None: ... + if sys.version_info < (3, 11): + def output_charset(self) -> Any: ... + def set_output_charset(self, charset: str) -> None: ... def install(self, names: Container[str] | None = ...) -> None: ... class GNUTranslations(NullTranslations): @@ -26,51 +27,84 @@ class GNUTranslations(NullTranslations): CONTEXT: str VERSIONS: Sequence[int] +@overload # ignores incompatible overloads +def find( # type: ignore[misc] + domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., all: Literal[False] = ... +) -> str | None: ... +@overload +def find( + domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., all: Literal[True] = ... +) -> list[str]: ... +@overload def find(domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., all: bool = ...) -> Any: ... _T = TypeVar("_T") -@overload -def translation( - domain: str, - localedir: StrPath | None = ..., - languages: Iterable[str] | None = ..., - class_: None = ..., - fallback: bool = ..., - codeset: str | None = ..., -) -> NullTranslations: ... -@overload -def translation( - domain: str, - localedir: StrPath | None = ..., - languages: Iterable[str] | None = ..., - class_: Type[_T] = ..., - fallback: Literal[False] = ..., - codeset: str | None = ..., -) -> _T: ... -@overload -def translation( - domain: str, - localedir: StrPath | None = ..., - languages: Iterable[str] | None = ..., - class_: Type[Any] = ..., - fallback: Literal[True] = ..., - codeset: str | None = ..., -) -> Any: ... -def install( - domain: str, localedir: StrPath | None = ..., codeset: str | None = ..., names: Container[str] | None = ... -) -> None: ... +if sys.version_info >= (3, 11): + @overload + def translation( + domain: str, + localedir: StrPath | None = ..., + languages: Iterable[str] | None = ..., + class_: None = ..., + fallback: bool = ..., + ) -> NullTranslations: ... + @overload + def translation( + domain: str, + localedir: StrPath | None = ..., + languages: Iterable[str] | None = ..., + class_: type[_T] = ..., + fallback: Literal[False] = ..., + ) -> _T: ... + @overload + def translation( + domain: str, + localedir: StrPath | None = ..., + languages: Iterable[str] | None = ..., + class_: type[Any] = ..., + fallback: Literal[True] = ..., + ) -> Any: ... + def install(domain: str, localedir: StrPath | None = ..., names: Container[str] | None = ...) -> None: ... + +else: + @overload + def translation( + domain: str, + localedir: StrPath | None = ..., + languages: Iterable[str] | None = ..., + class_: None = ..., + fallback: bool = ..., + codeset: str | None = ..., + ) -> NullTranslations: ... + @overload + def translation( + domain: str, + localedir: StrPath | None = ..., + languages: Iterable[str] | None = ..., + class_: type[_T] = ..., + fallback: Literal[False] = ..., + codeset: str | None = ..., + ) -> _T: ... + @overload + def translation( + domain: str, + localedir: StrPath | None = ..., + languages: Iterable[str] | None = ..., + class_: type[Any] = ..., + fallback: Literal[True] = ..., + codeset: str | None = ..., + ) -> Any: ... + def install( + domain: str, localedir: StrPath | None = ..., codeset: str | None = ..., names: Container[str] | None = ... + ) -> None: ... + def textdomain(domain: str | None = ...) -> str: ... def bindtextdomain(domain: str, localedir: StrPath | None = ...) -> str: ... -def bind_textdomain_codeset(domain: str, codeset: str | None = ...) -> str: ... def dgettext(domain: str, message: str) -> str: ... -def ldgettext(domain: str, message: str) -> str: ... def dngettext(domain: str, msgid1: str, msgid2: str, n: int) -> str: ... -def ldngettext(domain: str, msgid1: str, msgid2: str, n: int) -> str: ... def gettext(message: str) -> str: ... -def lgettext(message: str) -> str: ... def ngettext(msgid1: str, msgid2: str, n: int) -> str: ... -def lngettext(msgid1: str, msgid2: str, n: int) -> str: ... if sys.version_info >= (3, 8): def pgettext(context: str, message: str) -> str: ... @@ -78,4 +112,11 @@ if sys.version_info >= (3, 8): def npgettext(context: str, msgid1: str, msgid2: str, n: int) -> str: ... def dnpgettext(domain: str, context: str, msgid1: str, msgid2: str, n: int) -> str: ... +if sys.version_info < (3, 11): + def lgettext(message: str) -> str: ... + def ldgettext(domain: str, message: str) -> str: ... + def lngettext(msgid1: str, msgid2: str, n: int) -> str: ... + def ldngettext(domain: str, msgid1: str, msgid2: str, n: int) -> str: ... + def bind_textdomain_codeset(domain: str, codeset: str | None = ...) -> str: ... + Catalog = translation diff --git a/mypy/typeshed/stdlib/graphlib.pyi b/mypy/typeshed/stdlib/graphlib.pyi index 0872af4a54a4..96d64cbce18c 100644 --- a/mypy/typeshed/stdlib/graphlib.pyi +++ b/mypy/typeshed/stdlib/graphlib.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsItems -from typing import Generic, Iterable, Tuple, TypeVar +from typing import Generic, Iterable, TypeVar _T = TypeVar("_T") @@ -10,7 +10,7 @@ class TopologicalSorter(Generic[_T]): def is_active(self) -> bool: ... def __bool__(self) -> bool: ... def done(self, *nodes: _T) -> None: ... - def get_ready(self) -> Tuple[_T, ...]: ... + def get_ready(self) -> tuple[_T, ...]: ... def static_order(self) -> Iterable[_T]: ... class CycleError(ValueError): ... diff --git a/mypy/typeshed/stdlib/grp.pyi b/mypy/typeshed/stdlib/grp.pyi index 08cbe6b86476..b416269921d6 100644 --- a/mypy/typeshed/stdlib/grp.pyi +++ b/mypy/typeshed/stdlib/grp.pyi @@ -1,11 +1,19 @@ -from typing import NamedTuple +import sys +from _typeshed import structseq +from typing import Any, Optional +from typing_extensions import final -class struct_group(NamedTuple): - gr_name: str - gr_passwd: str | None - gr_gid: int - gr_mem: list[str] - -def getgrall() -> list[struct_group]: ... -def getgrgid(id: int) -> struct_group: ... -def getgrnam(name: str) -> struct_group: ... +if sys.platform != "win32": + @final + class struct_group(structseq[Any], tuple[str, Optional[str], int, list[str]]): + @property + def gr_name(self) -> str: ... + @property + def gr_passwd(self) -> str | None: ... + @property + def gr_gid(self) -> int: ... + @property + def gr_mem(self) -> list[str]: ... + def getgrall() -> list[struct_group]: ... + def getgrgid(id: int) -> struct_group: ... + def getgrnam(name: str) -> struct_group: ... diff --git a/mypy/typeshed/stdlib/hashlib.pyi b/mypy/typeshed/stdlib/hashlib.pyi index e39f2f25326e..fad3c5aad457 100644 --- a/mypy/typeshed/stdlib/hashlib.pyi +++ b/mypy/typeshed/stdlib/hashlib.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import ReadableBuffer, Self from typing import AbstractSet -class _Hash(object): +class _Hash: @property def digest_size(self) -> int: ... @property @@ -49,7 +49,7 @@ def pbkdf2_hmac( hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: int | None = ... ) -> bytes: ... -class _VarLenHash(object): +class _VarLenHash: digest_size: int block_size: int name: str diff --git a/mypy/typeshed/stdlib/heapq.pyi b/mypy/typeshed/stdlib/heapq.pyi index 81ee02582a6a..fd3c2db8ad66 100644 --- a/mypy/typeshed/stdlib/heapq.pyi +++ b/mypy/typeshed/stdlib/heapq.pyi @@ -1,4 +1,4 @@ -from _typeshed import SupportsLessThan +from _typeshed import SupportsRichComparison from typing import Any, Callable, Iterable, TypeVar _T = TypeVar("_T") @@ -9,6 +9,6 @@ def heappushpop(__heap: list[_T], __item: _T) -> _T: ... def heapify(__heap: list[Any]) -> None: ... def heapreplace(__heap: list[_T], __item: _T) -> _T: ... def merge(*iterables: Iterable[_T], key: Callable[[_T], Any] | None = ..., reverse: bool = ...) -> Iterable[_T]: ... -def nlargest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsLessThan] | None = ...) -> list[_T]: ... -def nsmallest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsLessThan] | None = ...) -> list[_T]: ... +def nlargest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsRichComparison] | None = ...) -> list[_T]: ... +def nsmallest(n: int, iterable: Iterable[_T], key: Callable[[_T], SupportsRichComparison] | None = ...) -> list[_T]: ... def _heapify_max(__x: list[Any]) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/hmac.pyi b/mypy/typeshed/stdlib/hmac.pyi index 440bddd7919c..88c88631f99a 100644 --- a/mypy/typeshed/stdlib/hmac.pyi +++ b/mypy/typeshed/stdlib/hmac.pyi @@ -7,6 +7,9 @@ from typing import Any, AnyStr, Callable, Union, overload _Hash = Any _DigestMod = Union[str, Callable[[], _Hash], ModuleType] +trans_5C: bytes +trans_36: bytes + digest_size: None if sys.version_info >= (3, 8): diff --git a/mypy/typeshed/stdlib/html/parser.pyi b/mypy/typeshed/stdlib/html/parser.pyi index fec3f3509522..60e0de51d3b8 100644 --- a/mypy/typeshed/stdlib/html/parser.pyi +++ b/mypy/typeshed/stdlib/html/parser.pyi @@ -1,5 +1,5 @@ from _markupbase import ParserBase -from typing import Tuple +from typing import Pattern class HTMLParser(ParserBase): def __init__(self, *, convert_charrefs: bool = ...) -> None: ... @@ -18,7 +18,7 @@ class HTMLParser(ParserBase): def handle_decl(self, decl: str) -> None: ... def handle_pi(self, data: str) -> None: ... def unknown_decl(self, data: str) -> None: ... - CDATA_CONTENT_ELEMENTS: Tuple[str, ...] + CDATA_CONTENT_ELEMENTS: tuple[str, ...] def check_for_whole_start_tag(self, i: int) -> int: ... # undocumented def clear_cdata_mode(self) -> None: ... # undocumented def goahead(self, end: bool) -> None: ... # undocumented @@ -28,3 +28,8 @@ class HTMLParser(ParserBase): def parse_pi(self, i: int) -> int: ... # undocumented def parse_starttag(self, i: int) -> int: ... # undocumented def set_cdata_mode(self, elem: str) -> None: ... # undocumented + rawdata: str # undocumented + cdata_elem: str | None # undocumented + convert_charrefs: bool # undocumented + interesting: Pattern[str] # undocumented + lasttag: str # undocumented diff --git a/mypy/typeshed/stdlib/http/client.pyi b/mypy/typeshed/stdlib/http/client.pyi index c450db587135..158a04c21f2b 100644 --- a/mypy/typeshed/stdlib/http/client.pyi +++ b/mypy/typeshed/stdlib/http/client.pyi @@ -5,7 +5,7 @@ import sys import types from _typeshed import Self, WriteableBuffer from socket import socket -from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, Mapping, Protocol, Type, TypeVar, Union, overload +from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, Mapping, Protocol, TypeVar, Union, overload _DataType = Union[bytes, IO[Any], Iterable[bytes], str] _T = TypeVar("_T") @@ -78,7 +78,7 @@ class HTTPMessage(email.message.Message): def parse_headers(fp: io.BufferedIOBase, _class: Callable[[], email.message.Message] = ...) -> HTTPMessage: ... -class HTTPResponse(io.BufferedIOBase, BinaryIO): +class HTTPResponse(io.BufferedIOBase, BinaryIO): # type: ignore # argument disparities between base classes msg: HTTPMessage headers: HTTPMessage version: int @@ -96,7 +96,7 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): def read(self, amt: int | None = ...) -> bytes: ... def read1(self, n: int = ...) -> bytes: ... def readinto(self, b: WriteableBuffer) -> int: ... - def readline(self, limit: int = ...) -> bytes: ... # type: ignore + def readline(self, limit: int = ...) -> bytes: ... # type: ignore[override] @overload def getheader(self, name: str) -> str | None: ... @overload @@ -107,7 +107,7 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): def __iter__(self) -> Iterator[bytes]: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None ) -> bool | None: ... def info(self) -> email.message.Message: ... def geturl(self) -> str: ... @@ -135,7 +135,7 @@ class HTTPConnection: auto_open: int # undocumented debuglevel: int default_port: int # undocumented - response_class: Type[HTTPResponse] # undocumented + response_class: type[HTTPResponse] # undocumented timeout: float | None host: str port: int diff --git a/mypy/typeshed/stdlib/http/cookiejar.pyi b/mypy/typeshed/stdlib/http/cookiejar.pyi index f37fb19cebe9..1b4deb9b2ca1 100644 --- a/mypy/typeshed/stdlib/http/cookiejar.pyi +++ b/mypy/typeshed/stdlib/http/cookiejar.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import StrPath from http.client import HTTPResponse -from typing import ClassVar, Iterable, Iterator, Pattern, Sequence, Tuple, TypeVar, overload +from typing import ClassVar, Iterable, Iterator, Pattern, Sequence, TypeVar, overload from urllib.request import Request _T = TypeVar("_T") @@ -27,8 +27,6 @@ class CookieJar(Iterable[Cookie]): def clear_expired_cookies(self) -> None: ... # undocumented def __iter__(self) -> Iterator[Cookie]: ... def __len__(self) -> int: ... - def __repr__(self) -> str: ... - def __str__(self) -> str: ... class FileCookieJar(CookieJar): filename: str @@ -102,10 +100,10 @@ class DefaultCookiePolicy(CookiePolicy): strict_ns_set_initial_dollar: bool = ..., strict_ns_set_path: bool = ..., ) -> None: ... - def blocked_domains(self) -> Tuple[str, ...]: ... + def blocked_domains(self) -> tuple[str, ...]: ... def set_blocked_domains(self, blocked_domains: Sequence[str]) -> None: ... def is_blocked(self, domain: str) -> bool: ... - def allowed_domains(self) -> Tuple[str, ...] | None: ... + def allowed_domains(self) -> tuple[str, ...] | None: ... def set_allowed_domains(self, allowed_domains: Sequence[str] | None) -> None: ... def is_not_allowed(self, domain: str) -> bool: ... def set_ok_version(self, cookie: Cookie, request: Request) -> bool: ... # undocumented diff --git a/mypy/typeshed/stdlib/http/cookies.pyi b/mypy/typeshed/stdlib/http/cookies.pyi index 7e9513adb1a1..211fd37662d4 100644 --- a/mypy/typeshed/stdlib/http/cookies.pyi +++ b/mypy/typeshed/stdlib/http/cookies.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, Dict, Generic, Iterable, Mapping, TypeVar, Union, overload +from typing import Any, Generic, Iterable, Mapping, TypeVar, Union, overload if sys.version_info >= (3, 9): from types import GenericAlias @@ -18,7 +18,7 @@ def _unquote(str: str) -> str: ... class CookieError(Exception): ... -class Morsel(Dict[str, Any], Generic[_T]): +class Morsel(dict[str, Any], Generic[_T]): value: str coded_value: _T key: str @@ -29,7 +29,7 @@ class Morsel(Dict[str, Any], Generic[_T]): def set(self, key: str, val: str, coded_val: _T, LegalChars: str = ...) -> None: ... def setdefault(self, key: str, val: str | None = ...) -> str: ... # The dict update can also get a keywords argument so this is incompatible - @overload # type: ignore + @overload # type: ignore[override] def update(self, values: Mapping[str, str]) -> None: ... @overload def update(self, values: Iterable[tuple[str, str]]) -> None: ... @@ -40,7 +40,7 @@ class Morsel(Dict[str, Any], Generic[_T]): if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... -class BaseCookie(Dict[str, Morsel[_T]], Generic[_T]): +class BaseCookie(dict[str, Morsel[_T]], Generic[_T]): def __init__(self, input: _DataType | None = ...) -> None: ... def value_decode(self, val: str) -> _T: ... def value_encode(self, val: _T) -> str: ... diff --git a/mypy/typeshed/stdlib/imaplib.pyi b/mypy/typeshed/stdlib/imaplib.pyi index a9f19048c9ae..33b99239ea85 100644 --- a/mypy/typeshed/stdlib/imaplib.pyi +++ b/mypy/typeshed/stdlib/imaplib.pyi @@ -5,21 +5,21 @@ from _typeshed import Self from socket import socket as _socket from ssl import SSLContext, SSLSocket from types import TracebackType -from typing import IO, Any, Callable, List, Pattern, Tuple, Type, Union +from typing import IO, Any, Callable, Pattern, Union from typing_extensions import Literal # TODO: Commands should use their actual return types, not this type alias. # E.g. Tuple[Literal["OK"], List[bytes]] -_CommandResults = Tuple[str, List[Any]] +_CommandResults = tuple[str, list[Any]] -_AnyResponseData = Union[List[None], List[Union[bytes, Tuple[bytes, bytes]]]] +_AnyResponseData = Union[list[None], list[Union[bytes, tuple[bytes, bytes]]]] _list = list # conflicts with a method named "list" class IMAP4: - error: Type[Exception] - abort: Type[Exception] - readonly: Type[Exception] + error: type[Exception] + abort: type[Exception] + readonly: type[Exception] mustquote: Pattern[str] debug: int state: str @@ -63,7 +63,7 @@ class IMAP4: def deleteacl(self, mailbox: str, who: str) -> _CommandResults: ... def enable(self, capability: str) -> _CommandResults: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, t: Type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... + def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... def expunge(self) -> _CommandResults: ... def fetch(self, message_set: str, message_parts: str) -> tuple[str, _AnyResponseData]: ... def getacl(self, mailbox: str) -> _CommandResults: ... diff --git a/mypy/typeshed/stdlib/imp.pyi b/mypy/typeshed/stdlib/imp.pyi index 88f2e789329b..ec09d18de32c 100644 --- a/mypy/typeshed/stdlib/imp.pyi +++ b/mypy/typeshed/stdlib/imp.pyi @@ -1,7 +1,7 @@ import types from _typeshed import StrPath from os import PathLike -from typing import IO, Any, Protocol, TypeVar +from typing import IO, Any, Protocol from _imp import ( acquire_lock as acquire_lock, @@ -15,8 +15,6 @@ from _imp import ( release_lock as release_lock, ) -_T = TypeVar("_T") - SEARCH_ERROR: int PY_SOURCE: int PY_COMPILED: int diff --git a/mypy/typeshed/stdlib/importlib/abc.pyi b/mypy/typeshed/stdlib/importlib/abc.pyi index 2e18f3f899a2..9bb370dfd7e8 100644 --- a/mypy/typeshed/stdlib/importlib/abc.pyi +++ b/mypy/typeshed/stdlib/importlib/abc.pyi @@ -12,8 +12,8 @@ from _typeshed import ( from abc import ABCMeta, abstractmethod from importlib.machinery import ModuleSpec from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper -from typing import IO, Any, BinaryIO, Iterator, Mapping, Protocol, Sequence, Union, overload -from typing_extensions import Literal, runtime_checkable +from typing import IO, Any, BinaryIO, Iterator, Mapping, NoReturn, Protocol, Sequence, Union, overload, runtime_checkable +from typing_extensions import Literal _Path = Union[bytes, str] @@ -85,8 +85,12 @@ if sys.version_info >= (3, 7): def open_resource(self, resource: StrOrBytesPath) -> IO[bytes]: ... @abstractmethod def resource_path(self, resource: StrOrBytesPath) -> str: ... - @abstractmethod - def is_resource(self, name: str) -> bool: ... + if sys.version_info >= (3, 10): + @abstractmethod + def is_resource(self, path: str) -> bool: ... + else: + @abstractmethod + def is_resource(self, name: str) -> bool: ... @abstractmethod def contents(self) -> Iterator[str]: ... @@ -169,3 +173,10 @@ if sys.version_info >= (3, 9): def read_bytes(self) -> bytes: ... @abstractmethod def read_text(self, encoding: str | None = ...) -> str: ... + class TraversableResources(ResourceReader): + @abstractmethod + def files(self) -> Traversable: ... + def open_resource(self, resource: StrPath) -> BufferedReader: ... # type: ignore[override] + def resource_path(self, resource: Any) -> NoReturn: ... + def is_resource(self, path: StrPath) -> bool: ... + def contents(self) -> Iterator[str]: ... diff --git a/mypy/typeshed/stdlib/importlib/machinery.pyi b/mypy/typeshed/stdlib/importlib/machinery.pyi index 432bec901161..acce9885092a 100644 --- a/mypy/typeshed/stdlib/importlib/machinery.pyi +++ b/mypy/typeshed/stdlib/importlib/machinery.pyi @@ -1,6 +1,10 @@ import importlib.abc +import sys import types -from typing import Any, Callable, Sequence +from typing import Any, Callable, Iterable, Sequence + +if sys.version_info >= (3, 8): + from importlib.metadata import DistributionFinder, PathDistribution class ModuleSpec: def __init__( @@ -41,10 +45,16 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader) # Loader @staticmethod def module_repr(module: types.ModuleType) -> str: ... - @classmethod - def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: ... - @classmethod - def exec_module(cls, module: types.ModuleType) -> None: ... + if sys.version_info >= (3, 10): + @staticmethod + def create_module(spec: ModuleSpec) -> types.ModuleType | None: ... + @staticmethod + def exec_module(module: types.ModuleType) -> None: ... + else: + @classmethod + def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: ... + @classmethod + def exec_module(cls, module: types.ModuleType) -> None: ... class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): # MetaPathFinder @@ -66,8 +76,12 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): # Loader @staticmethod def module_repr(m: types.ModuleType) -> str: ... - @classmethod - def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: ... + if sys.version_info >= (3, 10): + @staticmethod + def create_module(spec: ModuleSpec) -> types.ModuleType | None: ... + else: + @classmethod + def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: ... @staticmethod def exec_module(module: types.ModuleType) -> None: ... @@ -80,8 +94,18 @@ class WindowsRegistryFinder(importlib.abc.MetaPathFinder): ) -> ModuleSpec | None: ... class PathFinder: - @classmethod - def invalidate_caches(cls) -> None: ... + if sys.version_info >= (3, 10): + @staticmethod + def invalidate_caches() -> None: ... + else: + @classmethod + def invalidate_caches(cls) -> None: ... + if sys.version_info >= (3, 10): + @staticmethod + def find_distributions(context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... + elif sys.version_info >= (3, 8): + @classmethod + def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... @classmethod def find_spec( cls, fullname: str, path: Sequence[bytes | str] | None = ..., target: types.ModuleType | None = ... @@ -105,10 +129,10 @@ class FileFinder(importlib.abc.PathEntryFinder): cls, *loader_details: tuple[importlib.abc.Loader, list[str]] ) -> Callable[[str], importlib.abc.PathEntryFinder]: ... -class SourceFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): +class SourceFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): # type: ignore # argument disparities def set_data(self, path: importlib.abc._Path, data: bytes, *, _mode: int = ...) -> None: ... -class SourcelessFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): ... +class SourcelessFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): ... # type: ignore # argument disparities class ExtensionFileLoader(importlib.abc.ExecutionLoader): def __init__(self, name: str, path: importlib.abc._Path) -> None: ... diff --git a/mypy/typeshed/stdlib/importlib/metadata.pyi b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi similarity index 80% rename from mypy/typeshed/stdlib/importlib/metadata.pyi rename to mypy/typeshed/stdlib/importlib/metadata/__init__.pyi index 2c1041b76503..a9e223149b52 100644 --- a/mypy/typeshed/stdlib/importlib/metadata.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi @@ -7,9 +7,10 @@ from email.message import Message from importlib.abc import MetaPathFinder from os import PathLike from pathlib import Path -from typing import Any, Iterable, NamedTuple, Tuple, overload +from typing import Any, ClassVar, Iterable, NamedTuple, Pattern, overload if sys.version_info >= (3, 10): + from importlib.metadata._meta import PackageMetadata as PackageMetadata def packages_distributions() -> Mapping[str, list[str]]: ... if sys.version_info >= (3, 8): @@ -19,9 +20,18 @@ if sys.version_info >= (3, 8): value: str group: str class EntryPoint(_EntryPointBase): + pattern: ClassVar[Pattern[str]] def load(self) -> Any: ... # Callable[[], Any] or an importable module @property def extras(self) -> list[str]: ... + if sys.version_info >= (3, 9): + @property + def module(self) -> str: ... + @property + def attr(self) -> str: ... + if sys.version_info >= (3, 10): + dist: ClassVar[Distribution | None] + def matches(self, **params: Any) -> bool: ... # undocumented class PackagePath(pathlib.PurePosixPath): def read_text(self, encoding: str = ...) -> str: ... def read_binary(self) -> bytes: ... @@ -61,6 +71,9 @@ if sys.version_info >= (3, 8): def files(self) -> list[PackagePath] | None: ... @property def requires(self) -> list[str] | None: ... + if sys.version_info >= (3, 10): + @property + def name(self) -> str: ... class DistributionFinder(MetaPathFinder): class Context: name: str | None @@ -72,6 +85,9 @@ if sys.version_info >= (3, 8): class MetadataPathFinder(DistributionFinder): @classmethod def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ... + if sys.version_info >= (3, 10): + # Yes, this is an instance method that has argumend named "cls" + def invalidate_caches(cls) -> None: ... # type: ignore class PathDistribution(Distribution): def __init__(self, path: Path) -> None: ... def read_text(self, filename: StrPath) -> str: ... @@ -85,6 +101,6 @@ if sys.version_info >= (3, 8): ) -> Iterable[Distribution]: ... def metadata(distribution_name: str) -> Message: ... def version(distribution_name: str) -> str: ... - def entry_points() -> dict[str, Tuple[EntryPoint, ...]]: ... + def entry_points() -> dict[str, tuple[EntryPoint, ...]]: ... def files(distribution_name: str) -> list[PackagePath] | None: ... def requires(distribution_name: str) -> list[str] | None: ... diff --git a/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi b/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi new file mode 100644 index 000000000000..a5e5733396d7 --- /dev/null +++ b/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi @@ -0,0 +1,18 @@ +from typing import Any, Iterator, Protocol, TypeVar + +_T = TypeVar("_T") + +class PackageMetadata(Protocol): + def __len__(self) -> int: ... + def __contains__(self, item: str) -> bool: ... + def __getitem__(self, key: str) -> str: ... + def __iter__(self) -> Iterator[str]: ... + def get_all(self, name: str, failobj: _T = ...) -> list[Any] | _T: ... + @property + def json(self) -> dict[str, str | list[str]]: ... + +class SimplePath(Protocol): + def joinpath(self) -> SimplePath: ... + def __div__(self) -> SimplePath: ... + def parent(self) -> SimplePath: ... + def read_text(self) -> str: ... diff --git a/mypy/typeshed/stdlib/importlib/resources.pyi b/mypy/typeshed/stdlib/importlib/resources.pyi index 194c0bac2b6a..38b891fb72e7 100644 --- a/mypy/typeshed/stdlib/importlib/resources.pyi +++ b/mypy/typeshed/stdlib/importlib/resources.pyi @@ -1,25 +1,25 @@ +import os import sys -from typing import Any +from contextlib import AbstractContextManager +from pathlib import Path +from types import ModuleType +from typing import Any, BinaryIO, Iterator, TextIO, Union -# This is a >=3.7 module, so we conditionally include its source. -if sys.version_info >= (3, 7): - import os - from contextlib import AbstractContextManager - from pathlib import Path - from types import ModuleType - from typing import BinaryIO, Iterator, TextIO, Union +Package = Union[str, ModuleType] +Resource = Union[str, os.PathLike[Any]] - Package = Union[str, ModuleType] - Resource = Union[str, os.PathLike[Any]] - def open_binary(package: Package, resource: Resource) -> BinaryIO: ... - def open_text(package: Package, resource: Resource, encoding: str = ..., errors: str = ...) -> TextIO: ... - def read_binary(package: Package, resource: Resource) -> bytes: ... - def read_text(package: Package, resource: Resource, encoding: str = ..., errors: str = ...) -> str: ... - def path(package: Package, resource: Resource) -> AbstractContextManager[Path]: ... - def is_resource(package: Package, name: str) -> bool: ... - def contents(package: Package) -> Iterator[str]: ... +def open_binary(package: Package, resource: Resource) -> BinaryIO: ... +def open_text(package: Package, resource: Resource, encoding: str = ..., errors: str = ...) -> TextIO: ... +def read_binary(package: Package, resource: Resource) -> bytes: ... +def read_text(package: Package, resource: Resource, encoding: str = ..., errors: str = ...) -> str: ... +def path(package: Package, resource: Resource) -> AbstractContextManager[Path]: ... +def is_resource(package: Package, name: str) -> bool: ... +def contents(package: Package) -> Iterator[str]: ... if sys.version_info >= (3, 9): from importlib.abc import Traversable def files(package: Package) -> Traversable: ... def as_file(path: Traversable) -> AbstractContextManager[Path]: ... + +if sys.version_info >= (3, 10): + from importlib.abc import ResourceReader as ResourceReader diff --git a/mypy/typeshed/stdlib/importlib/util.pyi b/mypy/typeshed/stdlib/importlib/util.pyi index 30b8765fad04..c759d7def5be 100644 --- a/mypy/typeshed/stdlib/importlib/util.pyi +++ b/mypy/typeshed/stdlib/importlib/util.pyi @@ -1,5 +1,6 @@ import importlib.abc import importlib.machinery +import sys import types from _typeshed import StrOrBytesPath from typing import Any, Callable @@ -7,9 +8,9 @@ from typing_extensions import ParamSpec _P = ParamSpec("_P") -def module_for_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... # type: ignore -def set_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... # type: ignore -def set_package(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... # type: ignore +def module_for_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... +def set_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... +def set_package(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ... def resolve_name(name: str, package: str | None) -> str: ... MAGIC_NUMBER: bytes @@ -36,3 +37,6 @@ class LazyLoader(importlib.abc.Loader): def factory(cls, loader: importlib.abc.Loader) -> Callable[..., LazyLoader]: ... def create_module(self, spec: importlib.machinery.ModuleSpec) -> types.ModuleType | None: ... def exec_module(self, module: types.ModuleType) -> None: ... + +if sys.version_info >= (3, 7): + def source_hash(source_bytes: bytes) -> int: ... diff --git a/mypy/typeshed/stdlib/inspect.pyi b/mypy/typeshed/stdlib/inspect.pyi index 88002cf205b1..26ea5bacab2c 100644 --- a/mypy/typeshed/stdlib/inspect.pyi +++ b/mypy/typeshed/stdlib/inspect.pyi @@ -23,7 +23,7 @@ from types import ( 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 import Any, ClassVar, Coroutine, NamedTuple, Protocol, TypeVar, Union from typing_extensions import Literal, TypeGuard # @@ -41,22 +41,24 @@ class BlockFinder: last: int def tokeneater(self, type: int, token: str, srowcol: tuple[int, int], erowcol: tuple[int, int], line: str) -> None: ... -CO_OPTIMIZED: int -CO_NEWLOCALS: int -CO_VARARGS: int -CO_VARKEYWORDS: int -CO_NESTED: int -CO_GENERATOR: int -CO_NOFREE: int -CO_COROUTINE: int -CO_ITERABLE_COROUTINE: int -CO_ASYNC_GENERATOR: int -TPFLAGS_IS_ABSTRACT: int +CO_OPTIMIZED: Literal[1] +CO_NEWLOCALS: Literal[2] +CO_VARARGS: Literal[4] +CO_VARKEYWORDS: Literal[8] +CO_NESTED: Literal[16] +CO_GENERATOR: Literal[32] +CO_NOFREE: Literal[64] +CO_COROUTINE: Literal[128] +CO_ITERABLE_COROUTINE: Literal[256] +CO_ASYNC_GENERATOR: Literal[512] +TPFLAGS_IS_ABSTRACT: Literal[1048576] + +modulesbyfile: dict[str, Any] def getmembers(object: object, predicate: Callable[[Any], bool] | None = ...) -> list[tuple[str, Any]]: ... def getmodulename(path: str) -> str | None: ... def ismodule(object: object) -> TypeGuard[ModuleType]: ... -def isclass(object: object) -> TypeGuard[Type[Any]]: ... +def isclass(object: object) -> TypeGuard[type[Any]]: ... def ismethod(object: object) -> TypeGuard[MethodType]: ... def isfunction(object: object) -> TypeGuard[FunctionType]: ... @@ -93,14 +95,7 @@ def isframe(object: object) -> TypeGuard[FrameType]: ... def iscode(object: object) -> TypeGuard[CodeType]: ... def isbuiltin(object: object) -> TypeGuard[BuiltinFunctionType]: ... -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: +if sys.version_info >= (3, 7): def isroutine( object: object, ) -> TypeGuard[ @@ -116,6 +111,13 @@ else: def ismethoddescriptor(object: object) -> TypeGuard[MethodDescriptorType]: ... def ismemberdescriptor(object: object) -> TypeGuard[MemberDescriptorType]: ... +else: + def isroutine( + object: object, + ) -> TypeGuard[FunctionType | LambdaType | MethodType | BuiltinFunctionType | BuiltinMethodType]: ... + def ismethoddescriptor(object: object) -> bool: ... + def ismemberdescriptor(object: object) -> bool: ... + def isabstract(object: object) -> bool: ... def isgetsetdescriptor(object: object) -> TypeGuard[GetSetDescriptorType]: ... def isdatadescriptor(object: object) -> TypeGuard[_SupportsSet[Any, Any] | _SupportsDelete[Any]]: ... @@ -123,7 +125,7 @@ def isdatadescriptor(object: object) -> TypeGuard[_SupportsSet[Any, Any] | _Supp # # Retrieving source code # -_SourceObjectType = Union[ModuleType, Type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] +_SourceObjectType = Union[ModuleType, type[Any], MethodType, FunctionType, TracebackType, FrameType, CodeType, Callable[..., Any]] def findsource(object: _SourceObjectType) -> tuple[list[str], int]: ... def getabsfile(object: _SourceObjectType, _filename: str | None = ...) -> str: ... @@ -170,7 +172,7 @@ class Signature: def bind(self, *args: Any, **kwargs: Any) -> BoundArguments: ... def bind_partial(self, *args: Any, **kwargs: Any) -> BoundArguments: ... def replace( - self: Self, *, parameters: Sequence[Parameter] | Type[_void] | None = ..., return_annotation: Any = ... + self: Self, *, parameters: Sequence[Parameter] | type[_void] | None = ..., return_annotation: Any = ... ) -> Self: ... if sys.version_info >= (3, 10): @classmethod @@ -189,7 +191,7 @@ class Signature: if sys.version_info >= (3, 10): def get_annotations( - obj: Callable[..., Any] | Type[Any] | ModuleType, + obj: Callable[..., Any] | type[Any] | ModuleType, *, globals: Mapping[str, Any] | None = ..., locals: Mapping[str, Any] | None = ..., @@ -205,33 +207,38 @@ class _ParameterKind(enum.IntEnum): VAR_KEYWORD: int if sys.version_info >= (3, 8): - description: str + @property + def description(self) -> str: ... class Parameter: def __init__(self, name: str, kind: _ParameterKind, *, default: Any = ..., annotation: Any = ...) -> None: ... empty = _empty - name: str - default: Any - annotation: Any - kind: _ParameterKind POSITIONAL_ONLY: ClassVar[Literal[_ParameterKind.POSITIONAL_ONLY]] POSITIONAL_OR_KEYWORD: ClassVar[Literal[_ParameterKind.POSITIONAL_OR_KEYWORD]] VAR_POSITIONAL: ClassVar[Literal[_ParameterKind.VAR_POSITIONAL]] KEYWORD_ONLY: ClassVar[Literal[_ParameterKind.KEYWORD_ONLY]] VAR_KEYWORD: ClassVar[Literal[_ParameterKind.VAR_KEYWORD]] + @property + def name(self) -> str: ... + @property + def default(self) -> Any: ... + @property + def kind(self) -> _ParameterKind: ... + @property + def annotation(self) -> Any: ... def replace( self: Self, *, - name: str | Type[_void] = ..., - kind: _ParameterKind | Type[_void] = ..., + name: str | type[_void] = ..., + kind: _ParameterKind | type[_void] = ..., default: Any = ..., annotation: Any = ..., ) -> Self: ... class BoundArguments: arguments: OrderedDict[str, Any] - args: Tuple[Any, ...] + args: tuple[Any, ...] kwargs: dict[str, Any] signature: Signature def __init__(self, signature: Signature, arguments: OrderedDict[str, Any]) -> None: ... @@ -245,13 +252,7 @@ class BoundArguments: # seem to be supporting this at the moment: # _ClassTreeItem = list[_ClassTreeItem] | Tuple[type, Tuple[type, ...]] def getclasstree(classes: list[type], unique: bool = ...) -> list[Any]: ... -def walktree(classes: list[type], children: dict[Type[Any], list[type]], parent: Type[Any] | None) -> list[Any]: ... - -class ArgSpec(NamedTuple): - args: list[str] - varargs: str | None - keywords: str | None - defaults: Tuple[Any, ...] +def walktree(classes: list[type], children: dict[type[Any], list[type]], parent: type[Any] | None) -> list[Any]: ... class Arguments(NamedTuple): args: list[str] @@ -259,13 +260,20 @@ class Arguments(NamedTuple): varkw: str | None def getargs(co: CodeType) -> Arguments: ... -def getargspec(func: object) -> ArgSpec: ... + +if sys.version_info < (3, 11): + class ArgSpec(NamedTuple): + args: list[str] + varargs: str | None + keywords: str | None + defaults: tuple[Any, ...] + def getargspec(func: object) -> ArgSpec: ... class FullArgSpec(NamedTuple): args: list[str] varargs: str | None varkw: str | None - defaults: Tuple[Any, ...] | None + defaults: tuple[Any, ...] | None kwonlyargs: list[str] kwonlydefaults: dict[str, Any] | None annotations: dict[str, Any] @@ -281,21 +289,24 @@ class ArgInfo(NamedTuple): def getargvalues(frame: FrameType) -> ArgInfo: ... def formatannotation(annotation: object, base_module: str | None = ...) -> str: ... def formatannotationrelativeto(object: object) -> Callable[[object], str]: ... -def formatargspec( - args: list[str], - varargs: str | None = ..., - varkw: str | None = ..., - defaults: Tuple[Any, ...] | None = ..., - kwonlyargs: Sequence[str] | None = ..., - kwonlydefaults: dict[str, Any] | None = ..., - annotations: dict[str, Any] = ..., - formatarg: Callable[[str], str] = ..., - formatvarargs: Callable[[str], str] = ..., - formatvarkw: Callable[[str], str] = ..., - formatvalue: Callable[[Any], str] = ..., - formatreturns: Callable[[Any], str] = ..., - formatannotation: Callable[[Any], str] = ..., -) -> str: ... + +if sys.version_info < (3, 11): + def formatargspec( + args: list[str], + varargs: str | None = ..., + varkw: str | None = ..., + defaults: tuple[Any, ...] | None = ..., + kwonlyargs: Sequence[str] | None = ..., + kwonlydefaults: dict[str, Any] | None = ..., + annotations: dict[str, Any] = ..., + formatarg: Callable[[str], str] = ..., + formatvarargs: Callable[[str], str] = ..., + formatvarkw: Callable[[str], str] = ..., + formatvalue: Callable[[Any], str] = ..., + formatreturns: Callable[[Any], str] = ..., + formatannotation: Callable[[Any], str] = ..., + ) -> str: ... + def formatargvalues( args: list[str], varargs: str | None, @@ -306,7 +317,7 @@ def formatargvalues( formatvarkw: Callable[[str], str] | None = ..., formatvalue: Callable[[Any], str] | None = ..., ) -> str: ... -def getmro(cls: type) -> Tuple[type, ...]: ... +def getmro(cls: type) -> tuple[type, ...]: ... def getcallargs(__func: Callable[..., Any], *args: Any, **kwds: Any) -> dict[str, Any]: ... class ClosureVars(NamedTuple): @@ -327,7 +338,7 @@ class Traceback(NamedTuple): lineno: int function: str code_context: list[str] | None - index: int | None # type: ignore + index: int | None # type: ignore[assignment] class FrameInfo(NamedTuple): frame: FrameType @@ -335,7 +346,7 @@ class FrameInfo(NamedTuple): lineno: int function: str code_context: list[str] | None - index: int | None # type: ignore + index: int | None # type: ignore[assignment] def getframeinfo(frame: FrameType | TracebackType, context: int = ...) -> Traceback: ... def getouterframes(frame: Any, context: int = ...) -> list[FrameInfo]: ... @@ -355,26 +366,25 @@ def getattr_static(obj: object, attr: str, default: Any | None = ...) -> Any: .. # Current State of Generators and Coroutines # -# TODO In the next two blocks of code, can we be more specific regarding the -# type of the "enums"? +GEN_CREATED: Literal["GEN_CREATED"] +GEN_RUNNING: Literal["GEN_RUNNING"] +GEN_SUSPENDED: Literal["GEN_SUSPENDED"] +GEN_CLOSED: Literal["GEN_CLOSED"] -GEN_CREATED: str -GEN_RUNNING: str -GEN_SUSPENDED: str -GEN_CLOSED: str +def getgeneratorstate( + generator: Generator[Any, Any, Any] +) -> Literal["GEN_CREATED", "GEN_RUNNING", "GEN_SUSPENDED", "GEN_CLOSED"]: ... -def getgeneratorstate(generator: Generator[Any, Any, Any]) -> str: ... +CORO_CREATED: Literal["CORO_CREATED"] +CORO_RUNNING: Literal["CORO_RUNNING"] +CORO_SUSPENDED: Literal["CORO_SUSPENDED"] +CORO_CLOSED: Literal["CORO_CLOSED"] -CORO_CREATED: str -CORO_RUNNING: str -CORO_SUSPENDED: str -CORO_CLOSED: str -# TODO can we be more specific than "object"? -def getcoroutinestate(coroutine: object) -> str: ... +def getcoroutinestate( + coroutine: Coroutine[Any, Any, Any] +) -> Literal["CORO_CREATED", "CORO_RUNNING", "CORO_SUSPENDED", "CORO_CLOSED"]: ... def getgeneratorlocals(generator: Generator[Any, Any, Any]) -> dict[str, Any]: ... - -# TODO can we be more specific than "object"? -def getcoroutinelocals(coroutine: object) -> dict[str, Any]: ... +def getcoroutinelocals(coroutine: Coroutine[Any, Any, Any]) -> dict[str, Any]: ... # Create private type alias to avoid conflict with symbol of same # name created in Attribute class. diff --git a/mypy/typeshed/stdlib/io.pyi b/mypy/typeshed/stdlib/io.pyi index 6342907004d5..7b9951dbe631 100644 --- a/mypy/typeshed/stdlib/io.pyi +++ b/mypy/typeshed/stdlib/io.pyi @@ -4,13 +4,14 @@ import sys from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer from os import _Opener from types import TracebackType -from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, TextIO, Tuple, Type +from typing import IO, Any, BinaryIO, Callable, Iterable, Iterator, TextIO +from typing_extensions import Literal -DEFAULT_BUFFER_SIZE: int +DEFAULT_BUFFER_SIZE: Literal[8192] -SEEK_SET: int -SEEK_CUR: int -SEEK_END: int +SEEK_SET: Literal[0] +SEEK_CUR: Literal[1] +SEEK_END: Literal[2] open = builtins.open @@ -26,7 +27,7 @@ class IOBase: def __next__(self) -> bytes: ... 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 ) -> bool | None: ... def close(self) -> None: ... def fileno(self) -> int: ... @@ -63,9 +64,9 @@ class BufferedIOBase(IOBase): def read(self, __size: int | None = ...) -> bytes: ... def read1(self, __size: int = ...) -> bytes: ... -class FileIO(RawIOBase, BinaryIO): +class FileIO(RawIOBase, BinaryIO): # type: ignore # argument disparities between the base classes mode: str - name: StrOrBytesPath | int # type: ignore + name: StrOrBytesPath | int # type: ignore[assignment] def __init__( self, file: StrOrBytesPath | int, mode: str = ..., closefd: bool = ..., opener: _Opener | None = ... ) -> None: ... @@ -75,7 +76,7 @@ class FileIO(RawIOBase, BinaryIO): def read(self, __size: int = ...) -> bytes: ... def __enter__(self: Self) -> Self: ... -class BytesIO(BufferedIOBase, BinaryIO): +class BytesIO(BufferedIOBase, BinaryIO): # type: ignore # argument disparities between the base classes def __init__(self, initial_bytes: bytes = ...) -> None: ... # BytesIO does not contain a "name" field. This workaround is necessary # to allow BytesIO sub-classes to add this field, as it is defined @@ -87,18 +88,18 @@ class BytesIO(BufferedIOBase, BinaryIO): if sys.version_info >= (3, 7): def read1(self, __size: int | None = ...) -> bytes: ... else: - def read1(self, __size: int | None) -> bytes: ... # type: ignore + def read1(self, __size: int | None) -> bytes: ... # type: ignore[override] -class BufferedReader(BufferedIOBase, BinaryIO): +class BufferedReader(BufferedIOBase, BinaryIO): # type: ignore # argument disparities between base classes def __enter__(self: Self) -> Self: ... def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... def peek(self, __size: int = ...) -> bytes: ... if sys.version_info >= (3, 7): def read1(self, __size: int = ...) -> bytes: ... else: - def read1(self, __size: int) -> bytes: ... # type: ignore + def read1(self, __size: int) -> bytes: ... # type: ignore[override] -class BufferedWriter(BufferedIOBase, BinaryIO): +class BufferedWriter(BufferedIOBase, BinaryIO): # type: ignore # argument disparities between base classes def __enter__(self: Self) -> Self: ... def __init__(self, raw: RawIOBase, buffer_size: int = ...) -> None: ... def write(self, __buffer: ReadableBuffer) -> int: ... @@ -110,7 +111,7 @@ class BufferedRandom(BufferedReader, BufferedWriter): if sys.version_info >= (3, 7): def read1(self, __size: int = ...) -> bytes: ... else: - def read1(self, __size: int) -> bytes: ... # type: ignore + def read1(self, __size: int) -> bytes: ... # type: ignore[override] class BufferedRWPair(BufferedIOBase): def __init__(self, reader: RawIOBase, writer: RawIOBase, buffer_size: int = ...) -> None: ... @@ -119,18 +120,18 @@ class BufferedRWPair(BufferedIOBase): class TextIOBase(IOBase): encoding: str errors: str | None - newlines: str | Tuple[str, ...] | None - def __iter__(self) -> Iterator[str]: ... # type: ignore - def __next__(self) -> str: ... # type: ignore + newlines: str | tuple[str, ...] | None + def __iter__(self) -> Iterator[str]: ... # type: ignore[override] + def __next__(self) -> str: ... # type: ignore[override] def detach(self) -> BinaryIO: ... def write(self, __s: str) -> int: ... - def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore - def readline(self, __size: int = ...) -> str: ... # type: ignore - def readlines(self, __hint: int = ...) -> list[str]: ... # type: ignore + def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore[override] + def readline(self, __size: int = ...) -> str: ... # type: ignore[override] + def readlines(self, __hint: int = ...) -> list[str]: ... # type: ignore[override] def read(self, __size: int | None = ...) -> str: ... def tell(self) -> int: ... -class TextIOWrapper(TextIOBase, TextIO): +class TextIOWrapper(TextIOBase, TextIO): # type: ignore # argument disparities between base classes def __init__( self, buffer: IO[bytes], @@ -160,11 +161,11 @@ class TextIOWrapper(TextIOBase, TextIO): ) -> None: ... # These are inherited from TextIOBase, but must exist in the stub to satisfy mypy. def __enter__(self: Self) -> Self: ... - def __iter__(self) -> Iterator[str]: ... # type: ignore - def __next__(self) -> str: ... # type: ignore - def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore - def readline(self, __size: int = ...) -> str: ... # type: ignore - def readlines(self, __hint: int = ...) -> list[str]: ... # type: ignore + def __iter__(self) -> Iterator[str]: ... # type: ignore[override] + def __next__(self) -> str: ... # type: ignore[override] + def writelines(self, __lines: Iterable[str]) -> None: ... # type: ignore[override] + def readline(self, __size: int = ...) -> str: ... # type: ignore[override] + def readlines(self, __hint: int = ...) -> list[str]: ... # type: ignore[override] def seek(self, __cookie: int, __whence: int = ...) -> int: ... class StringIO(TextIOWrapper): @@ -179,4 +180,4 @@ class IncrementalNewlineDecoder(codecs.IncrementalDecoder): def __init__(self, decoder: codecs.IncrementalDecoder | None, translate: bool, errors: str = ...) -> None: ... def decode(self, input: bytes | str, final: bool = ...) -> str: ... @property - def newlines(self) -> str | Tuple[str, ...] | None: ... + def newlines(self) -> str | tuple[str, ...] | None: ... diff --git a/mypy/typeshed/stdlib/ipaddress.pyi b/mypy/typeshed/stdlib/ipaddress.pyi index 0ded1ef19b47..0b29f2633d05 100644 --- a/mypy/typeshed/stdlib/ipaddress.pyi +++ b/mypy/typeshed/stdlib/ipaddress.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Self from typing import Any, Container, Generic, Iterable, Iterator, SupportsInt, TypeVar, overload # Undocumented length constants @@ -7,18 +8,17 @@ IPV6LENGTH: int _A = TypeVar("_A", IPv4Address, IPv6Address) _N = TypeVar("_N", IPv4Network, IPv6Network) -_T = TypeVar("_T") -def ip_address(address: object) -> Any: ... # morally IPv4Address | IPv6Address -def ip_network(address: object, strict: bool = ...) -> Any: ... # morally IPv4Network | IPv6Network -def ip_interface(address: object) -> Any: ... # morally IPv4Interface | IPv6Interface +def ip_address(address: object) -> IPv4Address | IPv6Address: ... +def ip_network(address: object, strict: bool = ...) -> IPv4Network | IPv6Network: ... +def ip_interface(address: object) -> IPv4Interface | IPv6Interface: ... class _IPAddressBase: def __eq__(self, other: Any) -> bool: ... - def __ge__(self: _T, other: _T) -> bool: ... - def __gt__(self: _T, other: _T) -> bool: ... - def __le__(self: _T, other: _T) -> bool: ... - def __lt__(self: _T, other: _T) -> bool: ... + def __ge__(self: Self, other: Self) -> bool: ... + def __gt__(self: Self, other: Self) -> bool: ... + def __le__(self: Self, other: Self) -> bool: ... + def __lt__(self: Self, other: Self) -> bool: ... def __ne__(self, other: Any) -> bool: ... @property def compressed(self) -> str: ... @@ -31,10 +31,10 @@ class _IPAddressBase: class _BaseAddress(_IPAddressBase, SupportsInt): def __init__(self, address: object) -> None: ... - def __add__(self: _T, other: int) -> _T: ... + def __add__(self: Self, other: int) -> Self: ... def __hash__(self) -> int: ... def __int__(self) -> int: ... - def __sub__(self: _T, other: int) -> _T: ... + def __sub__(self: Self, other: int) -> Self: ... @property def is_global(self) -> bool: ... @property @@ -61,10 +61,10 @@ class _BaseNetwork(_IPAddressBase, Container[_A], Iterable[_A], Generic[_A]): def __contains__(self, other: Any) -> bool: ... def __getitem__(self, n: int) -> _A: ... def __iter__(self) -> Iterator[_A]: ... - def address_exclude(self: _T, other: _T) -> Iterator[_T]: ... + def address_exclude(self: Self, other: Self) -> Iterator[Self]: ... @property def broadcast_address(self) -> _A: ... - def compare_networks(self: _T, other: _T) -> int: ... + def compare_networks(self: Self, other: Self) -> int: ... def hosts(self) -> Iterator[_A]: ... @property def is_global(self) -> bool: ... @@ -88,10 +88,10 @@ class _BaseNetwork(_IPAddressBase, Container[_A], Iterable[_A], Generic[_A]): @property def prefixlen(self) -> int: ... if sys.version_info >= (3, 7): - def subnet_of(self: _T, other: _T) -> bool: ... - def supernet_of(self: _T, other: _T) -> bool: ... - def subnets(self: _T, prefixlen_diff: int = ..., new_prefix: int | None = ...) -> Iterator[_T]: ... - def supernet(self: _T, prefixlen_diff: int = ..., new_prefix: int | None = ...) -> _T: ... + def subnet_of(self: Self, other: Self) -> bool: ... + def supernet_of(self: Self, other: Self) -> bool: ... + def subnets(self: Self, prefixlen_diff: int = ..., new_prefix: int | None = ...) -> Iterator[Self]: ... + def supernet(self: Self, prefixlen_diff: int = ..., new_prefix: int | None = ...) -> Self: ... @property def with_hostmask(self) -> str: ... @property @@ -127,6 +127,9 @@ class IPv6Address(_BaseAddress): def sixtofour(self) -> IPv4Address | None: ... @property def teredo(self) -> tuple[IPv4Address, IPv4Address] | None: ... + if sys.version_info >= (3, 9): + @property + def scope_id(self) -> str | None: ... class IPv6Network(_BaseNetwork[IPv6Address]): @property @@ -136,10 +139,16 @@ class IPv6Interface(IPv6Address, _BaseInterface[IPv6Address, IPv6Network]): ... def v4_int_to_packed(address: int) -> bytes: ... def v6_int_to_packed(address: int) -> bytes: ... + +# Third overload is technically incorrect, but convenient when first and last are return values of ip_address() @overload def summarize_address_range(first: IPv4Address, last: IPv4Address) -> Iterator[IPv4Network]: ... @overload def summarize_address_range(first: IPv6Address, last: IPv6Address) -> Iterator[IPv6Network]: ... +@overload +def summarize_address_range( + first: IPv4Address | IPv6Address, last: IPv4Address | IPv6Address +) -> Iterator[IPv4Network] | Iterator[IPv6Network]: ... def collapse_addresses(addresses: Iterable[_N]) -> Iterator[_N]: ... @overload def get_mixed_type_key(obj: _A) -> tuple[int, _A]: ... diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index 9d666d681781..30b5897704de 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -9,14 +9,15 @@ from typing import ( SupportsComplex, SupportsFloat, SupportsInt, - Tuple, - Type, TypeVar, Union, overload, ) from typing_extensions import Literal, SupportsIndex +if sys.version_info >= (3, 9): + from types import GenericAlias + _T = TypeVar("_T") _S = TypeVar("_S") _N = TypeVar("_N", int, float, SupportsFloat, SupportsInt, SupportsIndex, SupportsComplex) @@ -66,7 +67,9 @@ class chain(Iterator[_T], Generic[_T]): def __iter__(self) -> Iterator[_T]: ... @classmethod # We use Type and not Type[_S] to not lose the type inference from __iterable - def from_iterable(cls: Type[Any], __iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... + def from_iterable(cls: type[Any], __iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, __item: Any) -> GenericAlias: ... class compress(Iterator[_T], Generic[_T]): def __init__(self, data: Iterable[_T], selectors: Iterable[Any]) -> None: ... @@ -86,7 +89,7 @@ class filterfalse(Iterator[_T], Generic[_T]): _T1 = TypeVar("_T1") _T2 = TypeVar("_T2") -class groupby(Iterator[Tuple[_T, Iterator[_S]]], Generic[_T, _S]): +class groupby(Iterator[tuple[_T, Iterator[_S]]], Generic[_T, _S]): @overload def __new__(cls, iterable: Iterable[_T1], key: None = ...) -> groupby[_T1, _T1]: ... @overload @@ -112,7 +115,7 @@ class takewhile(Iterator[_T], Generic[_T]): def __iter__(self) -> Iterator[_T]: ... def __next__(self) -> _T: ... -def tee(__iterable: Iterable[_T], __n: int = ...) -> Tuple[Iterator[_T], ...]: ... +def tee(__iterable: Iterable[_T], __n: int = ...) -> tuple[Iterator[_T], ...]: ... class zip_longest(Iterator[Any]): def __init__(self, *p: Iterable[Any], fillvalue: Any = ...) -> None: ... @@ -165,18 +168,18 @@ class product(Iterator[_T_co], Generic[_T_co]): __iter6: Iterable[Any], __iter7: Iterable[Any], *iterables: Iterable[Any], - ) -> product[Tuple[Any, ...]]: ... + ) -> product[tuple[Any, ...]]: ... @overload - def __new__(cls, *iterables: Iterable[_T1], repeat: int) -> product[Tuple[_T1, ...]]: ... + def __new__(cls, *iterables: Iterable[_T1], repeat: int) -> product[tuple[_T1, ...]]: ... @overload - def __new__(cls, *iterables: Iterable[Any], repeat: int = ...) -> product[Tuple[Any, ...]]: ... + def __new__(cls, *iterables: Iterable[Any], repeat: int = ...) -> product[tuple[Any, ...]]: ... def __iter__(self) -> Iterator[_T_co]: ... def __next__(self) -> _T_co: ... -class permutations(Iterator[Tuple[_T, ...]], Generic[_T]): +class permutations(Iterator[tuple[_T, ...]], Generic[_T]): def __init__(self, iterable: Iterable[_T], r: int | None = ...) -> None: ... - def __iter__(self) -> Iterator[Tuple[_T, ...]]: ... - def __next__(self) -> Tuple[_T, ...]: ... + def __iter__(self) -> Iterator[tuple[_T, ...]]: ... + def __next__(self) -> tuple[_T, ...]: ... class combinations(Iterator[_T_co], Generic[_T_co]): @overload @@ -188,14 +191,14 @@ class combinations(Iterator[_T_co], Generic[_T_co]): @overload def __new__(cls, iterable: Iterable[_T], r: Literal[5]) -> combinations[tuple[_T, _T, _T, _T, _T]]: ... @overload - def __new__(cls, iterable: Iterable[_T], r: int) -> combinations[Tuple[_T, ...]]: ... + def __new__(cls, iterable: Iterable[_T], r: int) -> combinations[tuple[_T, ...]]: ... def __iter__(self) -> Iterator[_T_co]: ... def __next__(self) -> _T_co: ... -class combinations_with_replacement(Iterator[Tuple[_T, ...]], Generic[_T]): +class combinations_with_replacement(Iterator[tuple[_T, ...]], Generic[_T]): def __init__(self, iterable: Iterable[_T], r: int) -> None: ... - def __iter__(self) -> Iterator[Tuple[_T, ...]]: ... - def __next__(self) -> Tuple[_T, ...]: ... + def __iter__(self) -> Iterator[tuple[_T, ...]]: ... + def __next__(self) -> tuple[_T, ...]: ... if sys.version_info >= (3, 10): class pairwise(Iterator[_T_co], Generic[_T_co]): diff --git a/mypy/typeshed/stdlib/json/__init__.pyi b/mypy/typeshed/stdlib/json/__init__.pyi index 3e26d1b14f82..b9867b55f950 100644 --- a/mypy/typeshed/stdlib/json/__init__.pyi +++ b/mypy/typeshed/stdlib/json/__init__.pyi @@ -1,5 +1,5 @@ from _typeshed import SupportsRead -from typing import IO, Any, Callable, Type +from typing import IO, Any, Callable from .decoder import JSONDecodeError as JSONDecodeError, JSONDecoder as JSONDecoder from .encoder import JSONEncoder as JSONEncoder @@ -11,7 +11,7 @@ def dumps( ensure_ascii: bool = ..., check_circular: bool = ..., allow_nan: bool = ..., - cls: Type[JSONEncoder] | None = ..., + cls: type[JSONEncoder] | None = ..., indent: None | int | str = ..., separators: tuple[str, str] | None = ..., default: Callable[[Any], Any] | None = ..., @@ -26,7 +26,7 @@ def dump( ensure_ascii: bool = ..., check_circular: bool = ..., allow_nan: bool = ..., - cls: Type[JSONEncoder] | None = ..., + cls: type[JSONEncoder] | None = ..., indent: None | int | str = ..., separators: tuple[str, str] | None = ..., default: Callable[[Any], Any] | None = ..., @@ -36,7 +36,7 @@ def dump( def loads( s: str | bytes, *, - cls: Type[JSONDecoder] | None = ..., + cls: type[JSONDecoder] | None = ..., object_hook: Callable[[dict[Any, Any]], Any] | None = ..., parse_float: Callable[[str], Any] | None = ..., parse_int: Callable[[str], Any] | None = ..., @@ -47,7 +47,7 @@ def loads( def load( fp: SupportsRead[str | bytes], *, - cls: Type[JSONDecoder] | None = ..., + cls: type[JSONDecoder] | None = ..., object_hook: Callable[[dict[Any, Any]], Any] | None = ..., parse_float: Callable[[str], Any] | None = ..., parse_int: Callable[[str], Any] | None = ..., diff --git a/mypy/typeshed/stdlib/json/encoder.pyi b/mypy/typeshed/stdlib/json/encoder.pyi index 9557a96eee78..6dd74896e5a0 100644 --- a/mypy/typeshed/stdlib/json/encoder.pyi +++ b/mypy/typeshed/stdlib/json/encoder.pyi @@ -1,4 +1,10 @@ -from typing import Any, Callable, Iterator +from typing import Any, Callable, Iterator, Pattern + +ESCAPE: Pattern[str] +ESCAPE_ASCII: Pattern[str] +HAS_UTF8: Pattern[bytes] +ESCAPE_DCT: dict[str, str] +INFINITY: float def py_encode_basestring(s: str) -> str: ... # undocumented def py_encode_basestring_ascii(s: str) -> str: ... # undocumented diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi index 48cb4eae916c..3c3b90c52f7c 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi @@ -1,10 +1,9 @@ -from _typeshed import StrPath -from typing import Dict, List, Optional, Tuple, TypeVar +from _typeshed import Self, StrPath +from typing import Optional -_P = TypeVar("_P") -_Label = Tuple[int, Optional[str]] -_DFA = List[List[Tuple[int, int]]] -_DFAS = Tuple[_DFA, Dict[int, int]] +_Label = tuple[int, Optional[str]] +_DFA = list[list[tuple[int, int]]] +_DFAS = tuple[_DFA, dict[int, int]] class Grammar: symbol2number: dict[str, int] @@ -19,7 +18,7 @@ class Grammar: def __init__(self) -> None: ... def dump(self, filename: StrPath) -> None: ... def load(self, filename: StrPath) -> None: ... - def copy(self: _P) -> _P: ... + def copy(self: Self) -> Self: ... def report(self) -> None: ... opmap_raw: str diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi index c4ab376eca64..2f944c40a02c 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi @@ -1,3 +1,5 @@ +import sys + ENDMARKER: int NAME: int NUMBER: int @@ -57,6 +59,8 @@ ATEQUAL: int AWAIT: int ASYNC: int ERRORTOKEN: int +if sys.version_info >= (3, 7): + COLONEQUAL: int N_TOKENS: int NT_OFFSET: int tok_name: dict[int, str] diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi index e96a0d8c8eb3..3679caee9314 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi @@ -1,9 +1,9 @@ from lib2to3.pgen2.token import * # noqa -from typing import Callable, Iterable, Iterator, Tuple +from typing import Callable, Iterable, Iterator -_Coord = Tuple[int, int] +_Coord = tuple[int, int] _TokenEater = Callable[[int, str, _Coord, _Coord, str], None] -_TokenInfo = Tuple[int, str, _Coord, _Coord, str] +_TokenInfo = tuple[int, str, _Coord, _Coord, str] class TokenError(Exception): ... class StopTokenizing(Exception): ... diff --git a/mypy/typeshed/stdlib/lib2to3/pytree.pyi b/mypy/typeshed/stdlib/lib2to3/pytree.pyi index eab82cbc200d..aefd3014617e 100644 --- a/mypy/typeshed/stdlib/lib2to3/pytree.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pytree.pyi @@ -1,11 +1,11 @@ +from _typeshed import Self from lib2to3.pgen2.grammar import Grammar -from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, TypeVar, Union +from typing import Any, Callable, Iterator, Optional, Union -_P = TypeVar("_P") _NL = Union[Node, Leaf] -_Context = Tuple[str, int, int] -_Results = Dict[str, _NL] -_RawNode = Tuple[int, str, _Context, Optional[List[_NL]]] +_Context = tuple[str, int, int] +_Results = dict[str, _NL] +_RawNode = tuple[int, str, _Context, Optional[list[_NL]]] _Convert = Callable[[Grammar, _RawNode], Any] HUGE: int @@ -20,8 +20,8 @@ class Base: was_changed: bool was_checked: bool def __eq__(self, other: Any) -> bool: ... - def _eq(self: _P, other: _P) -> bool: ... - def clone(self: _P) -> _P: ... + def _eq(self: Self, other: Self) -> bool: ... + def clone(self: Self) -> Self: ... def post_order(self) -> Iterator[_NL]: ... def pre_order(self) -> Iterator[_NL]: ... def replace(self, new: _NL | list[_NL]) -> None: ... diff --git a/mypy/typeshed/stdlib/linecache.pyi b/mypy/typeshed/stdlib/linecache.pyi index a66614bf6b37..e53d3efea5b2 100644 --- a/mypy/typeshed/stdlib/linecache.pyi +++ b/mypy/typeshed/stdlib/linecache.pyi @@ -1,7 +1,7 @@ -from typing import Any, Dict, List, Protocol, Tuple +from typing import Any, Protocol -_ModuleGlobals = Dict[str, Any] -_ModuleMetadata = Tuple[int, float, List[str], str] +_ModuleGlobals = dict[str, Any] +_ModuleMetadata = tuple[int, float, list[str], str] class _SourceLoader(Protocol): def __call__(self) -> str | None: ... diff --git a/mypy/typeshed/stdlib/locale.pyi b/mypy/typeshed/stdlib/locale.pyi index 1f80c8a62483..f3942102716a 100644 --- a/mypy/typeshed/stdlib/locale.pyi +++ b/mypy/typeshed/stdlib/locale.pyi @@ -4,7 +4,7 @@ import sys # as a type annotation or type alias. from builtins import str as _str from decimal import Decimal -from typing import Any, Callable, Iterable, Mapping, Sequence, Tuple +from typing import Any, Callable, Iterable, Mapping, Sequence CODESET: int D_T_FMT: int @@ -82,13 +82,13 @@ class Error(Exception): ... def setlocale(category: int, locale: _str | Iterable[_str] | None = ...) -> _str: ... def localeconv() -> Mapping[_str, int | _str | list[int]]: ... def nl_langinfo(__key: int) -> _str: ... -def getdefaultlocale(envvars: Tuple[_str, ...] = ...) -> tuple[_str | None, _str | None]: ... +def getdefaultlocale(envvars: tuple[_str, ...] = ...) -> tuple[_str | None, _str | None]: ... def getlocale(category: int = ...) -> Sequence[_str]: ... def getpreferredencoding(do_setlocale: bool = ...) -> _str: ... def normalize(localename: _str) -> _str: ... def resetlocale(category: int = ...) -> None: ... -def strcoll(string1: _str, string2: _str) -> int: ... -def strxfrm(string: _str) -> _str: ... +def strcoll(__os1: _str, __os2: _str) -> int: ... +def strxfrm(__string: _str) -> _str: ... def format(percent: _str, value: float | Decimal, grouping: bool = ..., monetary: bool = ..., *additional: Any) -> _str: ... if sys.version_info >= (3, 7): diff --git a/mypy/typeshed/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index c972559c9b60..08a785eb4638 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -1,17 +1,17 @@ import sys import threading -from _typeshed import StrPath, SupportsWrite +from _typeshed import Self, StrPath, SupportsWrite from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence from io import TextIOWrapper from string import Template from time import struct_time from types import FrameType, TracebackType -from typing import Any, ClassVar, Generic, Optional, Pattern, TextIO, Tuple, Type, TypeVar, Union, overload +from typing import Any, ClassVar, Generic, Optional, Pattern, TextIO, TypeVar, Union, overload from typing_extensions import Literal -_SysExcInfoType = Union[Tuple[Type[BaseException], BaseException, Optional[TracebackType]], Tuple[None, None, None]] +_SysExcInfoType = Union[tuple[type[BaseException], BaseException, Optional[TracebackType]], tuple[None, None, None]] _ExcInfoType = Union[None, bool, _SysExcInfoType, BaseException] -_ArgsType = Union[Tuple[object, ...], Mapping[str, object]] +_ArgsType = Union[tuple[object, ...], Mapping[str, object]] _FilterType = Union[Filter, Callable[[LogRecord], int]] _Level = Union[int, str] _FormatStyle = Literal["%", "{", "$"] @@ -27,23 +27,23 @@ def currentframe() -> FrameType: ... _levelToName: dict[int, str] _nameToLevel: dict[str, int] -class Filterer(object): +class Filterer: filters: list[Filter] def __init__(self) -> None: ... def addFilter(self, filter: _FilterType) -> None: ... def removeFilter(self, filter: _FilterType) -> None: ... def filter(self, record: LogRecord) -> bool: ... -class Manager(object): # undocumented +class Manager: # undocumented root: RootLogger disable: int emittedNoHandlerWarning: bool loggerDict: dict[str, Logger | PlaceHolder] - loggerClass: Type[Logger] | None + loggerClass: type[Logger] | None logRecordFactory: Callable[..., LogRecord] | None def __init__(self, rootnode: RootLogger) -> None: ... def getLogger(self, name: str) -> Logger: ... - def setLoggerClass(self, klass: Type[Logger]) -> None: ... + def setLoggerClass(self, klass: type[Logger]) -> None: ... def setLogRecordFactory(self, factory: Callable[..., LogRecord]) -> None: ... class Logger(Filterer): @@ -59,7 +59,7 @@ class Logger(Filterer): def setLevel(self, level: _Level) -> None: ... def isEnabledFor(self, level: int) -> bool: ... def getEffectiveLevel(self) -> int: ... - def getChild(self, suffix: str) -> Logger: ... + def getChild(self: Self, suffix: str) -> Self: ... # see python/typing#980 if sys.version_info >= (3, 8): def debug( self, @@ -244,14 +244,14 @@ class Logger(Filterer): def hasHandlers(self) -> bool: ... def callHandlers(self, record: LogRecord) -> None: ... # undocumented -CRITICAL: int -FATAL: int -ERROR: int -WARNING: int -WARN: int -INFO: int -DEBUG: int -NOTSET: int +CRITICAL: Literal[50] +FATAL: Literal[50] +ERROR: Literal[40] +WARNING: Literal[30] +WARN: Literal[30] +INFO: Literal[20] +DEBUG: Literal[10] +NOTSET: Literal[0] class Handler(Filterer): level: int # undocumented @@ -285,7 +285,17 @@ class Formatter: else: default_msec_format: str - if sys.version_info >= (3, 8): + if sys.version_info >= (3, 10): + def __init__( + self, + fmt: str | None = ..., + datefmt: str | None = ..., + style: _FormatStyle = ..., + validate: bool = ..., + *, + defaults: Mapping[str, Any] | None = ..., + ) -> None: ... + elif sys.version_info >= (3, 8): def __init__( self, fmt: str | None = ..., datefmt: str | None = ..., style: _FormatStyle = ..., validate: bool = ... ) -> None: ... @@ -326,6 +336,7 @@ class LogRecord: lineno: int module: str msecs: float + # Only created when logging.Formatter.format is called. See #6132. message: str msg: str name: str @@ -357,7 +368,7 @@ class LoggerAdapter(Generic[_L]): manager: Manager # undocumented if sys.version_info >= (3, 10): extra: Mapping[str, object] | None - def __init__(self, logger: _L, extra: Mapping[str, object] | None) -> None: ... + def __init__(self, logger: _L, extra: Mapping[str, object] | None = ...) -> None: ... else: extra: Mapping[str, object] def __init__(self, logger: _L, extra: Mapping[str, object]) -> None: ... @@ -535,7 +546,7 @@ class LoggerAdapter(Generic[_L]): def name(self) -> str: ... # undocumented def getLogger(name: str | None = ...) -> Logger: ... -def getLoggerClass() -> Type[Logger]: ... +def getLoggerClass() -> type[Logger]: ... def getLogRecordFactory() -> Callable[..., LogRecord]: ... if sys.version_info >= (3, 8): @@ -692,7 +703,7 @@ else: ) -> None: ... def shutdown(handlerList: Sequence[Any] = ...) -> None: ... # handlerList is undocumented -def setLoggerClass(klass: Type[Logger]) -> None: ... +def setLoggerClass(klass: type[Logger]) -> None: ... def captureWarnings(capture: bool) -> None: ... def setLogRecordFactory(factory: Callable[..., LogRecord]) -> None: ... @@ -738,14 +749,17 @@ class RootLogger(Logger): root: RootLogger -class PercentStyle(object): # undocumented +class PercentStyle: # undocumented default_format: str asctime_format: str asctime_search: str if sys.version_info >= (3, 8): validation_pattern: Pattern[str] _fmt: str - def __init__(self, fmt: str) -> None: ... + if sys.version_info >= (3, 10): + def __init__(self, fmt: str, *, defaults: Mapping[str, Any] | None = ...) -> None: ... + else: + def __init__(self, fmt: str) -> None: ... def usesTime(self) -> bool: ... if sys.version_info >= (3, 8): def validate(self) -> None: ... diff --git a/mypy/typeshed/stdlib/logging/handlers.pyi b/mypy/typeshed/stdlib/logging/handlers.pyi index 5be624872a14..50d6d0583556 100644 --- a/mypy/typeshed/stdlib/logging/handlers.pyi +++ b/mypy/typeshed/stdlib/logging/handlers.pyi @@ -128,7 +128,7 @@ class SocketHandler(Handler): def createSocket(self) -> None: ... class DatagramHandler(SocketHandler): - def makeSocket(self) -> socket: ... # type: ignore + def makeSocket(self) -> socket: ... # type: ignore[override] class SysLogHandler(Handler): LOG_EMERG: int diff --git a/mypy/typeshed/stdlib/lzma.pyi b/mypy/typeshed/stdlib/lzma.pyi index e1da3024c4ac..e4bd977d7eab 100644 --- a/mypy/typeshed/stdlib/lzma.pyi +++ b/mypy/typeshed/stdlib/lzma.pyi @@ -41,7 +41,7 @@ PRESET_EXTREME: int # from _lzma.c @final -class LZMADecompressor(object): +class LZMADecompressor: def __init__(self, format: int | None = ..., memlimit: int | None = ..., filters: _FilterChain | None = ...) -> None: ... def decompress(self, data: bytes, max_length: int = ...) -> bytes: ... @property @@ -55,7 +55,7 @@ class LZMADecompressor(object): # from _lzma.c @final -class LZMACompressor(object): +class LZMACompressor: def __init__( self, format: int | None = ..., check: int = ..., preset: int | None = ..., filters: _FilterChain | None = ... ) -> None: ... diff --git a/mypy/typeshed/stdlib/mailbox.pyi b/mypy/typeshed/stdlib/mailbox.pyi index ffd9c3005cec..4ce792300ef4 100644 --- a/mypy/typeshed/stdlib/mailbox.pyi +++ b/mypy/typeshed/stdlib/mailbox.pyi @@ -2,22 +2,7 @@ import email.message import sys from _typeshed import Self, StrOrBytesPath from types import TracebackType -from typing import ( - IO, - Any, - AnyStr, - Callable, - Generic, - Iterable, - Iterator, - Mapping, - Protocol, - Sequence, - Type, - TypeVar, - Union, - overload, -) +from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Iterator, Mapping, Protocol, Sequence, TypeVar, Union, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -184,7 +169,7 @@ class _ProxyFile(Generic[AnyStr]): def seek(self, offset: int, whence: int = ...) -> None: ... def close(self) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, exc_type: Type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... + def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... def readable(self) -> bool: ... def writable(self) -> bool: ... def seekable(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/mailcap.pyi b/mypy/typeshed/stdlib/mailcap.pyi index 9eaa771ed3d3..56218d1370fe 100644 --- a/mypy/typeshed/stdlib/mailcap.pyi +++ b/mypy/typeshed/stdlib/mailcap.pyi @@ -1,6 +1,6 @@ -from typing import Dict, Mapping, Sequence, Union +from typing import Mapping, Sequence, Union -_Cap = Dict[str, Union[str, int]] +_Cap = dict[str, Union[str, int]] def findmatch( caps: Mapping[str, list[_Cap]], MIMEtype: str, key: str = ..., filename: str = ..., plist: Sequence[str] = ... diff --git a/mypy/typeshed/stdlib/math.pyi b/mypy/typeshed/stdlib/math.pyi index f92a3d94f978..d5e6f99dfa68 100644 --- a/mypy/typeshed/stdlib/math.pyi +++ b/mypy/typeshed/stdlib/math.pyi @@ -21,6 +21,10 @@ def asinh(__x: _SupportsFloatOrIndex) -> float: ... def atan(__x: _SupportsFloatOrIndex) -> float: ... def atan2(__y: _SupportsFloatOrIndex, __x: _SupportsFloatOrIndex) -> float: ... def atanh(__x: _SupportsFloatOrIndex) -> float: ... + +if sys.version_info >= (3, 11): + def cbrt(__x: _SupportsFloatOrIndex) -> float: ... + def ceil(__x: _SupportsFloatOrIndex) -> int: ... if sys.version_info >= (3, 8): @@ -99,7 +103,7 @@ def pow(__x: _SupportsFloatOrIndex, __y: _SupportsFloatOrIndex) -> float: ... if sys.version_info >= (3, 8): @overload - def prod(__iterable: Iterable[SupportsIndex], *, start: SupportsIndex = ...) -> int: ... # type: ignore + def prod(__iterable: Iterable[SupportsIndex], *, start: SupportsIndex = ...) -> int: ... # type: ignore[misc] @overload def prod(__iterable: Iterable[_SupportsFloatOrIndex], *, start: _SupportsFloatOrIndex = ...) -> float: ... diff --git a/mypy/typeshed/stdlib/mimetypes.pyi b/mypy/typeshed/stdlib/mimetypes.pyi index 90c87d2cf385..8f51c1580eec 100644 --- a/mypy/typeshed/stdlib/mimetypes.pyi +++ b/mypy/typeshed/stdlib/mimetypes.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import StrPath -from typing import IO, Sequence, Tuple +from typing import IO, Sequence if sys.version_info >= (3, 8): def guess_type(url: StrPath, strict: bool = ...) -> tuple[str | None, str | None]: ... @@ -26,9 +26,12 @@ class MimeTypes: encodings_map: dict[str, str] types_map: tuple[dict[str, str], dict[str, str]] types_map_inv: tuple[dict[str, str], dict[str, str]] - def __init__(self, filenames: Tuple[str, ...] = ..., strict: bool = ...) -> None: ... + def __init__(self, filenames: tuple[str, ...] = ..., strict: bool = ...) -> None: ... def guess_extension(self, type: str, strict: bool = ...) -> str | None: ... - def guess_type(self, url: str, strict: bool = ...) -> tuple[str | None, str | None]: ... + if sys.version_info >= (3, 8): + def guess_type(self, url: StrPath, strict: bool = ...) -> tuple[str | None, str | None]: ... + else: + def guess_type(self, url: str, strict: bool = ...) -> tuple[str | None, str | None]: ... def guess_all_extensions(self, type: str, strict: bool = ...) -> list[str]: ... def read(self, filename: str, strict: bool = ...) -> None: ... def readfp(self, fp: IO[str], strict: bool = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/mmap.pyi b/mypy/typeshed/stdlib/mmap.pyi index 4dd8f8cd2cdd..e59f97320672 100644 --- a/mypy/typeshed/stdlib/mmap.pyi +++ b/mypy/typeshed/stdlib/mmap.pyi @@ -1,6 +1,7 @@ import sys from _typeshed import ReadableBuffer -from typing import ContextManager, Iterable, Iterator, NoReturn, Sized, overload +from contextlib import AbstractContextManager +from typing import Iterable, Iterator, NoReturn, Sized, overload ACCESS_DEFAULT: int ACCESS_READ: int @@ -12,6 +13,8 @@ ALLOCATIONGRANULARITY: int if sys.platform == "linux": MAP_DENYWRITE: int MAP_EXECUTABLE: int + if sys.version_info >= (3, 10): + MAP_POPULATE: int if sys.platform != "win32": MAP_ANON: int @@ -24,7 +27,7 @@ if sys.platform != "win32": PAGESIZE: int -class mmap(ContextManager[mmap], Iterable[int], Sized): +class mmap(AbstractContextManager[mmap], Iterable[int], Sized): if sys.platform == "win32": def __init__(self, fileno: int, length: int, tagname: str | None = ..., access: int = ..., offset: int = ...) -> None: ... else: diff --git a/mypy/typeshed/stdlib/modulefinder.pyi b/mypy/typeshed/stdlib/modulefinder.pyi index e77a108e9525..4a1783efefd1 100644 --- a/mypy/typeshed/stdlib/modulefinder.pyi +++ b/mypy/typeshed/stdlib/modulefinder.pyi @@ -1,6 +1,6 @@ import sys from types import CodeType -from typing import IO, Any, Container, Iterable, Iterator, Sequence, Tuple +from typing import IO, Any, Container, Iterable, Iterator, Sequence LOAD_CONST: int # undocumented IMPORT_NAME: int # undocumented @@ -19,7 +19,6 @@ def ReplacePackage(oldname: str, newname: str) -> None: ... class Module: # undocumented def __init__(self, name: str, file: str | None = ..., path: str | None = ...) -> None: ... - def __repr__(self) -> str: ... class ModuleFinder: @@ -62,7 +61,7 @@ class ModuleFinder: def find_all_submodules(self, m: Module) -> Iterable[str]: ... # undocumented def import_module(self, partname: str, fqname: str, parent: Module) -> Module | None: ... # undocumented def load_module(self, fqname: str, fp: IO[str], pathname: str, file_info: tuple[str, str, str]) -> Module: ... # undocumented - def scan_opcodes(self, co: CodeType) -> Iterator[tuple[str, Tuple[Any, ...]]]: ... # undocumented + def scan_opcodes(self, co: CodeType) -> Iterator[tuple[str, tuple[Any, ...]]]: ... # undocumented def scan_code(self, co: CodeType, m: Module) -> None: ... # undocumented def load_package(self, fqname: str, pathname: str) -> Module: ... # undocumented def add_module(self, fqname: str) -> Module: ... # undocumented diff --git a/mypy/typeshed/stdlib/msilib/__init__.pyi b/mypy/typeshed/stdlib/msilib/__init__.pyi index 4e1a7e6a7c02..ba94e861f938 100644 --- a/mypy/typeshed/stdlib/msilib/__init__.pyi +++ b/mypy/typeshed/stdlib/msilib/__init__.pyi @@ -1,6 +1,6 @@ import sys from types import ModuleType -from typing import Any, Container, Iterable, Sequence, Tuple, Type +from typing import Any, Container, Iterable, Sequence from typing_extensions import Literal if sys.platform == "win32": @@ -34,10 +34,10 @@ if sys.platform == "win32": def change_sequence( seq: Sequence[tuple[str, str | None, int]], action: str, - seqno: int | Type[_Unspecified] = ..., - cond: str | Type[_Unspecified] = ..., + seqno: int | type[_Unspecified] = ..., + cond: str | type[_Unspecified] = ..., ) -> None: ... - def add_data(db: _Database, table: str, values: Iterable[Tuple[Any, ...]]) -> None: ... + def add_data(db: _Database, table: str, values: Iterable[tuple[Any, ...]]) -> None: ... def add_stream(db: _Database, name: str, path: str) -> None: ... def init_database( name: str, schema: ModuleType, ProductName: str, ProductCode: str, ProductVersion: str, Manufacturer: str @@ -95,7 +95,6 @@ if sys.platform == "win32": name: str def __init__(self, fname: str) -> None: ... - def __repr__(self) -> str: ... class Feature: id: str diff --git a/mypy/typeshed/stdlib/msilib/sequence.pyi b/mypy/typeshed/stdlib/msilib/sequence.pyi index 123d232886f7..87dff754009d 100644 --- a/mypy/typeshed/stdlib/msilib/sequence.pyi +++ b/mypy/typeshed/stdlib/msilib/sequence.pyi @@ -1,9 +1,9 @@ import sys -from typing import List, Optional, Tuple +from typing import Optional if sys.platform == "win32": - _SequenceType = List[Tuple[str, Optional[str], int]] + _SequenceType = list[tuple[str, Optional[str], int]] AdminExecuteSequence: _SequenceType AdminUISequence: _SequenceType diff --git a/mypy/typeshed/stdlib/multiprocessing/connection.pyi b/mypy/typeshed/stdlib/multiprocessing/connection.pyi index 56ea5c7c0b0b..40630d66ffad 100644 --- a/mypy/typeshed/stdlib/multiprocessing/connection.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/connection.pyi @@ -2,13 +2,13 @@ import socket import sys import types from _typeshed import Self -from typing import Any, Iterable, Tuple, Type, Union +from typing import Any, Iterable, Union if sys.version_info >= (3, 8): from typing import SupportsIndex # https://docs.python.org/3/library/multiprocessing.html#address-formats -_Address = Union[str, Tuple[str, int]] +_Address = Union[str, tuple[str, int]] class _ConnectionBase: if sys.version_info >= (3, 8): @@ -31,7 +31,7 @@ class _ConnectionBase: def poll(self, timeout: float | None = ...) -> bool: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_value: BaseException | None, exc_tb: types.TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: types.TracebackType | None ) -> None: ... class Connection(_ConnectionBase): ... @@ -51,7 +51,7 @@ class Listener: def last_accepted(self) -> _Address | None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_value: BaseException | None, exc_tb: types.TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: types.TracebackType | None ) -> None: ... def deliver_challenge(connection: Connection, authkey: bytes) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/context.pyi b/mypy/typeshed/stdlib/multiprocessing/context.pyi index e65a387819bc..4f4470c978de 100644 --- a/mypy/typeshed/stdlib/multiprocessing/context.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/context.pyi @@ -8,7 +8,7 @@ from multiprocessing import queues, synchronize from multiprocessing.pool import Pool as _Pool from multiprocessing.process import BaseProcess from multiprocessing.sharedctypes import SynchronizedArray, SynchronizedBase -from typing import Any, Type, TypeVar, Union, overload +from typing import Any, TypeVar, Union, overload from typing_extensions import Literal _LockLike = Union[synchronize.Lock, synchronize.RLock] @@ -19,12 +19,12 @@ class BufferTooShort(ProcessError): ... class TimeoutError(ProcessError): ... class AuthenticationError(ProcessError): ... -class BaseContext(object): - Process: Type[BaseProcess] - ProcessError: Type[Exception] - BufferTooShort: Type[Exception] - TimeoutError: Type[Exception] - AuthenticationError: Type[Exception] +class BaseContext: + Process: type[BaseProcess] + ProcessError: type[Exception] + BufferTooShort: type[Exception] + TimeoutError: type[Exception] + AuthenticationError: type[Exception] # N.B. The methods below are applied at runtime to generate # multiprocessing.*, so the signatures should be identical (modulo self). @@ -60,26 +60,26 @@ class BaseContext(object): maxtasksperchild: int | None = ..., ) -> _Pool: ... @overload - def RawValue(self, typecode_or_type: Type[_CT], *args: Any) -> _CT: ... + def RawValue(self, typecode_or_type: type[_CT], *args: Any) -> _CT: ... @overload def RawValue(self, typecode_or_type: str, *args: Any) -> Any: ... @overload - def RawArray(self, typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... + def RawArray(self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... @overload def RawArray(self, typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ... @overload - def Value(self, typecode_or_type: Type[_CT], *args: Any, lock: Literal[False]) -> _CT: ... + def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[False]) -> _CT: ... @overload - def Value(self, typecode_or_type: Type[_CT], *args: Any, lock: Literal[True] | _LockLike) -> SynchronizedBase[_CT]: ... + def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[True] | _LockLike) -> SynchronizedBase[_CT]: ... @overload def Value(self, typecode_or_type: str, *args: Any, lock: Literal[True] | _LockLike) -> SynchronizedBase[Any]: ... @overload - def Value(self, typecode_or_type: str | Type[_CData], *args: Any, lock: bool | _LockLike = ...) -> Any: ... + def Value(self, typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = ...) -> Any: ... @overload - def Array(self, typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False]) -> _CT: ... + def Array(self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False]) -> _CT: ... @overload def Array( - self, typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike + self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike ) -> SynchronizedArray[_CT]: ... @overload def Array( @@ -87,7 +87,7 @@ class BaseContext(object): ) -> SynchronizedArray[Any]: ... @overload def Array( - self, typecode_or_type: str | Type[_CData], size_or_initializer: int | Sequence[Any], *, lock: bool | _LockLike = ... + self, typecode_or_type: str | type[_CData], size_or_initializer: int | Sequence[Any], *, lock: bool | _LockLike = ... ) -> Any: ... def freeze_support(self) -> None: ... def get_logger(self) -> Logger: ... @@ -127,7 +127,7 @@ class Process(BaseProcess): def _Popen(process_obj: BaseProcess) -> DefaultContext: ... class DefaultContext(BaseContext): - Process: Type[multiprocessing.Process] + Process: type[multiprocessing.Process] def __init__(self, context: BaseContext) -> None: ... def set_start_method(self, method: str | None, force: bool = ...) -> None: ... def get_start_method(self, allow_none: bool = ...) -> str: ... @@ -150,13 +150,13 @@ if sys.platform != "win32": def _Popen(process_obj: BaseProcess) -> Any: ... class ForkContext(BaseContext): _name: str - Process: Type[ForkProcess] + Process: type[ForkProcess] class SpawnContext(BaseContext): _name: str - Process: Type[SpawnProcess] + Process: type[SpawnProcess] class ForkServerContext(BaseContext): _name: str - Process: Type[ForkServerProcess] + Process: type[ForkServerProcess] else: class SpawnProcess(BaseProcess): @@ -165,7 +165,7 @@ else: def _Popen(process_obj: BaseProcess) -> Any: ... class SpawnContext(BaseContext): _name: str - Process: Type[SpawnProcess] + Process: type[SpawnProcess] def _force_start_method(method: str) -> None: ... def get_spawning_popen() -> Any | None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi b/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi index 4ef3d095911f..26413cb75181 100644 --- a/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi @@ -1,13 +1,13 @@ from _typeshed import Self from queue import Queue from types import TracebackType -from typing import Any, Tuple, Type, Union +from typing import Any, Union families: list[None] -_Address = Union[str, Tuple[str, int]] +_Address = Union[str, tuple[str, int]] -class Connection(object): +class Connection: _in: Any _out: Any recv: Any @@ -16,19 +16,19 @@ class Connection(object): send_bytes: Any 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 __init__(self, _in: Any, _out: Any) -> None: ... def close(self) -> None: ... def poll(self, timeout: float = ...) -> bool: ... -class Listener(object): +class Listener: _backlog_queue: Queue[Any] | None @property def address(self) -> Queue[Any] | 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 __init__(self, address: _Address | None = ..., family: int | None = ..., backlog: int = ...) -> None: ... def accept(self) -> Connection: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi index 22a33f226c0b..42853dfd31d5 100644 --- a/mypy/typeshed/stdlib/multiprocessing/managers.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/managers.pyi @@ -1,9 +1,8 @@ -# NOTE: These are incomplete! - import queue import sys import threading -from typing import Any, AnyStr, Callable, ContextManager, Generic, Iterable, Mapping, Sequence, Tuple, TypeVar +from contextlib import AbstractContextManager +from typing import Any, AnyStr, Callable, Generic, Iterable, Mapping, Sequence, TypeVar from .connection import Connection from .context import BaseContext @@ -28,16 +27,15 @@ class Namespace: _Namespace = Namespace -class Token(object): +class Token: typeid: str | bytes | None address: tuple[str | bytes, int] id: str | bytes | int | None def __init__(self, typeid: bytes | str | None, address: tuple[str | bytes, int], id: str | bytes | int | None) -> None: ... - def __repr__(self) -> str: ... def __getstate__(self) -> tuple[str | bytes | None, tuple[str | bytes, int], str | bytes | int | None]: ... def __setstate__(self, state: tuple[str | bytes | None, tuple[str | bytes, int], str | bytes | int | None]) -> None: ... -class BaseProxy(object): +class BaseProxy: _address_to_local: dict[Any, Any] _mutex: Any def __init__( @@ -51,7 +49,7 @@ class BaseProxy(object): manager_owned: bool = ..., ) -> None: ... def __deepcopy__(self, memo: Any | None) -> Any: ... - def _callmethod(self, methodname: str, args: Tuple[Any, ...] = ..., kwds: dict[Any, Any] = ...) -> None: ... + def _callmethod(self, methodname: str, args: tuple[Any, ...] = ..., kwds: dict[Any, Any] = ...) -> None: ... def _getvalue(self) -> Any: ... def __reduce__(self) -> tuple[Any, tuple[Any, Any, str, dict[Any, Any]]]: ... @@ -71,7 +69,7 @@ class Server: def serve_forever(self) -> None: ... def accept_connection(self, c: Connection, name: str) -> None: ... -class BaseManager(ContextManager[BaseManager]): +class BaseManager(AbstractContextManager[BaseManager]): def __init__( self, address: Any | None = ..., authkey: bytes | None = ..., serializer: str = ..., ctx: BaseContext | None = ... ) -> None: ... @@ -97,7 +95,7 @@ class BaseManager(ContextManager[BaseManager]): _dict = dict _list = list -class SyncManager(BaseManager, ContextManager[SyncManager]): +class SyncManager(BaseManager, AbstractContextManager[SyncManager]): def BoundedSemaphore(self, value: Any = ...) -> threading.BoundedSemaphore: ... def Condition(self, lock: Any = ...) -> threading.Condition: ... def Event(self) -> threading.Event: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi index 75583aae8012..7c2fd8a06a69 100644 --- a/mypy/typeshed/stdlib/multiprocessing/pool.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/pool.pyi @@ -1,11 +1,14 @@ import sys from _typeshed import Self -from typing import Any, Callable, ContextManager, Generic, Iterable, Iterator, List, Mapping, TypeVar +from contextlib import AbstractContextManager +from typing import Any, Callable, Generic, Iterable, Iterator, Mapping, TypeVar +from typing_extensions import Literal if sys.version_info >= (3, 9): from types import GenericAlias -_PT = TypeVar("_PT", bound=Pool) +__all__ = ["Pool", "ThreadPool"] + _S = TypeVar("_S") _T = TypeVar("_T") @@ -31,7 +34,7 @@ class ApplyResult(Generic[_T]): # alias created during issue #17805 AsyncResult = ApplyResult -class MapResult(ApplyResult[List[_T]]): +class MapResult(ApplyResult[list[_T]]): if sys.version_info >= (3, 8): def __init__( self, @@ -56,13 +59,13 @@ class IMapIterator(Iterator[_T]): def __init__(self, pool: Pool) -> None: ... else: def __init__(self, cache: dict[int, IMapIterator[Any]]) -> None: ... - def __iter__(self: _S) -> _S: ... + def __iter__(self: Self) -> Self: ... def next(self, timeout: float | None = ...) -> _T: ... def __next__(self, timeout: float | None = ...) -> _T: ... class IMapUnorderedIterator(IMapIterator[_T]): ... -class Pool(ContextManager[Pool]): +class Pool(AbstractContextManager[Pool]): def __init__( self, processes: int | None = ..., @@ -107,18 +110,18 @@ class Pool(ContextManager[Pool]): def join(self) -> None: ... def __enter__(self: Self) -> Self: ... -class ThreadPool(Pool, ContextManager[ThreadPool]): +class ThreadPool(Pool, AbstractContextManager[ThreadPool]): def __init__( self, processes: int | None = ..., initializer: Callable[..., Any] | None = ..., initargs: Iterable[Any] = ... ) -> None: ... # undocumented if sys.version_info >= (3, 8): - INIT: str - RUN: str - CLOSE: str - TERMINATE: str + INIT: Literal["INIT"] + RUN: Literal["RUN"] + CLOSE: Literal["CLOSE"] + TERMINATE: Literal["TERMINATE"] else: - RUN: int - CLOSE: int - TERMINATE: int + RUN: Literal[0] + CLOSE: Literal[1] + TERMINATE: Literal[2] diff --git a/mypy/typeshed/stdlib/multiprocessing/process.pyi b/mypy/typeshed/stdlib/multiprocessing/process.pyi index 32c22d19f6e5..4746c78b1b4d 100644 --- a/mypy/typeshed/stdlib/multiprocessing/process.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/process.pyi @@ -1,17 +1,17 @@ import sys -from typing import Any, Callable, Mapping, Tuple +from typing import Any, Callable, Mapping class BaseProcess: name: str daemon: bool authkey: bytes - _identity: Tuple[int, ...] # undocumented + _identity: tuple[int, ...] # undocumented def __init__( self, group: None = ..., target: Callable[..., Any] | None = ..., name: str | None = ..., - args: Tuple[Any, ...] = ..., + args: tuple[Any, ...] = ..., kwargs: Mapping[str, Any] = ..., *, daemon: bool | None = ..., diff --git a/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi index 6ffc2542087a..1b51da38bc43 100644 --- a/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, Generic, Iterable, Tuple, TypeVar +from typing import Any, Generic, Iterable, TypeVar if sys.version_info >= (3, 9): from types import GenericAlias @@ -23,7 +23,7 @@ if sys.version_info >= (3, 8): def __init__(self, sequence: Iterable[_SLT] | None = ..., *, name: str | None = ...) -> None: ... def __getitem__(self, position: int) -> _SLT: ... def __setitem__(self, position: int, value: _SLT) -> None: ... - def __reduce__(self: _S) -> tuple[_S, Tuple[_SLT, ...]]: ... + def __reduce__(self: _S) -> tuple[_S, tuple[_SLT, ...]]: ... def __len__(self) -> int: ... @property def format(self) -> str: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi b/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi index bd9d8f089875..bbe3c17398d0 100644 --- a/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi @@ -3,25 +3,25 @@ from collections.abc import Callable, Iterable, Sequence from ctypes import _CData, _SimpleCData, c_char from multiprocessing.context import BaseContext from multiprocessing.synchronize import _LockLike -from typing import Any, Generic, Protocol, Type, TypeVar, overload +from typing import Any, Generic, Protocol, TypeVar, overload from typing_extensions import Literal _T = TypeVar("_T") _CT = TypeVar("_CT", bound=_CData) @overload -def RawValue(typecode_or_type: Type[_CT], *args: Any) -> _CT: ... +def RawValue(typecode_or_type: type[_CT], *args: Any) -> _CT: ... @overload def RawValue(typecode_or_type: str, *args: Any) -> Any: ... @overload -def RawArray(typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... +def RawArray(typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ... @overload def RawArray(typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ... @overload -def Value(typecode_or_type: Type[_CT], *args: Any, lock: Literal[False], ctx: BaseContext | None = ...) -> _CT: ... +def Value(typecode_or_type: type[_CT], *args: Any, lock: Literal[False], ctx: BaseContext | None = ...) -> _CT: ... @overload def Value( - typecode_or_type: Type[_CT], *args: Any, lock: Literal[True] | _LockLike, ctx: BaseContext | None = ... + typecode_or_type: type[_CT], *args: Any, lock: Literal[True] | _LockLike, ctx: BaseContext | None = ... ) -> SynchronizedBase[_CT]: ... @overload def Value( @@ -29,15 +29,15 @@ def Value( ) -> SynchronizedBase[Any]: ... @overload def Value( - typecode_or_type: str | Type[_CData], *args: Any, lock: bool | _LockLike = ..., ctx: BaseContext | None = ... + typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = ..., ctx: BaseContext | None = ... ) -> Any: ... @overload def Array( - typecode_or_type: Type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False], ctx: BaseContext | None = ... + typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False], ctx: BaseContext | None = ... ) -> _CT: ... @overload def Array( - typecode_or_type: Type[_CT], + typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike, @@ -53,7 +53,7 @@ def Array( ) -> SynchronizedArray[Any]: ... @overload def Array( - typecode_or_type: str | Type[_CData], + typecode_or_type: str | type[_CData], size_or_initializer: int | Sequence[Any], *, lock: bool | _LockLike = ..., diff --git a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi index 1741885f13bf..c32c9aafe9a4 100644 --- a/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/synchronize.pyi @@ -1,7 +1,8 @@ import sys import threading +from contextlib import AbstractContextManager from multiprocessing.context import BaseContext -from typing import Any, Callable, ContextManager, Union +from typing import Any, Callable, Union _LockLike = Union[Lock, RLock] @@ -13,7 +14,7 @@ class Barrier(threading.Barrier): class BoundedSemaphore(Semaphore): def __init__(self, value: int = ..., *, ctx: BaseContext) -> None: ... -class Condition(ContextManager[bool]): +class Condition(AbstractContextManager[bool]): def __init__(self, lock: _LockLike | None = ..., *, ctx: BaseContext) -> None: ... if sys.version_info >= (3, 7): def notify(self, n: int = ...) -> None: ... @@ -25,7 +26,7 @@ class Condition(ContextManager[bool]): def acquire(self, block: bool = ..., timeout: float | None = ...) -> bool: ... def release(self) -> None: ... -class Event(ContextManager[bool]): +class Event(AbstractContextManager[bool]): def __init__(self, lock: _LockLike | None = ..., *, ctx: BaseContext) -> None: ... def is_set(self) -> bool: ... def set(self) -> None: ... @@ -42,6 +43,6 @@ class Semaphore(SemLock): def __init__(self, value: int = ..., *, ctx: BaseContext) -> None: ... # Not part of public API -class SemLock(ContextManager[bool]): +class SemLock(AbstractContextManager[bool]): def acquire(self, block: bool = ..., timeout: float | None = ...) -> bool: ... def release(self) -> None: ... diff --git a/mypy/typeshed/stdlib/netrc.pyi b/mypy/typeshed/stdlib/netrc.pyi index b8eac307740a..7c1c2068aff6 100644 --- a/mypy/typeshed/stdlib/netrc.pyi +++ b/mypy/typeshed/stdlib/netrc.pyi @@ -1,5 +1,5 @@ from _typeshed import StrOrBytesPath -from typing import Optional, Tuple +from typing import Optional class NetrcParseError(Exception): filename: str | None @@ -8,7 +8,7 @@ class NetrcParseError(Exception): def __init__(self, msg: str, filename: StrOrBytesPath | None = ..., lineno: int | None = ...) -> None: ... # (login, account, password) tuple -_NetrcTuple = Tuple[str, Optional[str], Optional[str]] +_NetrcTuple = tuple[str, Optional[str], Optional[str]] class netrc: hosts: dict[str, _NetrcTuple] diff --git a/mypy/typeshed/stdlib/nntplib.pyi b/mypy/typeshed/stdlib/nntplib.pyi index 508b5f679bc3..f0a0fb42da5c 100644 --- a/mypy/typeshed/stdlib/nntplib.pyi +++ b/mypy/typeshed/stdlib/nntplib.pyi @@ -3,7 +3,7 @@ import socket import ssl import sys from _typeshed import Self -from typing import IO, Any, Iterable, NamedTuple, Tuple, Union +from typing import IO, Any, Iterable, NamedTuple, Union _File = Union[IO[bytes], bytes, str, None] @@ -72,7 +72,7 @@ class _NNTPBase: def xhdr(self, hdr: str, str: Any, *, file: _File = ...) -> tuple[str, _list[str]]: ... def xover(self, start: int, end: int, *, file: _File = ...) -> tuple[str, _list[tuple[int, dict[str, str]]]]: ... def over( - self, message_spec: None | str | _list[Any] | Tuple[Any, ...], *, file: _File = ... + self, message_spec: None | str | _list[Any] | tuple[Any, ...], *, file: _File = ... ) -> tuple[str, _list[tuple[int, dict[str, str]]]]: ... if sys.version_info < (3, 9): def xgtitle(self, group: str, *, file: _File = ...) -> tuple[str, _list[tuple[str, str]]]: ... diff --git a/mypy/typeshed/stdlib/ntpath.pyi b/mypy/typeshed/stdlib/ntpath.pyi index 45d715704157..f691356cb702 100644 --- a/mypy/typeshed/stdlib/ntpath.pyi +++ b/mypy/typeshed/stdlib/ntpath.pyi @@ -48,11 +48,13 @@ altsep: str if sys.version_info < (3, 7) and sys.platform == "win32": def splitunc(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... # deprecated -# Similar to posixpath, but have slightly different argument names +# First parameter is not actually pos-only, +# but must be defined as pos-only in the stub or cross-platform code doesn't type-check, +# as the parameter name is different in posixpath.join() @overload -def join(path: StrPath, *paths: StrPath) -> str: ... +def join(__path: StrPath, *paths: StrPath) -> str: ... @overload -def join(path: BytesPath, *paths: BytesPath) -> bytes: ... +def join(__path: BytesPath, *paths: BytesPath) -> bytes: ... if sys.platform == "win32": if sys.version_info >= (3, 10): diff --git a/mypy/typeshed/stdlib/opcode.pyi b/mypy/typeshed/stdlib/opcode.pyi index 982ddee43a63..402dbb74cf58 100644 --- a/mypy/typeshed/stdlib/opcode.pyi +++ b/mypy/typeshed/stdlib/opcode.pyi @@ -1,7 +1,40 @@ import sys -from typing import Sequence +from typing_extensions import Literal -cmp_op: Sequence[str] +__all__ = [ + "cmp_op", + "hasconst", + "hasname", + "hasjrel", + "hasjabs", + "haslocal", + "hascompare", + "hasfree", + "opname", + "opmap", + "HAVE_ARGUMENT", + "EXTENDED_ARG", + "hasnargs", + "stack_effect", +] + +if sys.version_info >= (3, 9): + cmp_op: tuple[Literal["<"], Literal["<="], Literal["=="], Literal["!="], Literal[">"], Literal[">="]] +else: + cmp_op: tuple[ + Literal["<"], + Literal["<="], + Literal["=="], + Literal["!="], + Literal[">"], + Literal[">="], + Literal["in"], + Literal["not in"], + Literal["is"], + Literal["is not"], + Literal["exception match"], + Literal["BAD"], + ] hasconst: list[int] hasname: list[int] hasjrel: list[int] @@ -12,8 +45,8 @@ hasfree: list[int] opname: list[str] opmap: dict[str, int] -HAVE_ARGUMENT: int -EXTENDED_ARG: int +HAVE_ARGUMENT: Literal[90] +EXTENDED_ARG: Literal[144] if sys.version_info >= (3, 8): def stack_effect(__opcode: int, __oparg: int | None = ..., *, jump: bool | None = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/operator.pyi b/mypy/typeshed/stdlib/operator.pyi index bb8e23733f87..180bd161c045 100644 --- a/mypy/typeshed/stdlib/operator.pyi +++ b/mypy/typeshed/stdlib/operator.pyi @@ -1,179 +1,51 @@ -from typing import ( - Any, - Container, - Generic, - Mapping, - MutableMapping, - MutableSequence, - Sequence, - SupportsAbs, - Tuple, - TypeVar, - overload, -) -from typing_extensions import final +import sys -_T = TypeVar("_T") -_T_co = TypeVar("_T_co", covariant=True) -_K = TypeVar("_K") -_V = TypeVar("_V") +from _operator import * -def lt(__a: Any, __b: Any) -> Any: ... -def le(__a: Any, __b: Any) -> Any: ... -def eq(__a: Any, __b: Any) -> Any: ... -def ne(__a: Any, __b: Any) -> Any: ... -def ge(__a: Any, __b: Any) -> Any: ... -def gt(__a: Any, __b: Any) -> Any: ... -def __lt__(a: Any, b: Any) -> Any: ... -def __le__(a: Any, b: Any) -> Any: ... -def __eq__(a: Any, b: Any) -> Any: ... -def __ne__(a: Any, b: Any) -> Any: ... -def __ge__(a: Any, b: Any) -> Any: ... -def __gt__(a: Any, b: Any) -> Any: ... -def not_(__a: Any) -> bool: ... -def __not__(a: Any) -> bool: ... -def truth(__a: Any) -> bool: ... -def is_(__a: Any, __b: Any) -> bool: ... -def is_not(__a: Any, __b: Any) -> bool: ... -def abs(__a: SupportsAbs[_T]) -> _T: ... -def __abs__(a: SupportsAbs[_T]) -> _T: ... -def add(__a: Any, __b: Any) -> Any: ... -def __add__(a: Any, b: Any) -> Any: ... -def and_(__a: Any, __b: Any) -> Any: ... -def __and__(a: Any, b: Any) -> Any: ... -def floordiv(__a: Any, __b: Any) -> Any: ... -def __floordiv__(a: Any, b: Any) -> Any: ... -def index(__a: Any) -> int: ... -def __index__(a: Any) -> int: ... -def inv(__a: Any) -> Any: ... -def invert(__a: Any) -> Any: ... -def __inv__(a: Any) -> Any: ... -def __invert__(a: Any) -> Any: ... -def lshift(__a: Any, __b: Any) -> Any: ... -def __lshift__(a: Any, b: Any) -> Any: ... -def mod(__a: Any, __b: Any) -> Any: ... -def __mod__(a: Any, b: Any) -> Any: ... -def mul(__a: Any, __b: Any) -> Any: ... -def __mul__(a: Any, b: Any) -> Any: ... -def matmul(__a: Any, __b: Any) -> Any: ... -def __matmul__(a: Any, b: Any) -> Any: ... -def neg(__a: Any) -> Any: ... -def __neg__(a: Any) -> Any: ... -def or_(__a: Any, __b: Any) -> Any: ... -def __or__(a: Any, b: Any) -> Any: ... -def pos(__a: Any) -> Any: ... -def __pos__(a: Any) -> Any: ... -def pow(__a: Any, __b: Any) -> Any: ... -def __pow__(a: Any, b: Any) -> Any: ... -def rshift(__a: Any, __b: Any) -> Any: ... -def __rshift__(a: Any, b: Any) -> Any: ... -def sub(__a: Any, __b: Any) -> Any: ... -def __sub__(a: Any, b: Any) -> Any: ... -def truediv(__a: Any, __b: Any) -> Any: ... -def __truediv__(a: Any, b: Any) -> Any: ... -def xor(__a: Any, __b: Any) -> Any: ... -def __xor__(a: Any, b: Any) -> Any: ... -def concat(__a: Sequence[_T], __b: Sequence[_T]) -> Sequence[_T]: ... -def __concat__(a: Sequence[_T], b: Sequence[_T]) -> Sequence[_T]: ... -def contains(__a: Container[Any], __b: Any) -> bool: ... -def __contains__(a: Container[Any], b: Any) -> bool: ... -def countOf(__a: Container[Any], __b: Any) -> int: ... -@overload -def delitem(__a: MutableSequence[Any], __b: int) -> None: ... -@overload -def delitem(__a: MutableSequence[Any], __b: slice) -> None: ... -@overload -def delitem(__a: MutableMapping[_K, Any], __b: _K) -> None: ... -@overload -def __delitem__(a: MutableSequence[Any], b: int) -> None: ... -@overload -def __delitem__(a: MutableSequence[Any], b: slice) -> None: ... -@overload -def __delitem__(a: MutableMapping[_K, Any], b: _K) -> None: ... -@overload -def getitem(__a: Sequence[_T], __b: int) -> _T: ... -@overload -def getitem(__a: Sequence[_T], __b: slice) -> Sequence[_T]: ... -@overload -def getitem(__a: Mapping[_K, _V], __b: _K) -> _V: ... -@overload -def __getitem__(a: Sequence[_T], b: int) -> _T: ... -@overload -def __getitem__(a: Sequence[_T], b: slice) -> Sequence[_T]: ... -@overload -def __getitem__(a: Mapping[_K, _V], b: _K) -> _V: ... -def indexOf(__a: Sequence[_T], __b: _T) -> int: ... -@overload -def setitem(__a: MutableSequence[_T], __b: int, __c: _T) -> None: ... -@overload -def setitem(__a: MutableSequence[_T], __b: slice, __c: Sequence[_T]) -> None: ... -@overload -def setitem(__a: MutableMapping[_K, _V], __b: _K, __c: _V) -> None: ... -@overload -def __setitem__(a: MutableSequence[_T], b: int, c: _T) -> None: ... -@overload -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]: ... - @overload - def __new__(cls, attr: str, __attr2: str) -> attrgetter[tuple[Any, Any]]: ... - @overload - def __new__(cls, attr: str, __attr2: str, __attr3: str) -> attrgetter[tuple[Any, Any, Any]]: ... - @overload - def __new__(cls, attr: str, __attr2: str, __attr3: str, __attr4: str) -> attrgetter[tuple[Any, Any, Any, Any]]: ... - @overload - 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]: ... - @overload - def __new__(cls, item: Any, __item2: Any) -> itemgetter[tuple[Any, Any]]: ... - @overload - def __new__(cls, item: Any, __item2: Any, __item3: Any) -> itemgetter[tuple[Any, Any, Any]]: ... - @overload - def __new__(cls, item: Any, __item2: Any, __item3: Any, __item4: Any) -> itemgetter[tuple[Any, Any, Any, Any]]: ... - @overload - 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: ... - -def iadd(__a: Any, __b: Any) -> Any: ... -def __iadd__(a: Any, b: Any) -> Any: ... -def iand(__a: Any, __b: Any) -> Any: ... -def __iand__(a: Any, b: Any) -> Any: ... -def iconcat(__a: Any, __b: Any) -> Any: ... -def __iconcat__(a: Any, b: Any) -> Any: ... -def ifloordiv(__a: Any, __b: Any) -> Any: ... -def __ifloordiv__(a: Any, b: Any) -> Any: ... -def ilshift(__a: Any, __b: Any) -> Any: ... -def __ilshift__(a: Any, b: Any) -> Any: ... -def imod(__a: Any, __b: Any) -> Any: ... -def __imod__(a: Any, b: Any) -> Any: ... -def imul(__a: Any, __b: Any) -> Any: ... -def __imul__(a: Any, b: Any) -> Any: ... -def imatmul(__a: Any, __b: Any) -> Any: ... -def __imatmul__(a: Any, b: Any) -> Any: ... -def ior(__a: Any, __b: Any) -> Any: ... -def __ior__(a: Any, b: Any) -> Any: ... -def ipow(__a: Any, __b: Any) -> Any: ... -def __ipow__(a: Any, b: Any) -> Any: ... -def irshift(__a: Any, __b: Any) -> Any: ... -def __irshift__(a: Any, b: Any) -> Any: ... -def isub(__a: Any, __b: Any) -> Any: ... -def __isub__(a: Any, b: Any) -> Any: ... -def itruediv(__a: Any, __b: Any) -> Any: ... -def __itruediv__(a: Any, b: Any) -> Any: ... -def ixor(__a: Any, __b: Any) -> Any: ... -def __ixor__(a: Any, b: Any) -> Any: ... +__lt__ = lt +__le__ = le +__eq__ = eq +__ne__ = ne +__ge__ = ge +__gt__ = gt +__not__ = not_ +__abs__ = abs +__add__ = add +__and__ = and_ +__floordiv__ = floordiv +__index__ = index +__inv__ = inv +__invert__ = invert +__lshift__ = lshift +__mod__ = mod +__mul__ = mul +__matmul__ = matmul +__neg__ = neg +__or__ = or_ +__pos__ = pos +__pow__ = pow +__rshift__ = rshift +__sub__ = sub +__truediv__ = truediv +__xor__ = xor +__concat__ = concat +__contains__ = contains +__delitem__ = delitem +__getitem__ = getitem +__setitem__ = setitem +__iadd__ = iadd +__iand__ = iand +__iconcat__ = iconcat +__ifloordiv__ = ifloordiv +__ilshift__ = ilshift +__imod__ = imod +__imul__ = imul +__imatmul__ = imatmul +__ior__ = ior +__ipow__ = ipow +__irshift__ = irshift +__isub__ = isub +__itruediv__ = itruediv +__ixor__ = ixor +if sys.version_info >= (3, 11): + __call__ = call diff --git a/mypy/typeshed/stdlib/optparse.pyi b/mypy/typeshed/stdlib/optparse.pyi index b8ea9d2fff38..c32a17ceb0e9 100644 --- a/mypy/typeshed/stdlib/optparse.pyi +++ b/mypy/typeshed/stdlib/optparse.pyi @@ -1,6 +1,6 @@ -from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, Sequence, Tuple, Type, overload +from typing import IO, Any, AnyStr, Callable, Iterable, Mapping, Sequence, overload -NO_DEFAULT: Tuple[str, ...] +NO_DEFAULT: tuple[str, ...] SUPPRESS_HELP: str SUPPRESS_USAGE: str @@ -72,14 +72,14 @@ class TitledHelpFormatter(HelpFormatter): def format_usage(self, usage: str) -> str: ... class Option: - ACTIONS: Tuple[str, ...] - ALWAYS_TYPED_ACTIONS: Tuple[str, ...] + ACTIONS: tuple[str, ...] + ALWAYS_TYPED_ACTIONS: tuple[str, ...] ATTRS: list[str] CHECK_METHODS: list[Callable[..., Any]] | None - CONST_ACTIONS: Tuple[str, ...] - STORE_ACTIONS: Tuple[str, ...] - TYPED_ACTIONS: Tuple[str, ...] - TYPES: Tuple[str, ...] + CONST_ACTIONS: tuple[str, ...] + STORE_ACTIONS: tuple[str, ...] + TYPED_ACTIONS: tuple[str, ...] + TYPES: tuple[str, ...] TYPE_CHECKER: dict[str, Callable[..., Any]] _long_opts: list[str] _short_opts: list[str] @@ -89,7 +89,7 @@ class Option: nargs: int type: Any callback: Callable[..., Any] | None - callback_args: Tuple[Any, ...] | None + callback_args: tuple[Any, ...] | None callback_kwargs: dict[str, Any] | None help: str | None metavar: str | None @@ -119,8 +119,8 @@ class OptionContainer: conflict_handler: str defaults: dict[str, Any] description: Any - option_class: Type[Option] - def __init__(self, option_class: Type[Option], conflict_handler: Any, description: Any) -> None: ... + option_class: type[Option] + def __init__(self, option_class: type[Option], conflict_handler: Any, description: Any) -> None: ... def _check_conflict(self, option: Any) -> None: ... def _create_option_mappings(self) -> None: ... def _share_option_mappings(self, parser: OptionParser) -> None: ... @@ -177,7 +177,7 @@ class OptionParser(OptionContainer): self, usage: str | None = ..., option_list: Iterable[Option] | None = ..., - option_class: Type[Option] = ..., + option_class: type[Option] = ..., version: str | None = ..., conflict_handler: str = ..., description: str | None = ..., diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index b432f6931a3f..3341c50f6a7b 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -1,5 +1,6 @@ import sys from _typeshed import ( + BytesPath, FileDescriptorLike, OpenBinaryMode, OpenBinaryModeReading, @@ -9,10 +10,11 @@ from _typeshed import ( Self, StrOrBytesPath, StrPath, + structseq, ) from builtins import OSError +from contextlib import AbstractContextManager from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper as _TextIOWrapper -from posix import listdir as listdir, times_result from subprocess import Popen from typing import ( IO, @@ -20,17 +22,14 @@ from typing import ( AnyStr, BinaryIO, Callable, - ContextManager, Generic, Iterable, Iterator, - List, Mapping, MutableMapping, NoReturn, Protocol, Sequence, - Tuple, TypeVar, Union, overload, @@ -47,6 +46,8 @@ if sys.version_info >= (3, 9): path = _path _T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") _AnyStr_co = TypeVar("_AnyStr_co", str, bytes, covariant=True) # ----- os variables ----- @@ -92,6 +93,9 @@ if sys.platform != "win32": P_PGID: int P_ALL: int + if sys.platform == "linux" and sys.version_info >= (3, 9): + P_PIDFD: int + WEXITED: int WSTOPPED: int WNOWAIT: int @@ -101,6 +105,12 @@ if sys.platform != "win32": CLD_TRAPPED: int CLD_CONTINUED: int + if sys.version_info >= (3, 9): + CLD_KILLED: int + CLD_STOPPED: int + + # TODO: SCHED_RESET_ON_FORK not available on darwin? + # TODO: SCHED_BATCH and SCHED_IDLE are linux only? SCHED_OTHER: int # some flavors of Unix SCHED_BATCH: int # some flavors of Unix SCHED_IDLE: int # some flavors of Unix @@ -119,6 +129,8 @@ if sys.platform != "win32": if sys.platform == "linux": RTLD_DEEPBIND: int + GRND_NONBLOCK: int + GRND_RANDOM: int SEEK_SET: int SEEK_CUR: int @@ -161,6 +173,24 @@ O_NOATIME: int # Gnu extension if in C library O_PATH: int # Gnu extension if in C library O_TMPFILE: int # Gnu extension if in C library O_LARGEFILE: int # Gnu extension if in C library +O_ACCMODE: int # TODO: when does this exist? + +if sys.platform != "win32" and sys.platform != "darwin": + # posix, but apparently missing on macos + ST_APPEND: int + ST_MANDLOCK: int + ST_NOATIME: int + ST_NODEV: int + ST_NODIRATIME: int + ST_NOEXEC: int + ST_RELATIME: int + ST_SYNCHRONOUS: int + ST_WRITE: int + +if sys.platform != "win32": + NGROUPS_MAX: int + ST_NOSUID: int + ST_RDONLY: int curdir: str pardir: str @@ -210,13 +240,23 @@ class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): putenv: Callable[[AnyStr, AnyStr], None], unsetenv: Callable[[AnyStr, AnyStr], None], ) -> None: ... - def setdefault(self, key: AnyStr, value: AnyStr) -> AnyStr: ... # type: ignore + def setdefault(self, key: AnyStr, value: AnyStr) -> AnyStr: ... # type: ignore[override] def copy(self) -> dict[AnyStr, AnyStr]: ... def __delitem__(self, key: AnyStr) -> None: ... def __getitem__(self, key: AnyStr) -> AnyStr: ... def __setitem__(self, key: AnyStr, value: AnyStr) -> None: ... def __iter__(self) -> Iterator[AnyStr]: ... def __len__(self) -> int: ... + if sys.version_info >= (3, 9): + def __or__(self, value: Mapping[_T1, _T2]) -> dict[AnyStr | _T1, AnyStr | _T2]: ... + def __ror__(self, value: Mapping[_T1, _T2]) -> dict[AnyStr | _T1, AnyStr | _T2]: ... + # We use @overload instead of a Union for reasons similar to those given for + # overloading MutableMapping.update in stdlib/typing.pyi + # The type: ignore is needed due to incompatible __or__/__ior__ signatures + @overload # type: ignore[misc] + def __ior__(self: Self, value: Mapping[AnyStr, AnyStr]) -> Self: ... + @overload + def __ior__(self: Self, value: Iterable[tuple[AnyStr, AnyStr]]) -> Self: ... environ: _Environ[str] if sys.platform != "win32": @@ -262,55 +302,82 @@ 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 - # (and portable) members of the stat structure, in the order st_mode, - # st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, - # st_ctime. More items may be added at the end by some implementations. - - st_mode: int # protection bits, - st_ino: int # inode number, - st_dev: int # device, - st_nlink: int # number of hard links, - st_uid: int # user id of owner, - st_gid: int # group id of owner, - st_size: int # size of file, in bytes, - st_atime: float # time of most recent access, - st_mtime: float # time of most recent content modification, - st_ctime: float # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) - st_atime_ns: int # time of most recent access, in nanoseconds - st_mtime_ns: int # time of most recent content modification in nanoseconds - st_ctime_ns: int # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) in nanoseconds - if sys.version_info >= (3, 8) and sys.platform == "win32": - st_reparse_tag: int +class stat_result(structseq[float], tuple[int, int, int, int, int, int, int, float, float, float]): + # The constructor of this class takes an iterable of variable length (though it must be at least 10). + # + # However, this class behaves like a tuple of 10 elements, + # no matter how long the iterable supplied to the constructor is. + # https://github.com/python/typeshed/pull/6560#discussion_r767162532 + # + # The 10 elements always present are st_mode, st_ino, st_dev, st_nlink, + # st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime. + # + # More items may be added at the end by some implementations. + @property + def st_mode(self) -> int: ... # protection bits, + @property + def st_ino(self) -> int: ... # inode number, + @property + def st_dev(self) -> int: ... # device, + @property + def st_nlink(self) -> int: ... # number of hard links, + @property + def st_uid(self) -> int: ... # user id of owner, + @property + def st_gid(self) -> int: ... # group id of owner, + @property + def st_size(self) -> int: ... # size of file, in bytes, + @property + def st_atime(self) -> float: ... # time of most recent access, + @property + def st_mtime(self) -> float: ... # time of most recent content modification, + # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) + @property + def st_ctime(self) -> float: ... + @property + def st_atime_ns(self) -> int: ... # time of most recent access, in nanoseconds + @property + def st_mtime_ns(self) -> int: ... # time of most recent content modification in nanoseconds + # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) in nanoseconds + @property + def st_ctime_ns(self) -> int: ... if sys.platform == "win32": - st_file_attributes: int - def __getitem__(self, i: int) -> int: ... - # not documented - def __init__(self, tuple: Tuple[int, ...]) -> None: ... - # On some Unix systems (such as Linux), the following attributes may also - # be available: - st_blocks: int # number of blocks allocated for file - st_blksize: int # filesystem blocksize - st_rdev: int # type of device if an inode device - st_flags: int # user defined flags for file - - # On other Unix systems (such as FreeBSD), the following attributes may be - # available (but may be only filled out if root tries to use them): - st_gen: int # file generation number - st_birthtime: int # time of file creation - - # On Mac OS systems, the following attributes may also be available: - st_rsize: int - st_creator: int - st_type: int + @property + def st_file_attributes(self) -> int: ... + if sys.version_info >= (3, 8): + @property + def st_reparse_tag(self) -> int: ... + else: + @property + def st_blocks(self) -> int: ... # number of blocks allocated for file + @property + def st_blksize(self) -> int: ... # filesystem blocksize + @property + def st_rdev(self) -> int: ... # type of device if an inode device + if sys.platform != "linux": + # These properties are available on MacOS, but not on Windows or Ubuntu. + # On other Unix systems (such as FreeBSD), the following attributes may be + # available (but may be only filled out if root tries to use them): + @property + def st_gen(self) -> int: ... # file generation number + @property + def st_birthtime(self) -> int: ... # time of file creation + if sys.platform == "darwin": + @property + def st_flags(self) -> int: ... # user defined flags for file + # Attributes documented as sometimes appearing, but deliberately omitted from the stub: `st_creator`, `st_rsize`, `st_type`. + # See https://github.com/python/typeshed/pull/6560#issuecomment-991253327 @runtime_checkable class PathLike(Protocol[_AnyStr_co]): def __fspath__(self) -> _AnyStr_co: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +@overload +def listdir(path: StrPath | None = ...) -> list[str]: ... +@overload +def listdir(path: BytesPath) -> list[bytes]: ... +@overload +def listdir(path: int) -> list[str]: ... _FdOrAnyPath = Union[int, StrOrBytesPath] @@ -330,45 +397,36 @@ class DirEntry(Generic[AnyStr]): if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... -if sys.platform != "win32": - _Tuple10Int = Tuple[int, int, int, int, int, int, int, int, int, int] - _Tuple11Int = Tuple[int, int, int, int, int, int, int, int, int, int, int] +if sys.version_info >= (3, 7): + _StatVfsTuple = tuple[int, int, int, int, int, int, int, int, int, int, int] +else: + _StatVfsTuple = tuple[int, int, int, int, int, int, int, int, int, int] + +@final +class statvfs_result(structseq[int], _StatVfsTuple): + @property + def f_bsize(self) -> int: ... + @property + def f_frsize(self) -> int: ... + @property + def f_blocks(self) -> int: ... + @property + def f_bfree(self) -> int: ... + @property + def f_bavail(self) -> int: ... + @property + def f_files(self) -> int: ... + @property + def f_ffree(self) -> int: ... + @property + def f_favail(self) -> int: ... + @property + def f_flag(self) -> int: ... + @property + def f_namemax(self) -> 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 - n_sequence_fields: int - n_unnamed_fields: int - - f_bsize: int - f_frsize: int - f_blocks: int - f_bfree: int - f_bavail: int - f_files: int - f_ffree: int - f_favail: int - f_flag: int - f_namemax: int - f_fsid: int - else: - class statvfs_result(_Tuple10Int): # Unix only - n_fields: int - n_sequence_fields: int - n_unnamed_fields: int - - f_bsize: int - f_frsize: int - f_blocks: int - f_bfree: int - f_bavail: int - f_files: int - f_ffree: int - f_favail: int - f_flag: int - f_namemax: int + @property + def f_fsid(self) -> int: ... # ----- os function stubs ----- def fsencode(filename: StrOrBytesPath) -> bytes: ... @@ -385,9 +443,20 @@ def getpid() -> int: ... def getppid() -> int: ... def strerror(__code: int) -> str: ... def umask(__mask: int) -> int: ... +@final +class uname_result(structseq[str], tuple[str, str, str, str, str]): + @property + def sysname(self) -> str: ... + @property + def nodename(self) -> str: ... + @property + def release(self) -> str: ... + @property + def version(self) -> str: ... + @property + def machine(self) -> str: ... if sys.platform != "win32": - # Unix only def ctermid() -> str: ... def getegid() -> int: ... def geteuid() -> int: ... @@ -417,7 +486,6 @@ if sys.platform != "win32": def getsid(__pid: int) -> int: ... def setsid() -> None: ... def setuid(__uid: int) -> None: ... - from posix import uname_result def uname() -> uname_result: ... @overload @@ -433,7 +501,7 @@ if sys.platform != "win32": def putenv(__name: bytes | str, __value: bytes | str) -> None: ... -if sys.platform != "win32": +if sys.platform != "win32" or sys.version_info >= (3, 9): def unsetenv(__name: bytes | str) -> None: ... _Opener = Callable[[str, int], int] @@ -527,7 +595,9 @@ else: def dup2(fd: int, fd2: int, inheritable: bool = ...) -> None: ... def fstat(fd: int) -> stat_result: ... +def ftruncate(__fd: int, __length: int) -> None: ... def fsync(fd: FileDescriptorLike) -> None: ... +def isatty(__fd: int) -> bool: ... def lseek(__fd: int, __position: int, __how: int) -> int: ... def open(path: StrOrBytesPath, flags: int, mode: int = ..., *, dir_fd: int | None = ...) -> int: ... def pipe() -> tuple[int, int]: ... @@ -537,22 +607,29 @@ if sys.platform != "win32": # Unix only def fchmod(fd: int, mode: int) -> None: ... def fchown(fd: int, uid: int, gid: int) -> None: ... - if sys.platform != "darwin": - def fdatasync(fd: FileDescriptorLike) -> None: ... # Unix only, not Mac def fpathconf(__fd: int, __name: str | int) -> int: ... def fstatvfs(__fd: int) -> statvfs_result: ... - def ftruncate(__fd: int, __length: int) -> None: ... def get_blocking(__fd: int) -> bool: ... def set_blocking(__fd: int, __blocking: bool) -> None: ... - def isatty(__fd: int) -> bool: ... def lockf(__fd: int, __command: int, __length: int) -> None: ... def openpty() -> tuple[int, int]: ... # some flavors of Unix if sys.platform != "darwin": - def pipe2(flags: int) -> tuple[int, int]: ... # some flavors of Unix + def fdatasync(fd: FileDescriptorLike) -> None: ... + def pipe2(__flags: int) -> tuple[int, int]: ... # some flavors of Unix def posix_fallocate(fd: int, offset: int, length: int) -> None: ... def posix_fadvise(fd: int, offset: int, length: int, advice: int) -> None: ... def pread(__fd: int, __length: int, __offset: int) -> bytes: ... def pwrite(__fd: int, __buffer: bytes, __offset: int) -> int: ... + if sys.platform != "darwin": + if sys.version_info >= (3, 10): + RWF_APPEND: int # docs say available on 3.7+, stubtest says otherwise + if sys.version_info >= (3, 7): + def preadv(__fd: int, __buffers: Iterable[bytes], __offset: int, __flags: int = ...) -> int: ... + def pwritev(__fd: int, __buffers: Iterable[bytes], __offset: int, __flags: int = ...) -> int: ... + RWF_DSYNC: int + RWF_SYNC: int + RWF_HIPRI: int + RWF_NOWAIT: int @overload def sendfile(out_fd: int, in_fd: int, offset: int | None, count: int) -> int: ... @overload @@ -569,9 +646,11 @@ if sys.platform != "win32": def writev(__fd: int, __buffers: Sequence[bytes]) -> int: ... @final -class terminal_size(Tuple[int, int]): - columns: int - lines: int +class terminal_size(structseq[int], tuple[int, int]): + @property + def columns(self) -> int: ... + @property + def lines(self) -> int: ... def get_terminal_size(fd: int = ...) -> terminal_size: ... def get_inheritable(__fd: int) -> bool: ... @@ -596,17 +675,14 @@ def getcwd() -> str: ... def getcwdb() -> bytes: ... def chmod(path: _FdOrAnyPath, mode: int, *, dir_fd: int | None = ..., follow_symlinks: bool = ...) -> None: ... -if sys.platform != "win32": +if sys.platform != "win32" and sys.platform != "linux": def chflags(path: StrOrBytesPath, flags: int, follow_symlinks: bool = ...) -> None: ... # some flavors of Unix - def chown( - path: _FdOrAnyPath, uid: int, gid: int, *, dir_fd: int | None = ..., follow_symlinks: bool = ... - ) -> None: ... # Unix only + def lchflags(path: StrOrBytesPath, flags: int) -> None: ... + def lchmod(path: StrOrBytesPath, mode: int) -> None: ... if sys.platform != "win32": - # Unix only def chroot(path: StrOrBytesPath) -> None: ... - def lchflags(path: StrOrBytesPath, flags: int) -> None: ... - def lchmod(path: StrOrBytesPath, mode: int) -> None: ... + def chown(path: _FdOrAnyPath, uid: int, gid: int, *, dir_fd: int | None = ..., follow_symlinks: bool = ...) -> None: ... def lchown(path: StrOrBytesPath, uid: int, gid: int) -> None: ... def link( @@ -640,7 +716,7 @@ def renames(old: StrOrBytesPath, new: StrOrBytesPath) -> None: ... def replace(src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = ..., dst_dir_fd: int | None = ...) -> None: ... def rmdir(path: StrOrBytesPath, *, dir_fd: int | None = ...) -> None: ... -class _ScandirIterator(Iterator[DirEntry[AnyStr]], ContextManager[_ScandirIterator[AnyStr]]): +class _ScandirIterator(Iterator[DirEntry[AnyStr]], AbstractContextManager[_ScandirIterator[AnyStr]]): def __next__(self) -> DirEntry[AnyStr]: ... def close(self) -> None: ... @@ -744,14 +820,14 @@ def execlpe(file: StrOrBytesPath, __arg0: StrOrBytesPath, *args: Any) -> NoRetur # in practice, and doing so would explode the number of combinations in this already long union. # All these combinations are necessary due to list being invariant. _ExecVArgs = Union[ - Tuple[StrOrBytesPath, ...], - List[bytes], - List[str], - List[PathLike[Any]], - List[Union[bytes, str]], - List[Union[bytes, PathLike[Any]]], - List[Union[str, PathLike[Any]]], - List[Union[bytes, str, PathLike[Any]]], + tuple[StrOrBytesPath, ...], + list[bytes], + list[str], + list[PathLike[Any]], + list[Union[bytes, str]], + list[Union[bytes, PathLike[Any]]], + list[Union[str, PathLike[Any]]], + list[Union[bytes, str, PathLike[Any]]], ] _ExecEnv = Union[Mapping[bytes, Union[bytes, str]], Mapping[str, Union[bytes, str]]] @@ -773,7 +849,7 @@ if sys.platform != "win32": class _wrap_close(_TextIOWrapper): def __init__(self, stream: _TextIOWrapper, proc: Popen[str]) -> None: ... - def close(self) -> int | None: ... # type: ignore + def close(self) -> int | None: ... # type: ignore[override] def popen(cmd: str, mode: str = ..., buffering: int = ...) -> _wrap_close: ... def spawnl(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ... @@ -788,6 +864,19 @@ else: def spawnve(__mode: int, __path: StrOrBytesPath, __argv: _ExecVArgs, __env: _ExecEnv) -> int: ... def system(command: StrOrBytesPath) -> int: ... +@final +class times_result(structseq[float], tuple[float, float, float, float, float]): + @property + def user(self) -> float: ... + @property + def system(self) -> float: ... + @property + def children_user(self) -> float: ... + @property + def children_system(self) -> float: ... + @property + def elapsed(self) -> float: ... + def times() -> times_result: ... def waitpid(__pid: int, __options: int) -> tuple[int, int]: ... @@ -795,14 +884,24 @@ if sys.platform == "win32": def startfile(path: StrOrBytesPath, operation: str | None = ...) -> None: ... else: - # Unix only def spawnlp(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ... def spawnlpe(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ... # Imprecise signature def spawnvp(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ... def spawnvpe(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ... def wait() -> tuple[int, int]: ... # Unix only if sys.platform != "darwin": - from posix import waitid_result + @final + class waitid_result(structseq[int], tuple[int, int, int, int, int]): + @property + def si_pid(self) -> int: ... + @property + def si_uid(self) -> int: ... + @property + def si_signo(self) -> int: ... + @property + def si_status(self) -> int: ... + @property + def si_code(self) -> int: ... def waitid(idtype: int, ident: int, options: int) -> waitid_result: ... def wait3(options: int) -> tuple[int, int, Any]: ... def wait4(pid: int, options: int) -> tuple[int, int, Any]: ... @@ -815,10 +914,42 @@ else: def WSTOPSIG(status: int) -> int: ... def WTERMSIG(status: int) -> int: ... if sys.version_info >= (3, 8): - from posix import posix_spawn as posix_spawn, posix_spawnp as posix_spawnp + def posix_spawn( + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv, + *, + file_actions: Sequence[tuple[Any, ...]] | None = ..., + setpgroup: int | None = ..., + resetids: bool = ..., + setsid: bool = ..., + setsigmask: Iterable[int] = ..., + setsigdef: Iterable[int] = ..., + scheduler: tuple[Any, sched_param] | None = ..., + ) -> int: ... + def posix_spawnp( + path: StrOrBytesPath, + argv: _ExecVArgs, + env: _ExecEnv, + *, + file_actions: Sequence[tuple[Any, ...]] | None = ..., + setpgroup: int | None = ..., + resetids: bool = ..., + setsid: bool = ..., + setsigmask: Iterable[int] = ..., + setsigdef: Iterable[int] = ..., + scheduler: tuple[Any, sched_param] | None = ..., + ) -> int: ... + POSIX_SPAWN_OPEN: int + POSIX_SPAWN_CLOSE: int + POSIX_SPAWN_DUP2: int if sys.platform != "win32": - from posix import sched_param + @final + class sched_param(structseq[int], tuple[int]): + def __new__(cls, sched_priority: int) -> sched_param: ... + @property + def sched_priority(self) -> int: ... def sched_get_priority_min(policy: int) -> int: ... # some flavors of Unix def sched_get_priority_max(policy: int) -> int: ... # some flavors of Unix def sched_yield() -> None: ... # some flavors of Unix @@ -880,3 +1011,6 @@ if sys.version_info >= (3, 8): MFD_HUGE_2GB: int MFD_HUGE_16GB: int def memfd_create(name: str, flags: int = ...) -> int: ... + +if sys.version_info >= (3, 9): + def waitstatus_to_exitcode(status: int) -> int: ... diff --git a/mypy/typeshed/stdlib/parser.pyi b/mypy/typeshed/stdlib/parser.pyi index aecf3244ca8d..ab819a71a15f 100644 --- a/mypy/typeshed/stdlib/parser.pyi +++ b/mypy/typeshed/stdlib/parser.pyi @@ -1,13 +1,13 @@ from _typeshed import StrOrBytesPath from types import CodeType -from typing import Any, Sequence, Tuple +from typing import Any, Sequence def expr(source: str) -> STType: ... def suite(source: str) -> STType: ... def sequence2st(sequence: Sequence[Any]) -> STType: ... def tuple2st(sequence: Sequence[Any]) -> STType: ... def st2list(st: STType, line_info: bool = ..., col_info: bool = ...) -> list[Any]: ... -def st2tuple(st: STType, line_info: bool = ..., col_info: bool = ...) -> Tuple[Any, ...]: ... +def st2tuple(st: STType, line_info: bool = ..., col_info: bool = ...) -> tuple[Any, ...]: ... def compilest(st: STType, filename: StrOrBytesPath = ...) -> CodeType: ... def isexpr(st: STType) -> bool: ... def issuite(st: STType) -> bool: ... @@ -19,4 +19,4 @@ class STType: def isexpr(self) -> bool: ... def issuite(self) -> bool: ... def tolist(self, line_info: bool = ..., col_info: bool = ...) -> list[Any]: ... - def totuple(self, line_info: bool = ..., col_info: bool = ...) -> Tuple[Any, ...]: ... + def totuple(self, line_info: bool = ..., col_info: bool = ...) -> tuple[Any, ...]: ... diff --git a/mypy/typeshed/stdlib/pathlib.pyi b/mypy/typeshed/stdlib/pathlib.pyi index 7d5f7ff2dba8..3313bae9c2d9 100644 --- a/mypy/typeshed/stdlib/pathlib.pyi +++ b/mypy/typeshed/stdlib/pathlib.pyi @@ -11,16 +11,14 @@ from _typeshed import ( from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper from os import PathLike, stat_result from types import TracebackType -from typing import IO, Any, BinaryIO, Generator, Sequence, Tuple, Type, TypeVar, overload +from typing import IO, Any, BinaryIO, Generator, Sequence, overload from typing_extensions import Literal if sys.version_info >= (3, 9): from types import GenericAlias -_P = TypeVar("_P", bound=PurePath) - class PurePath(PathLike[str]): - parts: Tuple[str, ...] + parts: tuple[str, ...] drive: str root: str anchor: str @@ -28,14 +26,14 @@ class PurePath(PathLike[str]): suffix: str suffixes: list[str] stem: str - def __new__(cls: Type[_P], *args: StrPath) -> _P: ... + def __new__(cls: type[Self], *args: StrPath) -> Self: ... def __hash__(self) -> int: ... def __lt__(self, other: PurePath) -> bool: ... def __le__(self, other: PurePath) -> bool: ... def __gt__(self, other: PurePath) -> bool: ... def __ge__(self, other: PurePath) -> bool: ... - def __truediv__(self: _P, key: StrPath) -> _P: ... - def __rtruediv__(self: _P, key: StrPath) -> _P: ... + def __truediv__(self: Self, key: StrPath) -> Self: ... + def __rtruediv__(self: Self, key: StrPath) -> Self: ... def __bytes__(self) -> bytes: ... def as_posix(self) -> str: ... def as_uri(self) -> str: ... @@ -44,16 +42,16 @@ class PurePath(PathLike[str]): if sys.version_info >= (3, 9): def is_relative_to(self, *other: StrPath) -> bool: ... def match(self, path_pattern: str) -> bool: ... - def relative_to(self: _P, *other: StrPath) -> _P: ... - def with_name(self: _P, name: str) -> _P: ... + def relative_to(self: Self, *other: StrPath) -> Self: ... + def with_name(self: Self, name: str) -> Self: ... if sys.version_info >= (3, 9): - def with_stem(self: _P, stem: str) -> _P: ... - def with_suffix(self: _P, suffix: str) -> _P: ... - def joinpath(self: _P, *other: StrPath) -> _P: ... + def with_stem(self: Self, stem: str) -> Self: ... + def with_suffix(self: Self, suffix: str) -> Self: ... + def joinpath(self: Self, *other: StrPath) -> Self: ... @property - def parents(self: _P) -> Sequence[_P]: ... + def parents(self: Self) -> Sequence[Self]: ... @property - def parent(self: _P) -> _P: ... + def parent(self: Self) -> Self: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, type: Any) -> GenericAlias: ... @@ -61,13 +59,13 @@ class PurePosixPath(PurePath): ... class PureWindowsPath(PurePath): ... class Path(PurePath): - def __new__(cls: Type[_P], *args: StrPath, **kwargs: Any) -> _P: ... + def __new__(cls: type[Self], *args: StrPath, **kwargs: Any) -> Self: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None ) -> bool | None: ... @classmethod - def cwd(cls: Type[_P]) -> _P: ... + def cwd(cls: type[Self]) -> Self: ... if sys.version_info >= (3, 10): def stat(self, *, follow_symlinks: bool = ...) -> stat_result: ... def chmod(self, mode: int, *, follow_symlinks: bool = ...) -> None: ... @@ -75,7 +73,7 @@ class Path(PurePath): 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 glob(self: Self, pattern: str) -> Generator[Self, None, None]: ... def group(self) -> str: ... def is_dir(self) -> bool: ... def is_file(self) -> bool: ... @@ -86,7 +84,7 @@ class Path(PurePath): def is_fifo(self) -> bool: ... def is_block_device(self) -> bool: ... def is_char_device(self) -> bool: ... - def iterdir(self: _P) -> Generator[_P, None, None]: ... + def iterdir(self: Self) -> Generator[Self, None, None]: ... def lchmod(self, mode: int) -> None: ... def lstat(self) -> stat_result: ... def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: ... @@ -147,15 +145,15 @@ class Path(PurePath): ) -> IO[Any]: ... def owner(self) -> str: ... if sys.version_info >= (3, 9): - def readlink(self: _P) -> _P: ... + def readlink(self: Self) -> Self: ... if sys.version_info >= (3, 8): - def rename(self: _P, target: str | PurePath) -> _P: ... - def replace(self: _P, target: str | PurePath) -> _P: ... + def rename(self: Self, target: str | PurePath) -> Self: ... + def replace(self: Self, target: str | PurePath) -> Self: ... else: def rename(self, target: str | PurePath) -> None: ... def replace(self, target: str | PurePath) -> None: ... - def resolve(self: _P, strict: bool = ...) -> _P: ... - def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ... + def resolve(self: Self, strict: bool = ...) -> Self: ... + def rglob(self: Self, pattern: str) -> Generator[Self, None, None]: ... def rmdir(self) -> None: ... def symlink_to(self, target: str | Path, target_is_directory: bool = ...) -> None: ... if sys.version_info >= (3, 10): @@ -166,9 +164,9 @@ class Path(PurePath): else: def unlink(self) -> None: ... @classmethod - def home(cls: Type[_P]) -> _P: ... - def absolute(self: _P) -> _P: ... - def expanduser(self: _P) -> _P: ... + def home(cls: type[Self]) -> Self: ... + def absolute(self: Self) -> Self: ... + def expanduser(self: Self) -> Self: ... def read_bytes(self) -> bytes: ... def read_text(self, encoding: str | None = ..., errors: str | None = ...) -> str: ... def samefile(self, other_path: str | bytes | int | Path) -> bool: ... diff --git a/mypy/typeshed/stdlib/pickle.pyi b/mypy/typeshed/stdlib/pickle.pyi index cef1ffe9eb9b..d165e6e285ef 100644 --- a/mypy/typeshed/stdlib/pickle.pyi +++ b/mypy/typeshed/stdlib/pickle.pyi @@ -1,11 +1,11 @@ import sys -from typing import Any, Callable, ClassVar, Iterable, Iterator, Mapping, Optional, Protocol, Tuple, Type, Union +from typing import Any, Callable, ClassVar, Iterable, Iterator, Mapping, Optional, Protocol, Union from typing_extensions import final HIGHEST_PROTOCOL: int DEFAULT_PROTOCOL: int -bytes_types: Tuple[Type[Any], ...] # undocumented +bytes_types: tuple[type[Any], ...] # undocumented class _ReadableFileobj(Protocol): def read(self, __n: int) -> bytes: ... @@ -58,10 +58,10 @@ class UnpicklingError(PickleError): ... _reducedtype = Union[ str, - Tuple[Callable[..., Any], Tuple[Any, ...]], - Tuple[Callable[..., Any], Tuple[Any, ...], Any], - Tuple[Callable[..., Any], Tuple[Any, ...], Any, Optional[Iterator[Any]]], - Tuple[Callable[..., Any], Tuple[Any, ...], Any, Optional[Iterator[Any]], Optional[Iterator[Any]]], + tuple[Callable[..., Any], tuple[Any, ...]], + tuple[Callable[..., Any], tuple[Any, ...], Any], + tuple[Callable[..., Any], tuple[Any, ...], Any, Optional[Iterator[Any]]], + tuple[Callable[..., Any], tuple[Any, ...], Any, Optional[Iterator[Any]], Optional[Iterator[Any]]], ] class Pickler: diff --git a/mypy/typeshed/stdlib/pickletools.pyi b/mypy/typeshed/stdlib/pickletools.pyi index 9fa51a3848ee..056d115f52e7 100644 --- a/mypy/typeshed/stdlib/pickletools.pyi +++ b/mypy/typeshed/stdlib/pickletools.pyi @@ -1,7 +1,7 @@ -from typing import IO, Any, Callable, Iterator, MutableMapping, Tuple, Type +from typing import IO, Any, Callable, Iterator, MutableMapping _Reader = Callable[[IO[bytes]], Any] -bytes_types: Tuple[Type[Any], ...] +bytes_types: tuple[type[Any], ...] UP_TO_NEWLINE: int TAKEN_FROM_ARGUMENT1: int @@ -9,7 +9,7 @@ TAKEN_FROM_ARGUMENT4: int TAKEN_FROM_ARGUMENT4U: int TAKEN_FROM_ARGUMENT8U: int -class ArgumentDescriptor(object): +class ArgumentDescriptor: name: str n: int reader: _Reader @@ -106,11 +106,11 @@ def read_long4(f: IO[bytes]) -> int: ... long4: ArgumentDescriptor -class StackObject(object): +class StackObject: name: str - obtype: Type[Any] | Tuple[Type[Any], ...] + obtype: type[Any] | tuple[type[Any], ...] doc: str - def __init__(self, name: str, obtype: Type[Any] | Tuple[Type[Any], ...], doc: str) -> None: ... + def __init__(self, name: str, obtype: type[Any] | tuple[type[Any], ...], doc: str) -> None: ... pyint: StackObject pylong: StackObject @@ -131,7 +131,7 @@ anyobject: StackObject markobject: StackObject stackslice: StackObject -class OpcodeInfo(object): +class OpcodeInfo: name: str code: str arg: ArgumentDescriptor | None diff --git a/mypy/typeshed/stdlib/pkgutil.pyi b/mypy/typeshed/stdlib/pkgutil.pyi index e0f392fd91d8..0b60a4868143 100644 --- a/mypy/typeshed/stdlib/pkgutil.pyi +++ b/mypy/typeshed/stdlib/pkgutil.pyi @@ -18,7 +18,7 @@ class ImpLoader: def find_loader(fullname: str) -> Loader | None: ... def get_importer(path_item: str) -> PathEntryFinder | None: ... -def get_loader(module_or_name: str) -> Loader: ... +def get_loader(module_or_name: str) -> Loader | None: ... def iter_importers(fullname: str = ...) -> Iterator[MetaPathFinder | PathEntryFinder]: ... def iter_modules(path: Iterable[str] | None = ..., prefix: str = ...) -> Iterator[ModuleInfo]: ... def read_code(stream: SupportsRead[bytes]) -> Any: ... # undocumented diff --git a/mypy/typeshed/stdlib/platform.pyi b/mypy/typeshed/stdlib/platform.pyi index 7db2d59ff7ea..765a7a5ea5f9 100644 --- a/mypy/typeshed/stdlib/platform.pyi +++ b/mypy/typeshed/stdlib/platform.pyi @@ -4,7 +4,7 @@ if sys.version_info < (3, 8): import os DEV_NULL = os.devnull -from typing import NamedTuple, Tuple +from typing import NamedTuple if sys.version_info >= (3, 8): def libc_ver(executable: str | None = ..., lib: str = ..., version: str = ..., chunksize: int = ...) -> tuple[str, str]: ... @@ -17,11 +17,11 @@ if sys.version_info < (3, 8): distname: str = ..., version: str = ..., id: str = ..., - supported_dists: Tuple[str, ...] = ..., + supported_dists: tuple[str, ...] = ..., full_distribution_name: bool = ..., ) -> tuple[str, str, str]: ... def dist( - distname: str = ..., version: str = ..., id: str = ..., supported_dists: Tuple[str, ...] = ... + distname: str = ..., version: str = ..., id: str = ..., supported_dists: tuple[str, ...] = ... ) -> tuple[str, str, str]: ... def win32_ver(release: str = ..., version: str = ..., csd: str = ..., ptype: str = ...) -> tuple[str, str, str, str]: ... @@ -62,3 +62,6 @@ def python_revision() -> str: ... def python_build() -> tuple[str, str]: ... def python_compiler() -> str: ... def platform(aliased: bool = ..., terse: bool = ...) -> str: ... + +if sys.version_info >= (3, 10): + def freedesktop_os_release() -> dict[str, str]: ... diff --git a/mypy/typeshed/stdlib/plistlib.pyi b/mypy/typeshed/stdlib/plistlib.pyi index 07b6963746be..6f8157fe502a 100644 --- a/mypy/typeshed/stdlib/plistlib.pyi +++ b/mypy/typeshed/stdlib/plistlib.pyi @@ -1,7 +1,7 @@ import sys from datetime import datetime from enum import Enum -from typing import IO, Any, Dict as _Dict, Mapping, MutableMapping, Tuple, Type +from typing import IO, Any, Mapping, MutableMapping class PlistFormat(Enum): FMT_XML: int @@ -11,8 +11,8 @@ FMT_XML = PlistFormat.FMT_XML FMT_BINARY = PlistFormat.FMT_BINARY if sys.version_info >= (3, 9): - def load(fp: IO[bytes], *, fmt: PlistFormat | None = ..., dict_type: Type[MutableMapping[str, Any]] = ...) -> Any: ... - def loads(value: bytes, *, fmt: PlistFormat | None = ..., dict_type: Type[MutableMapping[str, Any]] = ...) -> Any: ... + def load(fp: IO[bytes], *, fmt: PlistFormat | None = ..., dict_type: type[MutableMapping[str, Any]] = ...) -> Any: ... + def loads(value: bytes, *, fmt: PlistFormat | None = ..., dict_type: type[MutableMapping[str, Any]] = ...) -> Any: ... else: def load( @@ -20,18 +20,18 @@ else: *, fmt: PlistFormat | None = ..., use_builtin_types: bool = ..., - dict_type: Type[MutableMapping[str, Any]] = ..., + dict_type: type[MutableMapping[str, Any]] = ..., ) -> Any: ... def loads( value: bytes, *, fmt: PlistFormat | None = ..., use_builtin_types: bool = ..., - dict_type: Type[MutableMapping[str, Any]] = ..., + dict_type: type[MutableMapping[str, Any]] = ..., ) -> Any: ... def dump( - value: Mapping[str, Any] | list[Any] | Tuple[Any, ...] | str | bool | float | bytes | datetime, + value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | datetime, fp: IO[bytes], *, fmt: PlistFormat = ..., @@ -39,7 +39,7 @@ def dump( skipkeys: bool = ..., ) -> None: ... def dumps( - value: Mapping[str, Any] | list[Any] | Tuple[Any, ...] | str | bool | float | bytes | datetime, + value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | datetime, *, fmt: PlistFormat = ..., skipkeys: bool = ..., @@ -53,7 +53,7 @@ if sys.version_info < (3, 9): def writePlistToBytes(value: Mapping[str, Any]) -> bytes: ... if sys.version_info < (3, 7): - class Dict(_Dict[str, Any]): + class Dict(dict[str, Any]): def __getattr__(self, attr: str) -> Any: ... def __setattr__(self, attr: str, value: Any) -> None: ... def __delattr__(self, attr: str) -> None: ... diff --git a/mypy/typeshed/stdlib/poplib.pyi b/mypy/typeshed/stdlib/poplib.pyi index 28fba4ce951f..028af412847b 100644 --- a/mypy/typeshed/stdlib/poplib.pyi +++ b/mypy/typeshed/stdlib/poplib.pyi @@ -1,8 +1,8 @@ import socket import ssl -from typing import Any, BinaryIO, List, Pattern, Tuple, overload +from typing import Any, BinaryIO, Pattern, overload -_LongResp = Tuple[bytes, List[bytes], int] +_LongResp = tuple[bytes, list[bytes], int] class error_proto(Exception): ... diff --git a/mypy/typeshed/stdlib/posix.pyi b/mypy/typeshed/stdlib/posix.pyi index 14cea87cde29..9f658039bcf2 100644 --- a/mypy/typeshed/stdlib/posix.pyi +++ b/mypy/typeshed/stdlib/posix.pyi @@ -1,204 +1,322 @@ 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 - release: str - version: str - machine: str +if sys.platform != "win32": + # Actually defined here, but defining in os allows sharing code with windows + from os import ( + CLD_CONTINUED as CLD_CONTINUED, + CLD_DUMPED as CLD_DUMPED, + CLD_EXITED as CLD_EXITED, + CLD_TRAPPED as CLD_TRAPPED, + EX_CANTCREAT as EX_CANTCREAT, + EX_CONFIG as EX_CONFIG, + EX_DATAERR as EX_DATAERR, + EX_IOERR as EX_IOERR, + EX_NOHOST as EX_NOHOST, + EX_NOINPUT as EX_NOINPUT, + EX_NOPERM as EX_NOPERM, + EX_NOTFOUND as EX_NOTFOUND, + EX_NOUSER as EX_NOUSER, + EX_OK as EX_OK, + EX_OSERR as EX_OSERR, + EX_OSFILE as EX_OSFILE, + EX_PROTOCOL as EX_PROTOCOL, + EX_SOFTWARE as EX_SOFTWARE, + EX_TEMPFAIL as EX_TEMPFAIL, + EX_UNAVAILABLE as EX_UNAVAILABLE, + EX_USAGE as EX_USAGE, + F_LOCK as F_LOCK, + F_OK as F_OK, + F_TEST as F_TEST, + F_TLOCK as F_TLOCK, + F_ULOCK as F_ULOCK, + O_APPEND as O_APPEND, + O_ASYNC as O_ASYNC, + O_CREAT as O_CREAT, + O_DIRECT as O_DIRECT, + O_DIRECTORY as O_DIRECTORY, + O_DSYNC as O_DSYNC, + O_EXCL as O_EXCL, + O_LARGEFILE as O_LARGEFILE, + O_NDELAY as O_NDELAY, + O_NOATIME as O_NOATIME, + O_NOCTTY as O_NOCTTY, + O_NOFOLLOW as O_NOFOLLOW, + O_NONBLOCK as O_NONBLOCK, + O_RDONLY as O_RDONLY, + O_RDWR as O_RDWR, + O_RSYNC as O_RSYNC, + O_SYNC as O_SYNC, + O_TRUNC as O_TRUNC, + O_WRONLY as O_WRONLY, + P_ALL as P_ALL, + P_PGID as P_PGID, + P_PID as P_PID, + PRIO_PGRP as PRIO_PGRP, + PRIO_PROCESS as PRIO_PROCESS, + PRIO_USER as PRIO_USER, + R_OK as R_OK, + RTLD_GLOBAL as RTLD_GLOBAL, + RTLD_LAZY as RTLD_LAZY, + RTLD_LOCAL as RTLD_LOCAL, + RTLD_NODELETE as RTLD_NODELETE, + RTLD_NOLOAD as RTLD_NOLOAD, + RTLD_NOW as RTLD_NOW, + SCHED_BATCH as SCHED_BATCH, + SCHED_FIFO as SCHED_FIFO, + SCHED_IDLE as SCHED_IDLE, + SCHED_OTHER as SCHED_OTHER, + SCHED_RESET_ON_FORK as SCHED_RESET_ON_FORK, + SCHED_RR as SCHED_RR, + SCHED_SPORADIC as SCHED_SPORADIC, + SEEK_DATA as SEEK_DATA, + SEEK_HOLE as SEEK_HOLE, + ST_NOSUID as ST_NOSUID, + ST_RDONLY as ST_RDONLY, + TMP_MAX as TMP_MAX, + W_OK as W_OK, + WCONTINUED as WCONTINUED, + WCOREDUMP as WCOREDUMP, + WEXITED as WEXITED, + WEXITSTATUS as WEXITSTATUS, + WIFCONTINUED as WIFCONTINUED, + WIFEXITED as WIFEXITED, + WIFSIGNALED as WIFSIGNALED, + WIFSTOPPED as WIFSTOPPED, + WNOHANG as WNOHANG, + WNOWAIT as WNOWAIT, + WSTOPPED as WSTOPPED, + WSTOPSIG as WSTOPSIG, + WTERMSIG as WTERMSIG, + WUNTRACED as WUNTRACED, + X_OK as X_OK, + DirEntry as DirEntry, + _exit as _exit, + abort as abort, + access as access, + chdir as chdir, + chmod as chmod, + chown as chown, + chroot as chroot, + close as close, + closerange as closerange, + confstr as confstr, + confstr_names as confstr_names, + cpu_count as cpu_count, + ctermid as ctermid, + device_encoding as device_encoding, + dup as dup, + dup2 as dup2, + error as error, + execv as execv, + execve as execve, + fchdir as fchdir, + fchmod as fchmod, + fchown as fchown, + fork as fork, + forkpty as forkpty, + fpathconf as fpathconf, + fspath as fspath, + fstat as fstat, + fstatvfs as fstatvfs, + fsync as fsync, + ftruncate as ftruncate, + get_blocking as get_blocking, + get_inheritable as get_inheritable, + get_terminal_size as get_terminal_size, + getcwd as getcwd, + getcwdb as getcwdb, + getegid as getegid, + geteuid as geteuid, + getgid as getgid, + getgrouplist as getgrouplist, + getgroups as getgroups, + getloadavg as getloadavg, + getlogin as getlogin, + getpgid as getpgid, + getpgrp as getpgrp, + getpid as getpid, + getppid as getppid, + getpriority as getpriority, + getsid as getsid, + getuid as getuid, + initgroups as initgroups, + isatty as isatty, + kill as kill, + killpg as killpg, + lchown as lchown, + link as link, + listdir as listdir, + lockf as lockf, + lseek as lseek, + lstat as lstat, + major as major, + makedev as makedev, + minor as minor, + mkdir as mkdir, + mkfifo as mkfifo, + mknod as mknod, + nice as nice, + open as open, + openpty as openpty, + pathconf as pathconf, + pathconf_names as pathconf_names, + pipe as pipe, + pread as pread, + putenv as putenv, + pwrite as pwrite, + read as read, + readlink as readlink, + readv as readv, + remove as remove, + rename as rename, + replace as replace, + rmdir as rmdir, + scandir as scandir, + sched_get_priority_max as sched_get_priority_max, + sched_get_priority_min as sched_get_priority_min, + sched_param as sched_param, + sched_yield as sched_yield, + sendfile as sendfile, + set_blocking as set_blocking, + set_inheritable as set_inheritable, + setegid as setegid, + seteuid as seteuid, + setgid as setgid, + setgroups as setgroups, + setpgid as setpgid, + setpgrp as setpgrp, + setpriority as setpriority, + setregid as setregid, + setreuid as setreuid, + setsid as setsid, + setuid as setuid, + stat as stat, + stat_result as stat_result, + statvfs as statvfs, + statvfs_result as statvfs_result, + strerror as strerror, + symlink as symlink, + sync as sync, + sysconf as sysconf, + sysconf_names as sysconf_names, + system as system, + tcgetpgrp as tcgetpgrp, + tcsetpgrp as tcsetpgrp, + terminal_size as terminal_size, + times as times, + times_result as times_result, + truncate as truncate, + ttyname as ttyname, + umask as umask, + uname as uname, + uname_result as uname_result, + unlink as unlink, + unsetenv as unsetenv, + urandom as urandom, + utime as utime, + wait as wait, + wait3 as wait3, + wait4 as wait4, + waitpid as waitpid, + write as write, + writev as writev, + ) -@final -class times_result(NamedTuple): - user: float - system: float - children_user: float - children_system: float - elapsed: float + if sys.platform == "linux": + from os import ( + GRND_NONBLOCK as GRND_NONBLOCK, + GRND_RANDOM as GRND_RANDOM, + RTLD_DEEPBIND as RTLD_DEEPBIND, + XATTR_CREATE as XATTR_CREATE, + XATTR_REPLACE as XATTR_REPLACE, + XATTR_SIZE_MAX as XATTR_SIZE_MAX, + getrandom as getrandom, + getxattr as getxattr, + listxattr as listxattr, + removexattr as removexattr, + setxattr as setxattr, + ) + else: + from os import chflags as chflags, lchflags as lchflags, lchmod as lchmod -if sys.platform != "darwin": - class waitid_result(NamedTuple): - si_pid: int - si_uid: int - si_signo: int - si_status: int - si_code: int + if sys.platform != "darwin": + from os import ( + POSIX_FADV_DONTNEED as POSIX_FADV_DONTNEED, + POSIX_FADV_NOREUSE as POSIX_FADV_NOREUSE, + POSIX_FADV_NORMAL as POSIX_FADV_NORMAL, + POSIX_FADV_RANDOM as POSIX_FADV_RANDOM, + POSIX_FADV_SEQUENTIAL as POSIX_FADV_SEQUENTIAL, + POSIX_FADV_WILLNEED as POSIX_FADV_WILLNEED, + fdatasync as fdatasync, + getresgid as getresgid, + getresuid as getresuid, + pipe2 as pipe2, + posix_fadvise as posix_fadvise, + posix_fallocate as posix_fallocate, + sched_getaffinity as sched_getaffinity, + sched_getparam as sched_getparam, + sched_getscheduler as sched_getscheduler, + sched_rr_get_interval as sched_rr_get_interval, + sched_setaffinity as sched_setaffinity, + sched_setparam as sched_setparam, + sched_setscheduler as sched_setscheduler, + setresgid as setresgid, + setresuid as setresuid, + waitid as waitid, + waitid_result as waitid_result, + ) -class sched_param(NamedTuple): - sched_priority: int + if sys.version_info >= (3, 10): + from os import RWF_APPEND as RWF_APPEND -CLD_CONTINUED: int -CLD_DUMPED: int -CLD_EXITED: int -CLD_TRAPPED: int + if sys.version_info >= (3, 9): + from os import CLD_KILLED as CLD_KILLED, CLD_STOPPED as CLD_STOPPED, waitstatus_to_exitcode as waitstatus_to_exitcode -EX_CANTCREAT: int -EX_CONFIG: int -EX_DATAERR: int -EX_IOERR: int -EX_NOHOST: int -EX_NOINPUT: int -EX_NOPERM: int -EX_NOTFOUND: int -EX_NOUSER: int -EX_OK: int -EX_OSERR: int -EX_OSFILE: int -EX_PROTOCOL: int -EX_SOFTWARE: int -EX_TEMPFAIL: int -EX_UNAVAILABLE: int -EX_USAGE: int + if sys.platform == "linux": + from os import P_PIDFD as P_PIDFD + if sys.version_info >= (3, 8): + from os import ( + POSIX_SPAWN_CLOSE as POSIX_SPAWN_CLOSE, + POSIX_SPAWN_DUP2 as POSIX_SPAWN_DUP2, + POSIX_SPAWN_OPEN as POSIX_SPAWN_OPEN, + posix_spawn as posix_spawn, + posix_spawnp as posix_spawnp, + ) -F_OK: int -R_OK: int -W_OK: int -X_OK: int + if sys.platform == "linux": + from os import ( + MFD_ALLOW_SEALING as MFD_ALLOW_SEALING, + MFD_CLOEXEC as MFD_CLOEXEC, + MFD_HUGE_1GB as MFD_HUGE_1GB, + MFD_HUGE_1MB as MFD_HUGE_1MB, + MFD_HUGE_2GB as MFD_HUGE_2GB, + MFD_HUGE_2MB as MFD_HUGE_2MB, + MFD_HUGE_8MB as MFD_HUGE_8MB, + MFD_HUGE_16GB as MFD_HUGE_16GB, + MFD_HUGE_16MB as MFD_HUGE_16MB, + MFD_HUGE_32MB as MFD_HUGE_32MB, + MFD_HUGE_64KB as MFD_HUGE_64KB, + MFD_HUGE_256MB as MFD_HUGE_256MB, + MFD_HUGE_512KB as MFD_HUGE_512KB, + MFD_HUGE_512MB as MFD_HUGE_512MB, + MFD_HUGE_MASK as MFD_HUGE_MASK, + MFD_HUGE_SHIFT as MFD_HUGE_SHIFT, + MFD_HUGETLB as MFD_HUGETLB, + memfd_create as memfd_create, + ) + if sys.version_info >= (3, 7): + from os import register_at_fork as register_at_fork -F_LOCK: int -F_TEST: int -F_TLOCK: int -F_ULOCK: int + if sys.platform != "darwin": + from os import ( + RWF_DSYNC as RWF_DSYNC, + RWF_HIPRI as RWF_HIPRI, + RWF_NOWAIT as RWF_NOWAIT, + RWF_SYNC as RWF_SYNC, + preadv as preadv, + pwritev as pwritev, + ) -if sys.platform == "linux": - GRND_NONBLOCK: int - GRND_RANDOM: int -NGROUPS_MAX: int - -O_APPEND: int -O_ACCMODE: int -O_ASYNC: int -O_CREAT: int -O_DIRECT: int -O_DIRECTORY: int -O_DSYNC: int -O_EXCL: int -O_LARGEFILE: int -O_NDELAY: int -O_NOATIME: int -O_NOCTTY: int -O_NOFOLLOW: int -O_NONBLOCK: int -O_RDONLY: int -O_RDWR: int -O_RSYNC: int -O_SYNC: int -O_TRUNC: int -O_WRONLY: int - -if sys.platform != "darwin": - POSIX_FADV_DONTNEED: int - POSIX_FADV_NOREUSE: int - POSIX_FADV_NORMAL: int - POSIX_FADV_RANDOM: int - POSIX_FADV_SEQUENTIAL: int - POSIX_FADV_WILLNEED: int - -PRIO_PGRP: int -PRIO_PROCESS: int -PRIO_USER: int - -P_ALL: int -P_PGID: int -P_PID: int - -if sys.platform == "linux": - RTLD_DEEPBIND: int -RTLD_GLOBAL: int -RTLD_LAZY: int -RTLD_LOCAL: int -RTLD_NODELETE: int -RTLD_NOLOAD: int -RTLD_NOW: int - -SCHED_FIFO: int -SCHED_OTHER: int -SCHED_RR: int - -if sys.platform == "linux": - SCHED_BATCH: int - SCHED_IDLE: int -if sys.platform != "darwin": - SCHED_RESET_ON_FORK: int - -SEEK_DATA: int -SEEK_HOLE: int - -ST_APPEND: int -ST_MANDLOCK: int -ST_NOATIME: int -ST_NODEV: int -ST_NODIRATIME: int -ST_NOEXEC: int -ST_NOSUID: int -ST_RDONLY: int -ST_RELATIME: int -ST_SYNCHRONOUS: int -ST_WRITE: int - -TMP_MAX: int -WCONTINUED: int - -def WCOREDUMP(__status: int) -> bool: ... -def WEXITSTATUS(status: int) -> int: ... -def WIFCONTINUED(status: int) -> bool: ... -def WIFEXITED(status: int) -> bool: ... -def WIFSIGNALED(status: int) -> bool: ... -def WIFSTOPPED(status: int) -> bool: ... - -WNOHANG: int - -def WSTOPSIG(status: int) -> int: ... -def WTERMSIG(status: int) -> int: ... - -WUNTRACED: int - -XATTR_CREATE: int -XATTR_REPLACE: int -XATTR_SIZE_MAX: int - -@overload -def listdir(path: str | None = ...) -> list[str]: ... -@overload -def listdir(path: bytes) -> list[bytes]: ... -@overload -def listdir(path: int) -> list[str]: ... -@overload -def listdir(path: PathLike[str]) -> list[str]: ... - -if sys.platform != "win32" and sys.version_info >= (3, 8): - def posix_spawn( - path: StrOrBytesPath, - argv: _ExecVArgs, - env: _ExecEnv, - *, - file_actions: Sequence[Tuple[Any, ...]] | None = ..., - setpgroup: int | None = ..., - resetids: bool = ..., - setsid: bool = ..., - setsigmask: Iterable[int] = ..., - setsigdef: Iterable[int] = ..., - scheduler: tuple[Any, sched_param] | None = ..., - ) -> int: ... - def posix_spawnp( - path: StrOrBytesPath, - argv: _ExecVArgs, - env: _ExecEnv, - *, - file_actions: Sequence[Tuple[Any, ...]] | None = ..., - setpgroup: int | None = ..., - resetids: bool = ..., - setsid: bool = ..., - setsigmask: Iterable[int] = ..., - setsigdef: Iterable[int] = ..., - scheduler: tuple[Any, sched_param] | None = ..., - ) -> int: ... - -if sys.platform == "win32": - environ: dict[str, str] -else: + # Not same as os.environ or os.environb + # Because of this variable, we can't do "from posix import *" in os/__init__.pyi environ: dict[bytes, bytes] diff --git a/mypy/typeshed/stdlib/posixpath.pyi b/mypy/typeshed/stdlib/posixpath.pyi index ae3d0d5cc65f..58cadb4de03c 100644 --- a/mypy/typeshed/stdlib/posixpath.pyi +++ b/mypy/typeshed/stdlib/posixpath.pyi @@ -60,10 +60,14 @@ def normpath(path: AnyStr) -> AnyStr: ... def commonpath(paths: Sequence[StrPath]) -> str: ... @overload def commonpath(paths: Sequence[BytesPath]) -> bytes: ... + +# First parameter is not actually pos-only, +# but must be defined as pos-only in the stub or cross-platform code doesn't type-check, +# as the parameter name is different in ntpath.join() @overload -def join(a: StrPath, *paths: StrPath) -> str: ... +def join(__a: StrPath, *paths: StrPath) -> str: ... @overload -def join(a: BytesPath, *paths: BytesPath) -> bytes: ... +def join(__a: BytesPath, *paths: BytesPath) -> bytes: ... if sys.version_info >= (3, 10): @overload diff --git a/mypy/typeshed/stdlib/profile.pyi b/mypy/typeshed/stdlib/profile.pyi index cb0cbf7c9388..007a1a11da12 100644 --- a/mypy/typeshed/stdlib/profile.pyi +++ b/mypy/typeshed/stdlib/profile.pyi @@ -1,14 +1,13 @@ -from _typeshed import StrOrBytesPath -from typing import Any, Callable, Tuple, TypeVar +from _typeshed import Self, StrOrBytesPath +from typing import Any, Callable, TypeVar def run(statement: str, filename: str | None = ..., sort: str | int = ...) -> None: ... def runctx( statement: str, globals: dict[str, Any], locals: dict[str, Any], filename: str | None = ..., sort: str | int = ... ) -> None: ... -_SelfT = TypeVar("_SelfT", bound=Profile) _T = TypeVar("_T") -_Label = Tuple[str, int, str] +_Label = tuple[str, int, str] class Profile: bias: int @@ -21,7 +20,7 @@ class Profile: def dump_stats(self, file: StrOrBytesPath) -> None: ... def create_stats(self) -> None: ... def snapshot_stats(self) -> None: ... - def run(self: _SelfT, cmd: str) -> _SelfT: ... - def runctx(self: _SelfT, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> _SelfT: ... + def run(self: Self, cmd: str) -> Self: ... + def runctx(self: Self, cmd: str, globals: dict[str, Any], locals: dict[str, Any]) -> Self: ... def runcall(self, __func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... def calibrate(self, m: int, verbose: int = ...) -> float: ... diff --git a/mypy/typeshed/stdlib/pstats.pyi b/mypy/typeshed/stdlib/pstats.pyi index e8256f9f98ab..1328308467f0 100644 --- a/mypy/typeshed/stdlib/pstats.pyi +++ b/mypy/typeshed/stdlib/pstats.pyi @@ -1,11 +1,10 @@ import sys -from _typeshed import StrOrBytesPath +from _typeshed import Self, StrOrBytesPath from cProfile import Profile as _cProfile from profile import Profile -from typing import IO, Any, Iterable, Tuple, TypeVar, Union, overload +from typing import IO, Any, Iterable, Union, overload _Selector = Union[str, float, int] -_T = TypeVar("_T", bound=Stats) if sys.version_info >= (3, 7): from enum import Enum @@ -23,29 +22,29 @@ if sys.version_info >= (3, 7): class Stats: sort_arg_dict_default: dict[str, tuple[Any, str]] def __init__( - self: _T, + self: Self, __arg: None | str | Profile | _cProfile = ..., - *args: None | str | Profile | _cProfile | _T, + *args: None | str | Profile | _cProfile | Self, stream: IO[Any] | None = ..., ) -> None: ... def init(self, arg: None | str | Profile | _cProfile) -> None: ... def load_stats(self, arg: None | str | Profile | _cProfile) -> None: ... def get_top_level_stats(self) -> None: ... - def add(self: _T, *arg_list: None | str | Profile | _cProfile | _T) -> _T: ... + def add(self: Self, *arg_list: None | str | Profile | _cProfile | Self) -> Self: ... def dump_stats(self, filename: StrOrBytesPath) -> None: ... - def get_sort_arg_defs(self) -> dict[str, tuple[Tuple[tuple[int, int], ...], str]]: ... + def get_sort_arg_defs(self) -> dict[str, tuple[tuple[tuple[int, int], ...], str]]: ... @overload - def sort_stats(self: _T, field: int) -> _T: ... + def sort_stats(self: Self, field: int) -> Self: ... @overload - def sort_stats(self: _T, *field: str) -> _T: ... - def reverse_order(self: _T) -> _T: ... - def strip_dirs(self: _T) -> _T: ... + def sort_stats(self: Self, *field: str) -> Self: ... + def reverse_order(self: Self) -> Self: ... + def strip_dirs(self: Self) -> Self: ... def calc_callees(self) -> None: ... def eval_print_amount(self, sel: _Selector, list: list[str], msg: str) -> tuple[list[str], str]: ... def get_print_list(self, sel_list: Iterable[_Selector]) -> tuple[int, list[str]]: ... - def print_stats(self: _T, *amount: _Selector) -> _T: ... - def print_callees(self: _T, *amount: _Selector) -> _T: ... - def print_callers(self: _T, *amount: _Selector) -> _T: ... + def print_stats(self: Self, *amount: _Selector) -> Self: ... + def print_callees(self: Self, *amount: _Selector) -> Self: ... + def print_callers(self: Self, *amount: _Selector) -> Self: ... def print_call_heading(self, name_size: int, column_title: str) -> None: ... def print_call_line(self, name_size: int, source: str, call_dict: dict[str, Any], arrow: str = ...) -> None: ... def print_title(self) -> None: ... diff --git a/mypy/typeshed/stdlib/pty.pyi b/mypy/typeshed/stdlib/pty.pyi index f943cebdb157..73c6ddfbd0c4 100644 --- a/mypy/typeshed/stdlib/pty.pyi +++ b/mypy/typeshed/stdlib/pty.pyi @@ -1,15 +1,18 @@ +import sys from typing import Callable, Iterable +from typing_extensions import Literal -_Reader = Callable[[int], bytes] +if sys.platform != "win32": + __all__ = ["openpty", "fork", "spawn"] + _Reader = Callable[[int], bytes] -STDIN_FILENO: int -STDOUT_FILENO: int -STDERR_FILENO: int + STDIN_FILENO: Literal[0] + STDOUT_FILENO: Literal[1] + STDERR_FILENO: Literal[2] -CHILD: int - -def openpty() -> tuple[int, int]: ... -def master_open() -> tuple[int, str]: ... -def slave_open(tty_name: str) -> int: ... -def fork() -> tuple[int, int]: ... -def spawn(argv: str | Iterable[str], master_read: _Reader = ..., stdin_read: _Reader = ...) -> int: ... + CHILD: Literal[0] + def openpty() -> tuple[int, int]: ... + def master_open() -> tuple[int, str]: ... # deprecated, use openpty() + def slave_open(tty_name: str) -> int: ... # deprecated, use openpty() + def fork() -> tuple[int, int]: ... + def spawn(argv: str | Iterable[str], master_read: _Reader = ..., stdin_read: _Reader = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/pwd.pyi b/mypy/typeshed/stdlib/pwd.pyi index 2b931248edda..08a9facf642e 100644 --- a/mypy/typeshed/stdlib/pwd.pyi +++ b/mypy/typeshed/stdlib/pwd.pyi @@ -1,18 +1,25 @@ -from typing import ClassVar, Tuple +import sys +from _typeshed import structseq +from typing import Any +from typing_extensions import final -class struct_passwd(Tuple[str, str, int, int, str, str, str]): - pw_name: str - pw_passwd: str - pw_uid: int - pw_gid: int - pw_gecos: str - pw_dir: str - pw_shell: str - - n_fields: ClassVar[int] - n_sequence_fields: ClassVar[int] - n_unnamed_fields: ClassVar[int] - -def getpwall() -> list[struct_passwd]: ... -def getpwuid(__uid: int) -> struct_passwd: ... -def getpwnam(__name: str) -> struct_passwd: ... +if sys.platform != "win32": + @final + class struct_passwd(structseq[Any], tuple[str, str, int, int, str, str, str]): + @property + def pw_name(self) -> str: ... + @property + def pw_passwd(self) -> str: ... + @property + def pw_uid(self) -> int: ... + @property + def pw_gid(self) -> int: ... + @property + def pw_gecos(self) -> str: ... + @property + def pw_dir(self) -> str: ... + @property + def pw_shell(self) -> str: ... + def getpwall() -> list[struct_passwd]: ... + def getpwuid(__uid: int) -> struct_passwd: ... + def getpwnam(__name: str) -> struct_passwd: ... diff --git a/mypy/typeshed/stdlib/py_compile.pyi b/mypy/typeshed/stdlib/py_compile.pyi index 1df818509d0e..2c967c221407 100644 --- a/mypy/typeshed/stdlib/py_compile.pyi +++ b/mypy/typeshed/stdlib/py_compile.pyi @@ -1,12 +1,12 @@ import sys -from typing import AnyStr, Type +from typing import AnyStr class PyCompileError(Exception): exc_type_name: str exc_value: BaseException file: str msg: str - def __init__(self, exc_type: Type[BaseException], exc_value: BaseException, file: str, msg: str = ...) -> None: ... + def __init__(self, exc_type: type[BaseException], exc_value: BaseException, file: str, msg: str = ...) -> None: ... if sys.version_info >= (3, 7): import enum diff --git a/mypy/typeshed/stdlib/pydoc.pyi b/mypy/typeshed/stdlib/pydoc.pyi index 97e71f389616..cc656f9b7559 100644 --- a/mypy/typeshed/stdlib/pydoc.pyi +++ b/mypy/typeshed/stdlib/pydoc.pyi @@ -1,10 +1,10 @@ from _typeshed import SupportsWrite from reprlib import Repr from types import MethodType, ModuleType, TracebackType -from typing import IO, Any, AnyStr, Callable, Container, Mapping, MutableMapping, NoReturn, Optional, Tuple, Type +from typing import IO, Any, AnyStr, Callable, Container, Mapping, MutableMapping, NoReturn, Optional # the return type of sys.exc_info(), used by ErrorDuringImport.__init__ -_Exc_Info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_Exc_Info = tuple[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]] __author__: str __date__: str @@ -28,7 +28,7 @@ def synopsis(filename: str, cache: MutableMapping[str, tuple[int, str]] = ...) - class ErrorDuringImport(Exception): filename: str - exc: Type[BaseException] | None + exc: type[BaseException] | None value: BaseException | None tb: TracebackType | None def __init__(self, filename: str, exc_info: _Exc_Info) -> None: ... @@ -96,7 +96,7 @@ class HTMLDoc(Doc): methods: Mapping[str, str] = ..., ) -> str: ... def formattree( - self, tree: list[tuple[type, Tuple[type, ...]] | list[Any]], modname: str, parent: type | None = ... + self, tree: list[tuple[type, tuple[type, ...]] | list[Any]], modname: str, parent: type | None = ... ) -> str: ... def docmodule(self, object: object, name: str | None = ..., mod: str | None = ..., *ignored: Any) -> str: ... def docclass( @@ -109,7 +109,7 @@ class HTMLDoc(Doc): *ignored: Any, ) -> str: ... def formatvalue(self, object: object) -> str: ... - def docroutine( + def docroutine( # type: ignore[override] self, object: object, name: str | None = ..., @@ -118,15 +118,10 @@ class HTMLDoc(Doc): classes: Mapping[str, str] = ..., methods: Mapping[str, str] = ..., cl: type | None = ..., - *ignored: Any, - ) -> str: ... - def docproperty( - self, object: object, name: str | None = ..., mod: str | None = ..., cl: Any | None = ..., *ignored: Any ) -> str: ... + def docproperty(self, object: object, name: str | None = ..., mod: str | None = ..., cl: Any | None = ...) -> str: ... # type: ignore[override] def docother(self, object: object, name: str | None = ..., mod: Any | None = ..., *ignored: Any) -> str: ... - def docdata( - self, object: object, name: str | None = ..., mod: Any | None = ..., cl: Any | None = ..., *ignored: Any - ) -> str: ... + def docdata(self, object: object, name: str | None = ..., mod: Any | None = ..., cl: Any | None = ...) -> str: ... # type: ignore[override] def index(self, dir: str, shadowed: MutableMapping[str, bool] | None = ...) -> str: ... def filelink(self, url: str, path: str) -> str: ... @@ -148,21 +143,15 @@ class TextDoc(Doc): def indent(self, text: str, prefix: str = ...) -> str: ... def section(self, title: str, contents: str) -> str: ... def formattree( - self, tree: list[tuple[type, Tuple[type, ...]] | list[Any]], modname: str, parent: type | None = ..., prefix: str = ... + self, tree: list[tuple[type, tuple[type, ...]] | list[Any]], modname: str, parent: type | None = ..., prefix: str = ... ) -> str: ... - def docmodule(self, object: object, name: str | None = ..., mod: Any | None = ..., *ignored: Any) -> str: ... + def docmodule(self, object: object, name: str | None = ..., mod: Any | None = ...) -> str: ... # type: ignore[override] def docclass(self, object: object, name: str | None = ..., mod: str | None = ..., *ignored: Any) -> str: ... def formatvalue(self, object: object) -> str: ... - def docroutine( - self, object: object, name: str | None = ..., mod: str | None = ..., cl: Any | None = ..., *ignored: Any - ) -> str: ... - def docproperty( - self, object: object, name: str | None = ..., mod: Any | None = ..., cl: Any | None = ..., *ignored: Any - ) -> str: ... - def docdata( - self, object: object, name: str | None = ..., mod: str | None = ..., cl: Any | None = ..., *ignored: Any - ) -> str: ... - def docother( + def docroutine(self, object: object, name: str | None = ..., mod: str | None = ..., cl: Any | None = ...) -> str: ... # type: ignore[override] + def docproperty(self, object: object, name: str | None = ..., mod: Any | None = ..., cl: Any | None = ...) -> str: ... # type: ignore[override] + def docdata(self, object: object, name: str | None = ..., mod: str | None = ..., cl: Any | None = ...) -> str: ... # type: ignore[override] + def docother( # type: ignore[override] self, object: object, name: str | None = ..., @@ -170,7 +159,6 @@ class TextDoc(Doc): parent: str | None = ..., maxlen: int | None = ..., doc: Any | None = ..., - *ignored: Any, ) -> str: ... def pager(text: str) -> None: ... @@ -199,7 +187,7 @@ _list = list # "list" conflicts with method name class Helper: keywords: dict[str, str | tuple[str, str]] symbols: dict[str, str] - topics: dict[str, str | Tuple[str, ...]] + topics: dict[str, str | tuple[str, ...]] def __init__(self, input: IO[str] | None = ..., output: IO[str] | None = ...) -> None: ... input: IO[str] output: IO[str] diff --git a/mypy/typeshed/stdlib/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/pyexpat/__init__.pyi index 6a3d6cd56791..5aca55c2b813 100644 --- a/mypy/typeshed/stdlib/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/pyexpat/__init__.pyi @@ -1,7 +1,7 @@ import pyexpat.errors as errors import pyexpat.model as model from _typeshed import SupportsRead -from typing import Any, Callable, Optional, Tuple +from typing import Any, Callable, Optional from typing_extensions import final EXPAT_VERSION: str # undocumented @@ -20,10 +20,10 @@ XML_PARAM_ENTITY_PARSING_NEVER: int XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE: int XML_PARAM_ENTITY_PARSING_ALWAYS: int -_Model = Tuple[int, int, Optional[str], Tuple[Any, ...]] +_Model = tuple[int, int, Optional[str], tuple[Any, ...]] @final -class XMLParserType(object): +class XMLParserType: def Parse(self, __data: str | bytes, __isfinal: bool = ...) -> int: ... def ParseFile(self, __file: SupportsRead[bytes]) -> int: ... def SetBase(self, __base: str) -> None: ... diff --git a/mypy/typeshed/stdlib/random.pyi b/mypy/typeshed/stdlib/random.pyi index 73c29d2f78c3..362374f9b85c 100644 --- a/mypy/typeshed/stdlib/random.pyi +++ b/mypy/typeshed/stdlib/random.pyi @@ -1,25 +1,31 @@ import _random import sys +from _typeshed import SupportsLenAndGetItem from collections.abc import Callable, Iterable, MutableSequence, Sequence, Set as AbstractSet from fractions import Fraction -from typing import Any, NoReturn, Tuple, TypeVar +from typing import Any, ClassVar, NoReturn, TypeVar _T = TypeVar("_T") class Random(_random.Random): + VERSION: ClassVar[int] def __init__(self, x: Any = ...) -> None: ... - def seed(self, a: Any = ..., version: int = ...) -> None: ... - def getstate(self) -> Tuple[Any, ...]: ... - def setstate(self, state: Tuple[Any, ...]) -> None: ... + # Using other `seed` types is deprecated since 3.9 and removed in 3.11 + if sys.version_info >= (3, 9): + def seed(self, a: int | float | str | bytes | bytearray | None = ..., version: int = ...) -> None: ... # type: ignore[override] + else: + def seed(self, a: Any = ..., version: int = ...) -> None: ... + def getstate(self) -> tuple[Any, ...]: ... + def setstate(self, state: tuple[Any, ...]) -> None: ... def getrandbits(self, __k: int) -> int: ... def randrange(self, start: int, stop: int | None = ..., step: int = ...) -> int: ... def randint(self, a: int, b: int) -> int: ... if sys.version_info >= (3, 9): def randbytes(self, n: int) -> bytes: ... - def choice(self, seq: Sequence[_T]) -> _T: ... + def choice(self, seq: SupportsLenAndGetItem[_T]) -> _T: ... def choices( self, - population: Sequence[_T], + population: SupportsLenAndGetItem[_T], weights: Sequence[float | Fraction] | None = ..., *, cum_weights: Sequence[float | Fraction] | None = ..., @@ -27,7 +33,9 @@ class Random(_random.Random): ) -> list[_T]: ... def shuffle(self, x: MutableSequence[Any], random: Callable[[], float] | None = ...) -> None: ... if sys.version_info >= (3, 9): - def sample(self, population: Sequence[_T] | AbstractSet[_T], k: int, *, counts: Iterable[_T] | None = ...) -> list[_T]: ... + def sample( + self, population: Sequence[_T] | AbstractSet[_T], k: int, *, counts: Iterable[_T] | None = ... + ) -> list[_T]: ... else: def sample(self, population: Sequence[_T] | AbstractSet[_T], k: int) -> list[_T]: ... def random(self) -> float: ... @@ -45,11 +53,17 @@ class Random(_random.Random): # SystemRandom is not implemented for all OS's; good on Windows & Linux class SystemRandom(Random): + def getrandbits(self, k: int) -> int: ... # k can be passed by keyword def getstate(self, *args: Any, **kwds: Any) -> NoReturn: ... def setstate(self, *args: Any, **kwds: Any) -> NoReturn: ... # ----- random function stubs ----- -def seed(a: Any = ..., version: int = ...) -> None: ... +if sys.version_info >= (3, 9): + def seed(a: int | float | str | bytes | bytearray | None = ..., version: int = ...) -> None: ... + +else: + def seed(a: Any = ..., version: int = ...) -> None: ... + def getstate() -> object: ... def setstate(state: object) -> None: ... def getrandbits(__k: int) -> int: ... @@ -59,9 +73,13 @@ def randint(a: int, b: int) -> int: ... if sys.version_info >= (3, 9): def randbytes(n: int) -> bytes: ... -def choice(seq: Sequence[_T]) -> _T: ... +def choice(seq: SupportsLenAndGetItem[_T]) -> _T: ... def choices( - population: Sequence[_T], weights: Sequence[float] | None = ..., *, cum_weights: Sequence[float] | None = ..., k: int = ... + population: SupportsLenAndGetItem[_T], + weights: Sequence[float] | None = ..., + *, + cum_weights: Sequence[float] | None = ..., + k: int = ..., ) -> list[_T]: ... def shuffle(x: MutableSequence[Any], random: Callable[[], float] | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/readline.pyi b/mypy/typeshed/stdlib/readline.pyi index 2de749b2c216..fd3a4b1dcc65 100644 --- a/mypy/typeshed/stdlib/readline.pyi +++ b/mypy/typeshed/stdlib/readline.pyi @@ -1,33 +1,34 @@ +import sys from _typeshed import StrOrBytesPath from typing import Callable, Optional, Sequence -_CompleterT = Optional[Callable[[str, int], Optional[str]]] -_CompDispT = Optional[Callable[[str, Sequence[str], int], None]] - -def parse_and_bind(__string: str) -> None: ... -def read_init_file(__filename: StrOrBytesPath | None = ...) -> None: ... -def get_line_buffer() -> str: ... -def insert_text(__string: str) -> None: ... -def redisplay() -> None: ... -def read_history_file(__filename: StrOrBytesPath | None = ...) -> None: ... -def write_history_file(__filename: StrOrBytesPath | None = ...) -> None: ... -def append_history_file(__nelements: int, __filename: StrOrBytesPath | None = ...) -> None: ... -def get_history_length() -> int: ... -def set_history_length(__length: int) -> None: ... -def clear_history() -> None: ... -def get_current_history_length() -> int: ... -def get_history_item(__index: int) -> str: ... -def remove_history_item(__pos: int) -> None: ... -def replace_history_item(__pos: int, __line: str) -> None: ... -def add_history(__string: str) -> None: ... -def set_auto_history(__enabled: bool) -> None: ... -def set_startup_hook(__function: Callable[[], None] | None = ...) -> None: ... -def set_pre_input_hook(__function: Callable[[], None] | None = ...) -> None: ... -def set_completer(__function: _CompleterT = ...) -> None: ... -def get_completer() -> _CompleterT: ... -def get_completion_type() -> int: ... -def get_begidx() -> int: ... -def get_endidx() -> int: ... -def set_completer_delims(__string: str) -> None: ... -def get_completer_delims() -> str: ... -def set_completion_display_matches_hook(__function: _CompDispT = ...) -> None: ... +if sys.platform != "win32": + _CompleterT = Optional[Callable[[str, int], Optional[str]]] + _CompDispT = Optional[Callable[[str, Sequence[str], int], None]] + def parse_and_bind(__string: str) -> None: ... + def read_init_file(__filename: StrOrBytesPath | None = ...) -> None: ... + def get_line_buffer() -> str: ... + def insert_text(__string: str) -> None: ... + def redisplay() -> None: ... + def read_history_file(__filename: StrOrBytesPath | None = ...) -> None: ... + def write_history_file(__filename: StrOrBytesPath | None = ...) -> None: ... + def append_history_file(__nelements: int, __filename: StrOrBytesPath | None = ...) -> None: ... + def get_history_length() -> int: ... + def set_history_length(__length: int) -> None: ... + def clear_history() -> None: ... + def get_current_history_length() -> int: ... + def get_history_item(__index: int) -> str: ... + def remove_history_item(__pos: int) -> None: ... + def replace_history_item(__pos: int, __line: str) -> None: ... + def add_history(__string: str) -> None: ... + def set_auto_history(__enabled: bool) -> None: ... + def set_startup_hook(__function: Callable[[], None] | None = ...) -> None: ... + def set_pre_input_hook(__function: Callable[[], None] | None = ...) -> None: ... + def set_completer(__function: _CompleterT = ...) -> None: ... + def get_completer() -> _CompleterT: ... + def get_completion_type() -> int: ... + def get_begidx() -> int: ... + def get_endidx() -> int: ... + def set_completer_delims(__string: str) -> None: ... + def get_completer_delims() -> str: ... + def set_completion_display_matches_hook(__function: _CompDispT = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/reprlib.pyi b/mypy/typeshed/stdlib/reprlib.pyi index 4d400554a4ff..2095c0af6983 100644 --- a/mypy/typeshed/stdlib/reprlib.pyi +++ b/mypy/typeshed/stdlib/reprlib.pyi @@ -1,6 +1,6 @@ from array import array from collections import deque -from typing import Any, Callable, Tuple +from typing import Any, Callable _ReprFunc = Callable[[Any], str] @@ -21,7 +21,7 @@ class Repr: def __init__(self) -> None: ... def repr(self, x: Any) -> str: ... def repr1(self, x: Any, level: int) -> str: ... - def repr_tuple(self, x: Tuple[Any, ...], level: int) -> str: ... + def repr_tuple(self, x: tuple[Any, ...], level: int) -> str: ... def repr_list(self, x: list[Any], level: int) -> str: ... def repr_array(self, x: array[Any], level: int) -> str: ... def repr_set(self, x: set[Any], level: int) -> str: ... diff --git a/mypy/typeshed/stdlib/resource.pyi b/mypy/typeshed/stdlib/resource.pyi index d7124edcc2fa..19a6f470b775 100644 --- a/mypy/typeshed/stdlib/resource.pyi +++ b/mypy/typeshed/stdlib/resource.pyi @@ -1,58 +1,73 @@ import sys -from typing import Any, Tuple, overload +from _typeshed import structseq +from typing import overload +from typing_extensions import final -RLIMIT_AS: int -RLIMIT_CORE: int -RLIMIT_CPU: int -RLIMIT_DATA: int -RLIMIT_FSIZE: int -RLIMIT_MEMLOCK: int -RLIMIT_NOFILE: int -RLIMIT_NPROC: int -RLIMIT_RSS: int -RLIMIT_STACK: int -RLIM_INFINITY: int -RUSAGE_CHILDREN: int -RUSAGE_SELF: int -if sys.platform == "linux": - RLIMIT_MSGQUEUE: int - RLIMIT_NICE: int - RLIMIT_OFILE: int - RLIMIT_RTPRIO: int - RLIMIT_RTTIME: int - RLIMIT_SIGPENDING: int - RUSAGE_THREAD: int - -_Tuple16 = Tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] - -class struct_rusage(_Tuple16): - def __new__(cls, sequence: _Tuple16, dict: dict[str, Any] = ...) -> struct_rusage: ... - ru_utime: float - ru_stime: float - ru_maxrss: int - ru_ixrss: int - ru_idrss: int - ru_isrss: int - ru_minflt: int - ru_majflt: int - ru_nswap: int - ru_inblock: int - ru_oublock: int - ru_msgsnd: int - ru_msgrcv: int - ru_nsignals: int - ru_nvcsw: int - ru_nivcsw: int - -def getpagesize() -> int: ... -def getrlimit(__resource: int) -> tuple[int, int]: ... -def getrusage(__who: int) -> struct_rusage: ... -def setrlimit(__resource: int, __limits: tuple[int, int]) -> None: ... - -if sys.platform == "linux": - @overload - def prlimit(pid: int, resource: int, limits: tuple[int, int]) -> tuple[int, int]: ... - @overload - def prlimit(pid: int, resource: int) -> tuple[int, int]: ... - -error = OSError +if sys.platform != "win32": + RLIMIT_AS: int + RLIMIT_CORE: int + RLIMIT_CPU: int + RLIMIT_DATA: int + RLIMIT_FSIZE: int + RLIMIT_MEMLOCK: int + RLIMIT_NOFILE: int + RLIMIT_NPROC: int + RLIMIT_RSS: int + RLIMIT_STACK: int + RLIM_INFINITY: int + RUSAGE_CHILDREN: int + RUSAGE_SELF: int + if sys.platform == "linux": + RLIMIT_MSGQUEUE: int + RLIMIT_NICE: int + RLIMIT_OFILE: int + RLIMIT_RTPRIO: int + RLIMIT_RTTIME: int + RLIMIT_SIGPENDING: int + RUSAGE_THREAD: int + @final + class struct_rusage( + structseq[float], tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int] + ): + @property + def ru_utime(self) -> float: ... + @property + def ru_stime(self) -> float: ... + @property + def ru_maxrss(self) -> int: ... + @property + def ru_ixrss(self) -> int: ... + @property + def ru_idrss(self) -> int: ... + @property + def ru_isrss(self) -> int: ... + @property + def ru_minflt(self) -> int: ... + @property + def ru_majflt(self) -> int: ... + @property + def ru_nswap(self) -> int: ... + @property + def ru_inblock(self) -> int: ... + @property + def ru_oublock(self) -> int: ... + @property + def ru_msgsnd(self) -> int: ... + @property + def ru_msgrcv(self) -> int: ... + @property + def ru_nsignals(self) -> int: ... + @property + def ru_nvcsw(self) -> int: ... + @property + def ru_nivcsw(self) -> int: ... + def getpagesize() -> int: ... + def getrlimit(__resource: int) -> tuple[int, int]: ... + def getrusage(__who: int) -> struct_rusage: ... + def setrlimit(__resource: int, __limits: tuple[int, int]) -> None: ... + if sys.platform == "linux": + @overload + def prlimit(pid: int, resource: int, limits: tuple[int, int]) -> tuple[int, int]: ... + @overload + def prlimit(pid: int, resource: int) -> tuple[int, int]: ... + error = OSError diff --git a/mypy/typeshed/stdlib/sched.pyi b/mypy/typeshed/stdlib/sched.pyi index cb96dc2bbf4a..71aacc5c2610 100644 --- a/mypy/typeshed/stdlib/sched.pyi +++ b/mypy/typeshed/stdlib/sched.pyi @@ -1,10 +1,10 @@ -from typing import Any, Callable, NamedTuple, Tuple +from typing import Any, Callable, NamedTuple class Event(NamedTuple): time: float priority: Any action: Callable[..., Any] - argument: Tuple[Any, ...] + argument: tuple[Any, ...] kwargs: dict[str, Any] class scheduler: @@ -14,7 +14,7 @@ class scheduler: time: float, priority: Any, action: Callable[..., Any], - argument: Tuple[Any, ...] = ..., + argument: tuple[Any, ...] = ..., kwargs: dict[str, Any] = ..., ) -> Event: ... def enter( @@ -22,7 +22,7 @@ class scheduler: delay: float, priority: Any, action: Callable[..., Any], - argument: Tuple[Any, ...] = ..., + argument: tuple[Any, ...] = ..., kwargs: dict[str, Any] = ..., ) -> Event: ... def run(self, blocking: bool = ...) -> float | None: ... diff --git a/mypy/typeshed/stdlib/secrets.pyi b/mypy/typeshed/stdlib/secrets.pyi index 6752a30f431e..f57eef8492d7 100644 --- a/mypy/typeshed/stdlib/secrets.pyi +++ b/mypy/typeshed/stdlib/secrets.pyi @@ -1,12 +1,13 @@ +from _typeshed import SupportsLenAndGetItem from hmac import compare_digest as compare_digest from random import SystemRandom as SystemRandom -from typing import Sequence, TypeVar +from typing import TypeVar _T = TypeVar("_T") def randbelow(exclusive_upper_bound: int) -> int: ... def randbits(k: int) -> int: ... -def choice(seq: Sequence[_T]) -> _T: ... +def choice(seq: SupportsLenAndGetItem[_T]) -> _T: ... def token_bytes(nbytes: int | None = ...) -> bytes: ... def token_hex(nbytes: int | None = ...) -> str: ... def token_urlsafe(nbytes: int | None = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/select.pyi b/mypy/typeshed/stdlib/select.pyi index 0329dbaa2c11..3e5aec69fac1 100644 --- a/mypy/typeshed/stdlib/select.pyi +++ b/mypy/typeshed/stdlib/select.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import FileDescriptorLike, Self from types import TracebackType -from typing import Any, Iterable, Type +from typing import Any, Iterable if sys.platform != "win32": PIPE_BUF: int @@ -13,6 +13,7 @@ if sys.platform != "win32": POLLOUT: int POLLPRI: int POLLRDBAND: int + POLLRDHUP: int POLLRDNORM: int POLLWRBAND: int POLLWRNORM: int @@ -32,7 +33,7 @@ error = OSError if sys.platform != "linux" and sys.platform != "win32": # BSD only - class kevent(object): + class kevent: data: Any fflags: int filter: int @@ -49,7 +50,7 @@ if sys.platform != "linux" and sys.platform != "win32": udata: Any = ..., ) -> None: ... # BSD only - class kqueue(object): + class kqueue: closed: bool def __init__(self) -> None: ... def close(self) -> None: ... @@ -99,12 +100,12 @@ if sys.platform != "linux" and sys.platform != "win32": KQ_NOTE_WRITE: int if sys.platform == "linux": - class epoll(object): + class epoll: def __init__(self, sizehint: int = ..., flags: int = ...) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( self, - exc_type: Type[BaseException] | None = ..., + exc_type: type[BaseException] | None = ..., exc_val: BaseException | None = ..., exc_tb: TracebackType | None = ..., ) -> None: ... @@ -118,6 +119,7 @@ if sys.platform == "linux": @classmethod def fromfd(cls, __fd: FileDescriptorLike) -> epoll: ... EPOLLERR: int + EPOLLEXCLUSIVE: int EPOLLET: int EPOLLHUP: int EPOLLIN: int @@ -126,10 +128,12 @@ if sys.platform == "linux": EPOLLOUT: int EPOLLPRI: int EPOLLRDBAND: int + EPOLLRDHUP: int EPOLLRDNORM: int EPOLLWRBAND: int EPOLLWRNORM: int EPOLL_RDHUP: int + EPOLL_CLOEXEC: int if sys.platform != "linux" and sys.platform != "darwin" and sys.platform != "win32": # Solaris only diff --git a/mypy/typeshed/stdlib/shelve.pyi b/mypy/typeshed/stdlib/shelve.pyi index 90b2aafa4f03..10f82b6a2eb3 100644 --- a/mypy/typeshed/stdlib/shelve.pyi +++ b/mypy/typeshed/stdlib/shelve.pyi @@ -1,7 +1,7 @@ from _typeshed import Self from collections.abc import Iterator, MutableMapping from types import TracebackType -from typing import Type, TypeVar, overload +from typing import TypeVar, overload _T = TypeVar("_T") _VT = TypeVar("_VT") @@ -21,7 +21,7 @@ class Shelf(MutableMapping[str, _VT]): def __delitem__(self, key: str) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... def close(self) -> None: ... def sync(self) -> None: ... diff --git a/mypy/typeshed/stdlib/shlex.pyi b/mypy/typeshed/stdlib/shlex.pyi index dfe554b0a773..a979ac07793d 100644 --- a/mypy/typeshed/stdlib/shlex.pyi +++ b/mypy/typeshed/stdlib/shlex.pyi @@ -1,5 +1,6 @@ import sys -from typing import Any, Iterable, TextIO, TypeVar +from _typeshed import Self +from typing import Any, Iterable, TextIO def split(s: str, comments: bool = ..., posix: bool = ...) -> list[str]: ... @@ -8,8 +9,6 @@ if sys.version_info >= (3, 8): def quote(s: str) -> str: ... -_SLT = TypeVar("_SLT", bound=shlex) - class shlex(Iterable[str]): commenters: str wordchars: str @@ -41,5 +40,5 @@ class shlex(Iterable[str]): def push_source(self, newstream: Any, newfile: Any = ...) -> None: ... def pop_source(self) -> None: ... def error_leader(self, infile: str | None = ..., lineno: int | None = ...) -> None: ... - def __iter__(self: _SLT) -> _SLT: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> str: ... diff --git a/mypy/typeshed/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi index f4c492caccaf..67a81e60f4e8 100644 --- a/mypy/typeshed/stdlib/shutil.pyi +++ b/mypy/typeshed/stdlib/shutil.pyi @@ -1,9 +1,10 @@ import os import sys -from _typeshed import StrOrBytesPath, StrPath, SupportsRead, SupportsWrite +from _typeshed import BytesPath, StrOrBytesPath, StrPath, SupportsRead, SupportsWrite from typing import Any, AnyStr, Callable, Iterable, NamedTuple, Sequence, TypeVar, Union, overload -_PathT = TypeVar("_PathT", str, os.PathLike[str]) +_StrOrBytesPathT = TypeVar("_StrOrBytesPathT", bound=StrOrBytesPath) +_StrPathT = TypeVar("_StrPathT", bound=StrPath) # Return value of some functions that may either return a path-like object that was passed in or # a string _PathReturn = Any @@ -16,11 +17,17 @@ class ReadError(OSError): ... class RegistryError(Exception): ... def copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = ...) -> None: ... -def copyfile(src: StrPath, dst: _PathT, *, follow_symlinks: bool = ...) -> _PathT: ... -def copymode(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> None: ... -def copystat(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> None: ... +def copyfile(src: StrOrBytesPath, dst: _StrOrBytesPathT, *, follow_symlinks: bool = ...) -> _StrOrBytesPathT: ... +def copymode(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = ...) -> None: ... +def copystat(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = ...) -> None: ... +@overload def copy(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... +@overload +def copy(src: BytesPath, dst: BytesPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... +@overload def copy2(src: StrPath, dst: StrPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... +@overload +def copy2(src: BytesPath, dst: BytesPath, *, follow_symlinks: bool = ...) -> _PathReturn: ... def ignore_patterns(*patterns: StrPath) -> Callable[[Any, list[str]], set[str]]: ... if sys.version_info >= (3, 8): @@ -44,10 +51,13 @@ else: ignore_dangling_symlinks: bool = ..., ) -> _PathReturn: ... -def rmtree(path: bytes | StrPath, ignore_errors: bool = ..., onerror: Callable[[Any, Any, Any], Any] | None = ...) -> None: ... +def rmtree(path: StrOrBytesPath, ignore_errors: bool = ..., onerror: Callable[[Any, Any, Any], Any] | None = ...) -> None: ... _CopyFn = Union[Callable[[str, str], None], Callable[[StrPath, StrPath], None]] +# N.B. shutil.move appears to take bytes arguments, however, +# this does not work when dst is (or is within) an existing directory. +# (#6832) if sys.version_info >= (3, 9): def move(src: StrPath, dst: StrPath, copy_function: _CopyFn = ...) -> _PathReturn: ... @@ -61,16 +71,23 @@ class _ntuple_diskusage(NamedTuple): free: int def disk_usage(path: int | StrOrBytesPath) -> _ntuple_diskusage: ... -def chown(path: StrPath, user: str | int | None = ..., group: str | int | None = ...) -> None: ... +@overload +def chown(path: StrOrBytesPath, user: str | int, group: None = ...) -> None: ... +@overload +def chown(path: StrOrBytesPath, user: None = ..., *, group: str | int) -> None: ... +@overload +def chown(path: StrOrBytesPath, user: None, group: str | int) -> None: ... +@overload +def chown(path: StrOrBytesPath, user: str | int, group: str | int) -> None: ... if sys.version_info >= (3, 8): @overload - def which(cmd: StrPath, mode: int = ..., path: StrPath | None = ...) -> str | None: ... + def which(cmd: _StrPathT, mode: int = ..., path: StrPath | None = ...) -> str | _StrPathT | None: ... @overload def which(cmd: bytes, mode: int = ..., path: StrPath | None = ...) -> bytes | None: ... else: - def which(cmd: StrPath, mode: int = ..., path: StrPath | None = ...) -> str | None: ... + def which(cmd: _StrPathT, mode: int = ..., path: StrPath | None = ...) -> str | _StrPathT | None: ... def make_archive( base_name: str, diff --git a/mypy/typeshed/stdlib/signal.pyi b/mypy/typeshed/stdlib/signal.pyi index d617e24f227f..777391662aa3 100644 --- a/mypy/typeshed/stdlib/signal.pyi +++ b/mypy/typeshed/stdlib/signal.pyi @@ -1,56 +1,40 @@ import sys +from _typeshed import structseq from enum import IntEnum from types import FrameType -from typing import Any, Callable, Iterable, Optional, Tuple, Union - -if sys.platform != "win32": - class ItimerError(IOError): ... - ITIMER_PROF: int - ITIMER_REAL: int - ITIMER_VIRTUAL: int +from typing import Any, Callable, Iterable, Optional, Union +from typing_extensions import final NSIG: int class Signals(IntEnum): SIGABRT: int - if sys.platform != "win32": - SIGALRM: int + SIGEMT: int + SIGFPE: int + SIGILL: int + SIGINFO: int + SIGINT: int + SIGSEGV: int + SIGTERM: int + if sys.platform == "win32": SIGBREAK: int - if sys.platform != "win32": + CTRL_C_EVENT: int + CTRL_BREAK_EVENT: int + else: + SIGALRM: int SIGBUS: int SIGCHLD: int - if sys.platform != "darwin" and sys.platform != "win32": - SIGCLD: int - if sys.platform != "win32": SIGCONT: int - SIGEMT: int - SIGFPE: int - if sys.platform != "win32": SIGHUP: int - SIGILL: int - SIGINFO: int - SIGINT: int - if sys.platform != "win32": SIGIO: int SIGIOT: int SIGKILL: int SIGPIPE: int - if sys.platform != "darwin" and sys.platform != "win32": - SIGPOLL: int - SIGPWR: int - if sys.platform != "win32": SIGPROF: int SIGQUIT: int - if sys.platform != "darwin" and sys.platform != "win32": - SIGRTMAX: int - SIGRTMIN: int - SIGSEGV: int - if sys.platform != "win32": SIGSTOP: int SIGSYS: int - SIGTERM: int - if sys.platform != "win32": SIGTRAP: int SIGTSTP: int SIGTTIN: int @@ -62,65 +46,54 @@ class Signals(IntEnum): SIGWINCH: int SIGXCPU: int SIGXFSZ: int + if sys.platform != "darwin": + SIGCLD: int + SIGPOLL: int + SIGPWR: int + SIGRTMAX: int + SIGRTMIN: int class Handlers(IntEnum): SIG_DFL: int SIG_IGN: int -SIG_DFL = Handlers.SIG_DFL -SIG_IGN = Handlers.SIG_IGN - -if sys.platform != "win32": - class Sigmasks(IntEnum): - SIG_BLOCK: int - SIG_UNBLOCK: int - SIG_SETMASK: int - SIG_BLOCK = Sigmasks.SIG_BLOCK - SIG_UNBLOCK = Sigmasks.SIG_UNBLOCK - SIG_SETMASK = Sigmasks.SIG_SETMASK +SIG_DFL: Handlers +SIG_IGN: Handlers _SIGNUM = Union[int, Signals] _HANDLER = Union[Callable[[int, Optional[FrameType]], Any], int, Handlers, None] +def default_int_handler(signum: int, frame: FrameType | None) -> None: ... +def getsignal(__signalnum: _SIGNUM) -> _HANDLER: ... +def signal(__signalnum: _SIGNUM, __handler: _HANDLER) -> _HANDLER: ... + SIGABRT: Signals -if sys.platform != "win32": - SIGALRM: Signals +SIGEMT: Signals +SIGFPE: Signals +SIGILL: Signals +SIGINFO: Signals +SIGINT: Signals +SIGSEGV: Signals +SIGTERM: Signals + if sys.platform == "win32": SIGBREAK: Signals -if sys.platform != "win32": + CTRL_C_EVENT: Signals + CTRL_BREAK_EVENT: Signals +else: + SIGALRM: Signals SIGBUS: Signals SIGCHLD: Signals -if sys.platform != "darwin" and sys.platform != "win32": - SIGCLD: Signals -if sys.platform != "win32": SIGCONT: Signals -SIGEMT: Signals -SIGFPE: Signals -if sys.platform != "win32": SIGHUP: Signals -SIGILL: Signals -SIGINFO: Signals -SIGINT: Signals -if sys.platform != "win32": SIGIO: Signals SIGIOT: Signals SIGKILL: Signals SIGPIPE: Signals -if sys.platform != "darwin" and sys.platform != "win32": - SIGPOLL: Signals - SIGPWR: Signals -if sys.platform != "win32": SIGPROF: Signals SIGQUIT: Signals -if sys.platform != "darwin" and sys.platform != "win32": - SIGRTMAX: Signals - SIGRTMIN: Signals -SIGSEGV: Signals -if sys.platform != "win32": SIGSTOP: Signals SIGSYS: Signals -SIGTERM: Signals -if sys.platform != "win32": SIGTRAP: Signals SIGTSTP: Signals SIGTTIN: Signals @@ -132,64 +105,58 @@ if sys.platform != "win32": SIGWINCH: Signals SIGXCPU: Signals SIGXFSZ: Signals - -if sys.platform == "win32": - CTRL_C_EVENT: int - CTRL_BREAK_EVENT: int - -if sys.platform != "win32" and sys.platform != "darwin": - class struct_siginfo(Tuple[int, int, int, int, int, int, int]): - def __init__(self, sequence: Iterable[int]) -> None: ... - @property - def si_signo(self) -> int: ... - @property - def si_code(self) -> int: ... - @property - def si_errno(self) -> int: ... - @property - def si_pid(self) -> int: ... - @property - def si_uid(self) -> int: ... - @property - def si_status(self) -> int: ... - @property - def si_band(self) -> int: ... - -if sys.platform != "win32": + class ItimerError(IOError): ... + ITIMER_PROF: int + ITIMER_REAL: int + ITIMER_VIRTUAL: int + class Sigmasks(IntEnum): + SIG_BLOCK: int + SIG_UNBLOCK: int + SIG_SETMASK: int + SIG_BLOCK = Sigmasks.SIG_BLOCK + SIG_UNBLOCK = Sigmasks.SIG_UNBLOCK + SIG_SETMASK = Sigmasks.SIG_SETMASK def alarm(__seconds: int) -> int: ... - -def default_int_handler(signum: int, frame: FrameType) -> None: ... - -if sys.platform != "win32": def getitimer(__which: int) -> tuple[float, float]: ... - -def getsignal(__signalnum: _SIGNUM) -> _HANDLER: ... + def pause() -> None: ... + def pthread_kill(__thread_id: int, __signalnum: int) -> None: ... + def pthread_sigmask(__how: int, __mask: Iterable[int]) -> set[_SIGNUM]: ... + def setitimer(__which: int, __seconds: float, __interval: float = ...) -> tuple[float, float]: ... + def siginterrupt(__signalnum: int, __flag: bool) -> None: ... + def sigpending() -> Any: ... + def sigwait(__sigset: Iterable[int]) -> _SIGNUM: ... + if sys.platform != "darwin": + SIGCLD: Signals + SIGPOLL: Signals + SIGPWR: Signals + SIGRTMAX: Signals + SIGRTMIN: Signals + @final + class struct_siginfo(structseq[int], tuple[int, int, int, int, int, int, int]): + @property + def si_signo(self) -> int: ... + @property + def si_code(self) -> int: ... + @property + def si_errno(self) -> int: ... + @property + def si_pid(self) -> int: ... + @property + def si_uid(self) -> int: ... + @property + def si_status(self) -> int: ... + @property + def si_band(self) -> int: ... + def sigtimedwait(sigset: Iterable[int], timeout: float) -> struct_siginfo | None: ... + def sigwaitinfo(sigset: Iterable[int]) -> struct_siginfo: ... if sys.version_info >= (3, 8): def strsignal(__signalnum: _SIGNUM) -> str | None: ... def valid_signals() -> set[Signals]: ... def raise_signal(__signalnum: _SIGNUM) -> None: ... -if sys.platform != "win32": - def pause() -> None: ... - def pthread_kill(__thread_id: int, __signalnum: int) -> None: ... - def pthread_sigmask(__how: int, __mask: Iterable[int]) -> set[_SIGNUM]: ... - if sys.version_info >= (3, 7): def set_wakeup_fd(fd: int, *, warn_on_full_buffer: bool = ...) -> int: ... else: def set_wakeup_fd(fd: int) -> int: ... - -if sys.platform != "win32": - def setitimer(__which: int, __seconds: float, __interval: float = ...) -> tuple[float, float]: ... - def siginterrupt(__signalnum: int, __flag: bool) -> None: ... - -def signal(__signalnum: _SIGNUM, __handler: _HANDLER) -> _HANDLER: ... - -if sys.platform != "win32": - def sigpending() -> Any: ... - def sigwait(__sigset: Iterable[int]) -> _SIGNUM: ... - if sys.platform != "darwin": - def sigtimedwait(sigset: Iterable[int], timeout: float) -> struct_siginfo | None: ... - def sigwaitinfo(sigset: Iterable[int]) -> struct_siginfo: ... diff --git a/mypy/typeshed/stdlib/smtpd.pyi b/mypy/typeshed/stdlib/smtpd.pyi index 2b6020524827..8a532058a2bb 100644 --- a/mypy/typeshed/stdlib/smtpd.pyi +++ b/mypy/typeshed/stdlib/smtpd.pyi @@ -2,9 +2,9 @@ import asynchat import asyncore import socket from collections import defaultdict -from typing import Any, Tuple, Type +from typing import Any -_Address = Tuple[str, int] # (host, port) +_Address = tuple[str, int] # (host, port) class SMTPChannel(asynchat.async_chat): COMMAND: int @@ -40,7 +40,7 @@ class SMTPChannel(asynchat.async_chat): decode_data: bool = ..., ) -> None: ... # base asynchat.async_chat.push() accepts bytes - def push(self, msg: str) -> None: ... # type: ignore + def push(self, msg: str) -> None: ... # type: ignore[override] def collect_incoming_data(self, data: bytes) -> None: ... def found_terminator(self) -> None: ... def smtp_HELO(self, arg: str) -> None: ... @@ -56,7 +56,7 @@ class SMTPChannel(asynchat.async_chat): def smtp_EXPN(self, arg: str) -> None: ... class SMTPServer(asyncore.dispatcher): - channel_class: Type[SMTPChannel] + channel_class: type[SMTPChannel] data_size_limit: int enable_SMTPUTF8: bool @@ -77,11 +77,7 @@ class SMTPServer(asyncore.dispatcher): class DebuggingServer(SMTPServer): ... class PureProxy(SMTPServer): - def process_message( # type: ignore - self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str - ) -> str | None: ... + def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str) -> str | None: ... # type: ignore[override] class MailmanProxy(PureProxy): - def process_message( # type: ignore - self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str - ) -> str | None: ... + def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str) -> str | None: ... # type: ignore[override] diff --git a/mypy/typeshed/stdlib/smtplib.pyi b/mypy/typeshed/stdlib/smtplib.pyi index 5dbdf5d44c29..4e4fb1648832 100644 --- a/mypy/typeshed/stdlib/smtplib.pyi +++ b/mypy/typeshed/stdlib/smtplib.pyi @@ -1,14 +1,15 @@ +import sys from _typeshed import Self from email.message import Message as _Message from socket import socket from ssl import SSLContext from types import TracebackType -from typing import Any, Dict, Pattern, Protocol, Sequence, Tuple, Type, Union, overload +from typing import Any, Pattern, Protocol, Sequence, Union, overload -_Reply = Tuple[int, bytes] -_SendErrs = Dict[str, _Reply] +_Reply = tuple[int, bytes] +_SendErrs = dict[str, _Reply] # Should match source_address for socket.create_connection -_SourceAddress = Tuple[Union[bytearray, bytes, str], int] +_SourceAddress = tuple[Union[bytearray, bytes, str], int] SMTP_PORT: int SMTP_SSL_PORT: int @@ -78,7 +79,7 @@ class SMTP: ) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None ) -> None: ... def set_debuglevel(self, debuglevel: int) -> None: ... def connect(self, host: str = ..., port: int = ..., source_address: _SourceAddress | None = ...) -> _Reply: ... @@ -149,6 +150,16 @@ class SMTP_SSL(SMTP): LMTP_PORT: int class LMTP(SMTP): - def __init__( - self, host: str = ..., port: int = ..., local_hostname: str | None = ..., source_address: _SourceAddress | None = ... - ) -> None: ... + if sys.version_info >= (3, 9): + def __init__( + self, + host: str = ..., + port: int = ..., + local_hostname: str | None = ..., + source_address: _SourceAddress | None = ..., + timeout: float = ..., + ) -> None: ... + else: + def __init__( + self, host: str = ..., port: int = ..., local_hostname: str | None = ..., source_address: _SourceAddress | None = ... + ) -> None: ... diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index 1f5ae6eb76c8..e97a66f5e8c5 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -3,7 +3,7 @@ from _typeshed import ReadableBuffer, Self, WriteableBuffer from collections.abc import Iterable from enum import IntEnum, IntFlag from io import RawIOBase -from typing import Any, BinaryIO, TextIO, TypeVar, overload +from typing import Any, BinaryIO, TextIO, overload from typing_extensions import Literal # Ideally, we'd just do "from _socket import *". Unfortunately, socket @@ -366,6 +366,8 @@ if sys.platform == "linux" and sys.version_info >= (3, 9): SO_J1939_PROMISC as SO_J1939_PROMISC, SO_J1939_SEND_PRIO as SO_J1939_SEND_PRIO, ) +if sys.platform == "linux" and sys.version_info >= (3, 10): + from _socket import IPPROTO_MPTCP as IPPROTO_MPTCP if sys.platform == "win32": from _socket import ( RCVALL_IPLEVEL as RCVALL_IPLEVEL, @@ -378,8 +380,6 @@ if sys.platform == "win32": SIO_RCVALL as SIO_RCVALL, ) -_T = TypeVar("_T") - # Re-exported from errno EBADF: int EAGAIN: int @@ -544,7 +544,7 @@ class socket(_socket.socket): ) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__(self, *args: object) -> None: ... - def dup(self: _T) -> _T: ... # noqa: F811 + def dup(self: Self) -> Self: ... # noqa: F811 def accept(self) -> tuple[socket, _RetAddress]: ... # Note that the makefile's documented windows-specific behavior is not represented # mode strings with duplicates are intentionally excluded @@ -570,9 +570,9 @@ class socket(_socket.socket): ) -> BinaryIO: ... def sendfile(self, file: BinaryIO, offset: int = ..., count: int | None = ...) -> int: ... @property - def family(self) -> AddressFamily: ... # type: ignore + def family(self) -> AddressFamily: ... # type: ignore[override] @property - def type(self) -> SocketKind: ... # type: ignore + def type(self) -> SocketKind: ... # type: ignore[override] def get_inheritable(self) -> bool: ... def set_inheritable(self, inheritable: bool) -> None: ... @@ -593,7 +593,7 @@ if sys.platform == "win32": def socketpair(family: int = ..., type: int = ..., proto: int = ...) -> tuple[socket, socket]: ... else: - def socketpair( # type: ignore + def socketpair( family: int | AddressFamily | None = ..., type: SocketType | int = ..., proto: int = ... ) -> tuple[socket, socket]: ... diff --git a/mypy/typeshed/stdlib/socketserver.pyi b/mypy/typeshed/stdlib/socketserver.pyi index 6f5eeefb84fd..b50d816f35d1 100644 --- a/mypy/typeshed/stdlib/socketserver.pyi +++ b/mypy/typeshed/stdlib/socketserver.pyi @@ -2,11 +2,10 @@ import sys import types from _typeshed import Self from socket import socket as _socket -from typing import Any, BinaryIO, Callable, ClassVar, Tuple, Type, TypeVar, Union +from typing import Any, BinaryIO, Callable, ClassVar, Union -_T = TypeVar("_T") -_RequestType = Union[_socket, Tuple[bytes, _socket]] -_AddressType = Union[Tuple[str, int], str] +_RequestType = Union[_socket, tuple[bytes, _socket]] +_AddressType = Union[tuple[str, int], str] class BaseServer: address_family: int @@ -33,7 +32,7 @@ class BaseServer: def verify_request(self, request: _RequestType, client_address: _AddressType) -> bool: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None ) -> None: ... def service_actions(self) -> None: ... def shutdown_request(self, request: _RequestType) -> None: ... # undocumented @@ -55,6 +54,7 @@ class TCPServer(BaseServer): def close_request(self, request: _RequestType) -> None: ... # undocumented class UDPServer(BaseServer): + max_packet_size: ClassVar[int] def __init__( self, server_address: tuple[str, int], diff --git a/mypy/typeshed/stdlib/spwd.pyi b/mypy/typeshed/stdlib/spwd.pyi index 0f8d36fee945..7a62d62523f5 100644 --- a/mypy/typeshed/stdlib/spwd.pyi +++ b/mypy/typeshed/stdlib/spwd.pyi @@ -1,15 +1,28 @@ -from typing import NamedTuple +import sys +from _typeshed import structseq +from typing import Any +from typing_extensions import final -class struct_spwd(NamedTuple): - sp_namp: str - sp_pwdp: str - sp_lstchg: int - sp_min: int - sp_max: int - sp_warn: int - sp_inact: int - sp_expire: int - sp_flag: int - -def getspall() -> list[struct_spwd]: ... -def getspnam(__arg: str) -> struct_spwd: ... +if sys.platform != "win32": + @final + class struct_spwd(structseq[Any], tuple[str, str, int, int, int, int, int, int, int]): + @property + def sp_namp(self) -> str: ... + @property + def sp_pwdp(self) -> str: ... + @property + def sp_lstchg(self) -> int: ... + @property + def sp_min(self) -> int: ... + @property + def sp_max(self) -> int: ... + @property + def sp_warn(self) -> int: ... + @property + def sp_inact(self) -> int: ... + @property + def sp_expire(self) -> int: ... + @property + def sp_flag(self) -> int: ... + def getspall() -> list[struct_spwd]: ... + def getspnam(__arg: str) -> struct_spwd: ... diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index e2e45d538da9..32b4a2e95dba 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Self, StrOrBytesPath from datetime import date, datetime, time -from typing import Any, Callable, Generator, Iterable, Iterator, Protocol, Type, TypeVar +from typing import Any, Callable, Generator, Iterable, Iterator, Protocol, TypeVar _T = TypeVar("_T") @@ -40,6 +40,8 @@ if sys.version_info >= (3, 7): SQLITE_DELETE: int SQLITE_DENY: int SQLITE_DETACH: int +if sys.version_info >= (3, 7): + SQLITE_DONE: int SQLITE_DROP_INDEX: int SQLITE_DROP_TABLE: int SQLITE_DROP_TEMP_INDEX: int @@ -83,7 +85,7 @@ version: str # TODO: adapt needs to get probed def adapt(obj, protocol, alternate): ... -def complete_statement(sql: str) -> bool: ... +def complete_statement(statement: str) -> bool: ... if sys.version_info >= (3, 7): def connect( @@ -92,7 +94,7 @@ if sys.version_info >= (3, 7): detect_types: int = ..., isolation_level: str | None = ..., check_same_thread: bool = ..., - factory: Type[Connection] | None = ..., + factory: type[Connection] | None = ..., cached_statements: int = ..., uri: bool = ..., ) -> Connection: ... @@ -104,18 +106,18 @@ else: detect_types: int = ..., isolation_level: str | None = ..., check_same_thread: bool = ..., - factory: Type[Connection] | None = ..., + factory: type[Connection] | None = ..., cached_statements: int = ..., uri: bool = ..., ) -> Connection: ... def enable_callback_tracebacks(__enable: bool) -> None: ... def enable_shared_cache(enable: int) -> None: ... -def register_adapter(__type: Type[_T], __caster: Callable[[_T], int | float | str | bytes]) -> None: ... +def register_adapter(__type: type[_T], __caster: Callable[[_T], int | float | str | bytes]) -> None: ... def register_converter(__name: str, __converter: Callable[[bytes], Any]) -> None: ... if sys.version_info < (3, 8): - class Cache(object): + class Cache: def __init__(self, *args, **kwargs) -> None: ... def display(self, *args, **kwargs) -> None: ... def get(self, *args, **kwargs) -> None: ... @@ -124,7 +126,7 @@ class _AggregateProtocol(Protocol): def step(self, value: int) -> None: ... def finalize(self) -> int: ... -class Connection(object): +class Connection: DataError: Any DatabaseError: Any Error: Any @@ -154,16 +156,14 @@ class Connection(object): # TODO: please check in executemany() if seq_of_parameters type is possible like this def executemany(self, __sql: str, __parameters: Iterable[Iterable[Any]]) -> Cursor: ... def executescript(self, __sql_script: bytes | str) -> Cursor: ... - def interrupt(self, *args: Any, **kwargs: Any) -> None: ... - def iterdump(self, *args: Any, **kwargs: Any) -> Generator[str, None, None]: ... - def rollback(self, *args: Any, **kwargs: Any) -> None: ... - # TODO: set_authorizer(authorzer_callback) - # see https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.set_authorizer - # returns [SQLITE_OK, SQLITE_DENY, SQLITE_IGNORE] so perhaps int - def set_authorizer(self, *args: Any, **kwargs: Any) -> None: ... - # set_progress_handler(handler, n) -> see https://docs.python.org/2/library/sqlite3.html#sqlite3.Connection.set_progress_handler - def set_progress_handler(self, *args: Any, **kwargs: Any) -> None: ... - def set_trace_callback(self, *args: Any, **kwargs: Any) -> None: ... + def interrupt(self) -> None: ... + def iterdump(self) -> Generator[str, None, None]: ... + def rollback(self) -> None: ... + def set_authorizer( + self, authorizer_callback: Callable[[int, str | None, str | None, str | None, str | None], int] | None + ) -> None: ... + def set_progress_handler(self, progress_handler: Callable[[], bool | None] | None, n: int) -> None: ... + def set_trace_callback(self, trace_callback: Callable[[str], object] | None) -> None: ... # enable_load_extension and load_extension is not available on python distributions compiled # without sqlite3 loadable extension support. see footnotes https://docs.python.org/3/library/sqlite3.html#f1 def enable_load_extension(self, enabled: bool) -> None: ... @@ -193,21 +193,26 @@ class Cursor(Iterator[Any]): # required type is sqlite3.Connection (which is imported as _Connection) # however, the name of the __init__ variable is unknown def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def close(self, *args: Any, **kwargs: Any) -> None: ... + def close(self) -> None: ... def execute(self, __sql: str, __parameters: Iterable[Any] = ...) -> Cursor: ... def executemany(self, __sql: str, __seq_of_parameters: Iterable[Iterable[Any]]) -> Cursor: ... def executescript(self, __sql_script: bytes | str) -> Cursor: ... def fetchall(self) -> list[Any]: ... def fetchmany(self, size: int | None = ...) -> list[Any]: ... def fetchone(self) -> Any: ... - def setinputsizes(self, *args: Any, **kwargs: Any) -> None: ... - def setoutputsize(self, *args: Any, **kwargs: Any) -> None: ... + def setinputsizes(self, __sizes: object) -> None: ... # does nothing + def setoutputsize(self, __size: object, __column: object = ...) -> None: ... # does nothing def __iter__(self) -> Cursor: ... def __next__(self) -> Any: ... class DataError(DatabaseError): ... class DatabaseError(Error): ... -class Error(Exception): ... + +class Error(Exception): + if sys.version_info >= (3, 11): + sqlite_errorcode: int + sqlite_errorname: str + class IntegrityError(DatabaseError): ... class InterfaceError(Error): ... class InternalError(DatabaseError): ... @@ -216,14 +221,14 @@ class OperationalError(DatabaseError): ... OptimizedUnicode = str -class PrepareProtocol(object): +class PrepareProtocol: def __init__(self, *args: Any, **kwargs: Any) -> None: ... class ProgrammingError(DatabaseError): ... -class Row(object): +class Row: def __init__(self, *args: Any, **kwargs: Any) -> None: ... - def keys(self, *args: Any, **kwargs: Any): ... + def keys(self): ... def __eq__(self, other): ... def __ge__(self, other): ... def __getitem__(self, index): ... @@ -236,7 +241,7 @@ class Row(object): def __ne__(self, other): ... if sys.version_info < (3, 8): - class Statement(object): + class Statement: def __init__(self, *args, **kwargs): ... class Warning(Exception): ... diff --git a/mypy/typeshed/stdlib/sre_compile.pyi b/mypy/typeshed/stdlib/sre_compile.pyi index aac8c0242764..98a9f4dad008 100644 --- a/mypy/typeshed/stdlib/sre_compile.pyi +++ b/mypy/typeshed/stdlib/sre_compile.pyi @@ -1,18 +1,5 @@ -from sre_constants import ( - SRE_FLAG_ASCII as SRE_FLAG_ASCII, - SRE_FLAG_DEBUG as SRE_FLAG_DEBUG, - SRE_FLAG_DOTALL as SRE_FLAG_DOTALL, - SRE_FLAG_IGNORECASE as SRE_FLAG_IGNORECASE, - SRE_FLAG_LOCALE as SRE_FLAG_LOCALE, - SRE_FLAG_MULTILINE as SRE_FLAG_MULTILINE, - SRE_FLAG_TEMPLATE as SRE_FLAG_TEMPLATE, - SRE_FLAG_UNICODE as SRE_FLAG_UNICODE, - SRE_FLAG_VERBOSE as SRE_FLAG_VERBOSE, - SRE_INFO_CHARSET as SRE_INFO_CHARSET, - SRE_INFO_LITERAL as SRE_INFO_LITERAL, - SRE_INFO_PREFIX as SRE_INFO_PREFIX, - _NamedIntConstant, -) +from sre_constants import * +from sre_constants import _NamedIntConstant from sre_parse import SubPattern from typing import Any, Pattern diff --git a/mypy/typeshed/stdlib/sre_constants.pyi b/mypy/typeshed/stdlib/sre_constants.pyi index 4658d0e4b175..df7e1a28007b 100644 --- a/mypy/typeshed/stdlib/sre_constants.pyi +++ b/mypy/typeshed/stdlib/sre_constants.pyi @@ -1,6 +1,8 @@ import sys from typing import Any +MAXGROUPS: int + MAGIC: int class error(Exception): @@ -20,6 +22,9 @@ OPCODES: list[_NamedIntConstant] ATCODES: list[_NamedIntConstant] CHCODES: list[_NamedIntConstant] OP_IGNORE: dict[_NamedIntConstant, _NamedIntConstant] +if sys.version_info >= (3, 7): + OP_LOCALE_IGNORE: dict[_NamedIntConstant, _NamedIntConstant] + OP_UNICODE_IGNORE: dict[_NamedIntConstant, _NamedIntConstant] AT_MULTILINE: dict[_NamedIntConstant, _NamedIntConstant] AT_LOCALE: dict[_NamedIntConstant, _NamedIntConstant] AT_UNICODE: dict[_NamedIntConstant, _NamedIntConstant] @@ -75,6 +80,14 @@ SUBPATTERN: _NamedIntConstant MIN_REPEAT_ONE: _NamedIntConstant if sys.version_info >= (3, 7): RANGE_UNI_IGNORE: _NamedIntConstant + GROUPREF_LOC_IGNORE: _NamedIntConstant + GROUPREF_UNI_IGNORE: _NamedIntConstant + IN_LOC_IGNORE: _NamedIntConstant + IN_UNI_IGNORE: _NamedIntConstant + LITERAL_LOC_IGNORE: _NamedIntConstant + LITERAL_UNI_IGNORE: _NamedIntConstant + NOT_LITERAL_LOC_IGNORE: _NamedIntConstant + NOT_LITERAL_UNI_IGNORE: _NamedIntConstant else: RANGE_IGNORE: _NamedIntConstant MIN_REPEAT: _NamedIntConstant diff --git a/mypy/typeshed/stdlib/sre_parse.pyi b/mypy/typeshed/stdlib/sre_parse.pyi index 2d00bedc2c81..c4de55bcbf7e 100644 --- a/mypy/typeshed/stdlib/sre_parse.pyi +++ b/mypy/typeshed/stdlib/sre_parse.pyi @@ -1,6 +1,7 @@ import sys +from sre_constants import * from sre_constants import _NamedIntConstant as _NIC, error as _Error -from typing import Any, Iterable, List, Match, Optional, Pattern as _Pattern, Tuple, Union, overload +from typing import Any, Iterable, Match, Optional, Pattern as _Pattern, Union, overload SPECIAL_CHARS: str REPEAT_CHARS: str @@ -12,6 +13,8 @@ WHITESPACE: frozenset[str] ESCAPES: dict[str, tuple[_NIC, int]] CATEGORIES: dict[str, tuple[_NIC, _NIC] | tuple[_NIC, list[tuple[_NIC, _NIC]]]] FLAGS: dict[str, int] +if sys.version_info >= (3, 7): + TYPE_FLAGS: int GLOBAL_FLAGS: int class Verbose(Exception): ... @@ -24,7 +27,7 @@ class _State: def __init__(self) -> None: ... @property def groups(self) -> int: ... - def opengroup(self, name: str = ...) -> int: ... + def opengroup(self, name: str | None = ...) -> int: ... def closegroup(self, gid: int, p: SubPattern) -> None: ... def checkgroup(self, gid: int) -> bool: ... def checklookbehindgroup(self, gid: int, source: Tokenizer) -> None: ... @@ -34,12 +37,12 @@ if sys.version_info >= (3, 8): else: Pattern = _State -_OpSubpatternType = Tuple[Optional[int], int, int, SubPattern] -_OpGroupRefExistsType = Tuple[int, SubPattern, SubPattern] -_OpInType = List[Tuple[_NIC, int]] -_OpBranchType = Tuple[None, List[SubPattern]] +_OpSubpatternType = tuple[Optional[int], int, int, SubPattern] +_OpGroupRefExistsType = tuple[int, SubPattern, SubPattern] +_OpInType = list[tuple[_NIC, int]] +_OpBranchType = tuple[None, list[SubPattern]] _AvType = Union[_OpInType, _OpBranchType, Iterable[SubPattern], _OpGroupRefExistsType, _OpSubpatternType] -_CodeType = Tuple[_NIC, _AvType] +_CodeType = tuple[_NIC, _AvType] class SubPattern: data: list[_CodeType] @@ -82,8 +85,8 @@ class Tokenizer: def fix_flags(src: str | bytes, flags: int) -> int: ... -_TemplateType = Tuple[List[Tuple[int, int]], List[Optional[str]]] -_TemplateByteType = Tuple[List[Tuple[int, int]], List[Optional[bytes]]] +_TemplateType = tuple[list[tuple[int, int]], list[Optional[str]]] +_TemplateByteType = tuple[list[tuple[int, int]], list[Optional[bytes]]] if sys.version_info >= (3, 8): def parse(str: str, flags: int = ..., state: State | None = ...) -> SubPattern: ... @overload diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index 689b083d764c..8851c94efc16 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -2,14 +2,14 @@ import enum import socket import sys from _typeshed import ReadableBuffer, Self, StrOrBytesPath, WriteableBuffer -from typing import Any, Callable, ClassVar, Dict, Iterable, List, NamedTuple, Optional, Set, Tuple, Type, Union, overload +from typing import Any, Callable, ClassVar, Iterable, NamedTuple, Optional, Union, overload from typing_extensions import Literal, TypedDict -_PCTRTT = Tuple[Tuple[str, str], ...] -_PCTRTTT = Tuple[_PCTRTT, ...] -_PeerCertRetDictType = Dict[str, Union[str, _PCTRTTT, _PCTRTT]] +_PCTRTT = tuple[tuple[str, str], ...] +_PCTRTTT = tuple[_PCTRTT, ...] +_PeerCertRetDictType = dict[str, Union[str, _PCTRTTT, _PCTRTT]] _PeerCertRetType = Union[_PeerCertRetDictType, bytes, None] -_EnumRetType = List[Tuple[bytes, str, Union[Set[str], bool]]] +_EnumRetType = list[tuple[bytes, str, Union[set[str], bool]]] _PasswordType = Union[Callable[[], Union[str, bytes]], str, bytes] _SrvnmeCbType = Callable[[Union[SSLSocket, SSLObject], Optional[str], SSLSocket], Optional[int]] @@ -102,7 +102,15 @@ def RAND_egd(path: str) -> None: ... def RAND_add(__s: bytes, __entropy: float) -> None: ... def match_hostname(cert: _PeerCertRetType, hostname: str) -> None: ... def cert_time_to_seconds(cert_time: str) -> int: ... -def get_server_certificate(addr: tuple[str, int], ssl_version: int = ..., ca_certs: str | None = ...) -> str: ... + +if sys.version_info >= (3, 10): + def get_server_certificate( + addr: tuple[str, int], ssl_version: int = ..., ca_certs: str | None = ..., timeout: float = ... + ) -> str: ... + +else: + def get_server_certificate(addr: tuple[str, int], ssl_version: int = ..., ca_certs: str | None = ...) -> str: ... + def DER_cert_to_PEM_cert(der_cert_bytes: bytes) -> str: ... def PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: ... @@ -135,6 +143,9 @@ class VerifyFlags(enum.IntFlag): VERIFY_CRL_CHECK_CHAIN: int VERIFY_X509_STRICT: int VERIFY_X509_TRUSTED_FIRST: int + if sys.version_info >= (3, 10): + VERIFY_ALLOW_PROXY_CERTS: int + VERIFY_X509_PARTIAL_CHAIN: int VERIFY_DEFAULT: VerifyFlags VERIFY_CRL_CHECK_LEAF: VerifyFlags @@ -142,6 +153,10 @@ VERIFY_CRL_CHECK_CHAIN: VerifyFlags VERIFY_X509_STRICT: VerifyFlags VERIFY_X509_TRUSTED_FIRST: VerifyFlags +if sys.version_info >= (3, 10): + VERIFY_ALLOW_PROXY_CERTS: VerifyFlags + VERIFY_X509_PARTIAL_CHAIN: VerifyFlags + class _SSLMethod(enum.IntEnum): PROTOCOL_SSLv23: int PROTOCOL_SSLv2: int @@ -205,7 +220,7 @@ if sys.version_info >= (3, 7): HAS_TLSv1: bool HAS_TLSv1_1: bool HAS_TLSv1_2: bool - HAS_TLSv1_3: bool +HAS_TLSv1_3: bool HAS_ALPN: bool HAS_ECDH: bool HAS_SNI: bool @@ -279,9 +294,9 @@ class _ASN1Object(NamedTuple): longname: str oid: str @classmethod - def fromnid(cls: Type[Self], nid: int) -> Self: ... + def fromnid(cls: type[Self], nid: int) -> Self: ... @classmethod - def fromname(cls: Type[Self], name: str) -> Self: ... + def fromname(cls: type[Self], name: str) -> Self: ... class Purpose(_ASN1Object, enum.Enum): SERVER_AUTH: _ASN1Object @@ -293,7 +308,9 @@ class SSLSocket(socket.socket): server_hostname: str | None session: SSLSession | None session_reused: bool | None - if sys.version_info < (3, 7): + if sys.version_info >= (3, 7): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + else: def __init__( self, sock: socket.socket | None = ..., @@ -315,8 +332,6 @@ class SSLSocket(socket.socket): _context: SSLContext | None = ..., _session: Any | None = ..., ) -> None: ... - else: - def __init__(self, *args: Any, **kwargs: Any) -> None: ... def connect(self, addr: socket._Address | bytes) -> None: ... def connect_ex(self, addr: socket._Address | bytes) -> int: ... def recv(self, buflen: int = ..., flags: int = ...) -> bytes: ... @@ -376,8 +391,8 @@ class SSLContext: maximum_version: TLSVersion minimum_version: TLSVersion sni_callback: Callable[[SSLObject, str, SSLContext], None | int] | None - sslobject_class: ClassVar[Type[SSLObject]] - sslsocket_class: ClassVar[Type[SSLSocket]] + sslobject_class: ClassVar[type[SSLObject]] + sslsocket_class: ClassVar[type[SSLSocket]] if sys.version_info >= (3, 8): keylog_filename: str post_handshake_auth: bool diff --git a/mypy/typeshed/stdlib/stat.pyi b/mypy/typeshed/stdlib/stat.pyi index d6450fe77817..4518acb5a162 100644 --- a/mypy/typeshed/stdlib/stat.pyi +++ b/mypy/typeshed/stdlib/stat.pyi @@ -1,97 +1 @@ -import sys - -def S_ISDIR(mode: int) -> bool: ... -def S_ISCHR(mode: int) -> bool: ... -def S_ISBLK(mode: int) -> bool: ... -def S_ISREG(mode: int) -> bool: ... -def S_ISFIFO(mode: int) -> bool: ... -def S_ISLNK(mode: int) -> bool: ... -def S_ISSOCK(mode: int) -> bool: ... -def S_IMODE(mode: int) -> int: ... -def S_IFMT(mode: int) -> int: ... -def S_ISDOOR(mode: int) -> int: ... -def S_ISPORT(mode: int) -> int: ... -def S_ISWHT(mode: int) -> int: ... -def filemode(mode: int) -> str: ... - -ST_MODE: int -ST_INO: int -ST_DEV: int -ST_NLINK: int -ST_UID: int -ST_GID: int -ST_SIZE: int -ST_ATIME: int -ST_MTIME: int -ST_CTIME: int - -S_IFSOCK: int -S_IFLNK: int -S_IFREG: int -S_IFBLK: int -S_IFDIR: int -S_IFCHR: int -S_IFIFO: int -S_IFDOOR: int -S_IFPORT: int -S_IFWHT: int -S_ISUID: int -S_ISGID: int -S_ISVTX: int - -S_IRWXU: int -S_IRUSR: int -S_IWUSR: int -S_IXUSR: int - -S_IRWXG: int -S_IRGRP: int -S_IWGRP: int -S_IXGRP: int - -S_IRWXO: int -S_IROTH: int -S_IWOTH: int -S_IXOTH: int - -S_ENFMT: int -S_IREAD: int -S_IWRITE: int -S_IEXEC: int - -UF_NODUMP: int -UF_IMMUTABLE: int -UF_APPEND: int -UF_OPAQUE: int -UF_NOUNLINK: int -if sys.platform == "darwin": - UF_COMPRESSED: int # OS X 10.6+ only - UF_HIDDEN: int # OX X 10.5+ only -SF_ARCHIVED: int -SF_IMMUTABLE: int -SF_APPEND: int -SF_NOUNLINK: int -SF_SNAPSHOT: int - -FILE_ATTRIBUTE_ARCHIVE: int -FILE_ATTRIBUTE_COMPRESSED: int -FILE_ATTRIBUTE_DEVICE: int -FILE_ATTRIBUTE_DIRECTORY: int -FILE_ATTRIBUTE_ENCRYPTED: int -FILE_ATTRIBUTE_HIDDEN: int -FILE_ATTRIBUTE_INTEGRITY_STREAM: int -FILE_ATTRIBUTE_NORMAL: int -FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: int -FILE_ATTRIBUTE_NO_SCRUB_DATA: int -FILE_ATTRIBUTE_OFFLINE: int -FILE_ATTRIBUTE_READONLY: int -FILE_ATTRIBUTE_REPARSE_POINT: int -FILE_ATTRIBUTE_SPARSE_FILE: int -FILE_ATTRIBUTE_SYSTEM: int -FILE_ATTRIBUTE_TEMPORARY: int -FILE_ATTRIBUTE_VIRTUAL: int - -if sys.platform == "win32" and sys.version_info >= (3, 8): - IO_REPARSE_TAG_SYMLINK: int - IO_REPARSE_TAG_MOUNT_POINT: int - IO_REPARSE_TAG_APPEXECLINK: int +from _stat import * diff --git a/mypy/typeshed/stdlib/statistics.pyi b/mypy/typeshed/stdlib/statistics.pyi index ec3574ab12b1..8437a43ffff1 100644 --- a/mypy/typeshed/stdlib/statistics.pyi +++ b/mypy/typeshed/stdlib/statistics.pyi @@ -1,10 +1,9 @@ import sys -from _typeshed import SupportsLessThanT +from _typeshed import Self, SupportsRichComparisonT from decimal import Decimal from fractions import Fraction -from typing import Any, Hashable, Iterable, NamedTuple, Sequence, SupportsFloat, Type, TypeVar, Union +from typing import Any, Hashable, Iterable, NamedTuple, Sequence, SupportsFloat, TypeVar, Union -_T = TypeVar("_T") # Most functions in this module accept homogeneous collections of one of these types _Number = Union[float, Decimal, Fraction] _NumberT = TypeVar("_NumberT", float, Decimal, Fraction) @@ -27,8 +26,8 @@ else: def harmonic_mean(data: Iterable[_NumberT]) -> _NumberT: ... def median(data: Iterable[_NumberT]) -> _NumberT: ... -def median_low(data: Iterable[SupportsLessThanT]) -> SupportsLessThanT: ... -def median_high(data: Iterable[SupportsLessThanT]) -> SupportsLessThanT: ... +def median_low(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparisonT: ... +def median_high(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparisonT: ... def median_grouped(data: Iterable[_NumberT], interval: _NumberT = ...) -> _NumberT: ... def mode(data: Iterable[_HashableT]) -> _HashableT: ... @@ -58,7 +57,7 @@ if sys.version_info >= (3, 8): @property def variance(self) -> float: ... @classmethod - def from_samples(cls: Type[_T], data: Iterable[SupportsFloat]) -> _T: ... + def from_samples(cls: type[Self], data: Iterable[SupportsFloat]) -> Self: ... def samples(self, n: int, *, seed: Any | None = ...) -> list[float]: ... def pdf(self, x: float) -> float: ... def cdf(self, x: float) -> float: ... diff --git a/mypy/typeshed/stdlib/stringprep.pyi b/mypy/typeshed/stdlib/stringprep.pyi index cbc562d460f6..fc28c027ca9b 100644 --- a/mypy/typeshed/stdlib/stringprep.pyi +++ b/mypy/typeshed/stdlib/stringprep.pyi @@ -1,3 +1,11 @@ +b1_set: set[int] +b3_exceptions: dict[int, str] +c22_specials: set[int] +c6_set: set[int] +c7_set: set[int] +c8_set: set[int] +c9_set: set[int] + def in_table_a1(code: str) -> bool: ... def in_table_b1(code: str) -> bool: ... def map_table_b3(code: str) -> str: ... diff --git a/mypy/typeshed/stdlib/struct.pyi b/mypy/typeshed/stdlib/struct.pyi index d7c9cbef7dce..47af62973259 100644 --- a/mypy/typeshed/stdlib/struct.pyi +++ b/mypy/typeshed/stdlib/struct.pyi @@ -1,14 +1,14 @@ import sys from _typeshed import ReadableBuffer, WriteableBuffer -from typing import Any, Iterator, Tuple +from typing import Any, Iterator class error(Exception): ... def pack(fmt: str | bytes, *v: Any) -> bytes: ... def pack_into(fmt: str | bytes, buffer: WriteableBuffer, offset: int, *v: Any) -> None: ... -def unpack(__format: str | bytes, __buffer: ReadableBuffer) -> Tuple[Any, ...]: ... -def unpack_from(__format: str | bytes, buffer: ReadableBuffer, offset: int = ...) -> Tuple[Any, ...]: ... -def iter_unpack(__format: str | bytes, __buffer: ReadableBuffer) -> Iterator[Tuple[Any, ...]]: ... +def unpack(__format: str | bytes, __buffer: ReadableBuffer) -> tuple[Any, ...]: ... +def unpack_from(__format: str | bytes, buffer: ReadableBuffer, offset: int = ...) -> tuple[Any, ...]: ... +def iter_unpack(__format: str | bytes, __buffer: ReadableBuffer) -> Iterator[tuple[Any, ...]]: ... def calcsize(__format: str | bytes) -> int: ... class Struct: @@ -20,6 +20,6 @@ class Struct: def __init__(self, format: str | bytes) -> None: ... def pack(self, *v: Any) -> bytes: ... def pack_into(self, buffer: WriteableBuffer, offset: int, *v: Any) -> None: ... - def unpack(self, __buffer: ReadableBuffer) -> Tuple[Any, ...]: ... - def unpack_from(self, buffer: ReadableBuffer, offset: int = ...) -> Tuple[Any, ...]: ... - def iter_unpack(self, __buffer: ReadableBuffer) -> Iterator[Tuple[Any, ...]]: ... + def unpack(self, __buffer: ReadableBuffer) -> tuple[Any, ...]: ... + def unpack_from(self, buffer: ReadableBuffer, offset: int = ...) -> tuple[Any, ...]: ... + def iter_unpack(self, __buffer: ReadableBuffer) -> Iterator[tuple[Any, ...]]: ... diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index fce517745ee6..b0987f3991fa 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Self, StrOrBytesPath from types import TracebackType -from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Mapping, Sequence, Type, TypeVar, Union, overload +from typing import IO, Any, AnyStr, Callable, Generic, Iterable, Mapping, Sequence, TypeVar, Union, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -1008,7 +1008,7 @@ class Popen(Generic[AnyStr]): def kill(self) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/symbol.pyi b/mypy/typeshed/stdlib/symbol.pyi index 2d3bd83087c7..234c814b55b5 100644 --- a/mypy/typeshed/stdlib/symbol.pyi +++ b/mypy/typeshed/stdlib/symbol.pyi @@ -1,3 +1,5 @@ +import sys + single_input: int file_input: int eval_input: int @@ -84,5 +86,13 @@ comp_if: int encoding_decl: int yield_expr: int yield_arg: int +if sys.version_info >= (3, 7): + sync_comp_for: int +if sys.version_info >= (3, 8): + func_body_suite: int + func_type: int + func_type_input: int + namedexpr_test: int + typelist: int sym_name: dict[int, str] diff --git a/mypy/typeshed/stdlib/symtable.pyi b/mypy/typeshed/stdlib/symtable.pyi index 613ac90ef7a9..bc25a4c4639b 100644 --- a/mypy/typeshed/stdlib/symtable.pyi +++ b/mypy/typeshed/stdlib/symtable.pyi @@ -1,9 +1,9 @@ import sys -from typing import Any, Sequence, Tuple +from typing import Any, Sequence def symtable(code: str, filename: str, compile_type: str) -> SymbolTable: ... -class SymbolTable(object): +class SymbolTable: def __init__(self, raw_table: Any, filename: str) -> None: ... def get_type(self) -> str: ... def get_id(self) -> int: ... @@ -19,19 +19,22 @@ class SymbolTable(object): def get_children(self) -> list[SymbolTable]: ... class Function(SymbolTable): - def get_parameters(self) -> Tuple[str, ...]: ... - def get_locals(self) -> Tuple[str, ...]: ... - def get_globals(self) -> Tuple[str, ...]: ... - def get_frees(self) -> Tuple[str, ...]: ... + def get_parameters(self) -> tuple[str, ...]: ... + def get_locals(self) -> tuple[str, ...]: ... + def get_globals(self) -> tuple[str, ...]: ... + def get_frees(self) -> tuple[str, ...]: ... + if sys.version_info >= (3, 8): + def get_nonlocals(self) -> tuple[str, ...]: ... class Class(SymbolTable): - def get_methods(self) -> Tuple[str, ...]: ... + def get_methods(self) -> tuple[str, ...]: ... -class Symbol(object): +class Symbol: if sys.version_info >= (3, 8): def __init__( self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = ..., *, module_scope: bool = ... ) -> None: ... + def is_nonlocal(self) -> bool: ... else: def __init__(self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = ...) -> None: ... def get_name(self) -> str: ... @@ -48,7 +51,7 @@ class Symbol(object): def get_namespaces(self) -> Sequence[SymbolTable]: ... def get_namespace(self) -> SymbolTable: ... -class SymbolTableFactory(object): +class SymbolTableFactory: def __init__(self) -> None: ... def new(self, table: Any, filename: str) -> SymbolTable: ... def __call__(self, table: Any, filename: str) -> SymbolTable: ... diff --git a/mypy/typeshed/stdlib/sys.pyi b/mypy/typeshed/stdlib/sys.pyi index 274e4b90fd6e..d42e1e0f9ec1 100644 --- a/mypy/typeshed/stdlib/sys.pyi +++ b/mypy/typeshed/stdlib/sys.pyi @@ -1,31 +1,18 @@ import sys +from _typeshed import structseq from builtins import object as _object from importlib.abc import PathEntryFinder from importlib.machinery import ModuleSpec from io import TextIOWrapper from types import FrameType, ModuleType, TracebackType -from typing import ( - Any, - AsyncGenerator, - Callable, - NoReturn, - Optional, - Protocol, - Sequence, - TextIO, - Tuple, - Type, - TypeVar, - Union, - overload, -) -from typing_extensions import Literal +from typing import Any, AsyncGenerator, Callable, NoReturn, Optional, Protocol, Sequence, TextIO, TypeVar, Union, overload +from typing_extensions import Literal, final _T = TypeVar("_T") # The following type alias are stub-only and do not exist during runtime -_ExcInfo = Tuple[Type[BaseException], BaseException, TracebackType] -_OptExcInfo = Union[_ExcInfo, Tuple[None, None, None]] +_ExcInfo = tuple[type[BaseException], BaseException, TracebackType] +_OptExcInfo = Union[_ExcInfo, tuple[None, None, None]] # Intentionally omits one deprecated and one optional method of `importlib.abc.MetaPathFinder` class _MetaPathFinder(Protocol): @@ -44,12 +31,12 @@ if sys.platform == "win32": dllhandle: int dont_write_bytecode: bool displayhook: Callable[[object], Any] -excepthook: Callable[[Type[BaseException], BaseException, TracebackType | None], Any] +excepthook: Callable[[type[BaseException], BaseException, TracebackType | None], Any] exec_prefix: str executable: str -float_repr_style: str +float_repr_style: Literal["short", "legacy"] hexversion: int -last_type: Type[BaseException] | None +last_type: type[BaseException] | None last_value: BaseException | None last_traceback: TracebackType | None maxsize: int @@ -87,49 +74,105 @@ if sys.platform == "win32": winver: str _xoptions: dict[Any, Any] +# Type alias used as a mixin for structseq classes that cannot be instantiated at runtime +# This can't be represented in the type system, so we just use `structseq[Any]` +_uninstantiable_structseq = structseq[Any] + flags: _flags -class _flags: - debug: int - division_warning: int - inspect: int - interactive: int - optimize: int - dont_write_bytecode: int - no_user_site: int - no_site: int - ignore_environment: int - verbose: int - bytes_warning: int - quiet: int - hash_randomization: int +if sys.version_info >= (3, 10): + _FlagTuple = tuple[int, int, int, int, int, int, int, int, int, int, int, int, int, bool, int, int] +elif sys.version_info >= (3, 7): + _FlagTuple = tuple[int, int, int, int, int, int, int, int, int, int, int, int, int, bool, int] +else: + _FlagTuple = tuple[int, int, int, int, int, int, int, int, int, int, int, int, int] + +@final +class _flags(_uninstantiable_structseq, _FlagTuple): + @property + def debug(self) -> int: ... + @property + def inspect(self) -> int: ... + @property + def interactive(self) -> int: ... + @property + def optimize(self) -> int: ... + @property + def dont_write_bytecode(self) -> int: ... + @property + def no_user_site(self) -> int: ... + @property + def no_site(self) -> int: ... + @property + def ignore_environment(self) -> int: ... + @property + def verbose(self) -> int: ... + @property + def bytes_warning(self) -> int: ... + @property + def quiet(self) -> int: ... + @property + def hash_randomization(self) -> int: ... + @property + def isolated(self) -> int: ... if sys.version_info >= (3, 7): - dev_mode: int - utf8_mode: int + @property + def dev_mode(self) -> bool: ... + @property + def utf8_mode(self) -> int: ... + if sys.version_info >= (3, 10): + @property + def warn_default_encoding(self) -> int: ... # undocumented float_info: _float_info -class _float_info: - epsilon: float # DBL_EPSILON - dig: int # DBL_DIG - mant_dig: int # DBL_MANT_DIG - max: float # DBL_MAX - max_exp: int # DBL_MAX_EXP - max_10_exp: int # DBL_MAX_10_EXP - min: float # DBL_MIN - min_exp: int # DBL_MIN_EXP - min_10_exp: int # DBL_MIN_10_EXP - radix: int # FLT_RADIX - rounds: int # FLT_ROUNDS +@final +class _float_info(structseq[float], tuple[float, int, int, float, int, int, int, int, float, int, int]): + @property + def max(self) -> float: ... # DBL_MAX + @property + def max_exp(self) -> int: ... # DBL_MAX_EXP + @property + def max_10_exp(self) -> int: ... # DBL_MAX_10_EXP + @property + def min(self) -> float: ... # DBL_MIN + @property + def min_exp(self) -> int: ... # DBL_MIN_EXP + @property + def min_10_exp(self) -> int: ... # DBL_MIN_10_EXP + @property + def dig(self) -> int: ... # DBL_DIG + @property + def mant_dig(self) -> int: ... # DBL_MANT_DIG + @property + def epsilon(self) -> float: ... # DBL_EPSILON + @property + def radix(self) -> int: ... # FLT_RADIX + @property + def rounds(self) -> int: ... # FLT_ROUNDS hash_info: _hash_info -class _hash_info: - width: int - modulus: int - inf: int - nan: int - imag: int +@final +class _hash_info(structseq[Any | int], tuple[int, int, int, int, int, str, int, int, int]): + @property + def width(self) -> int: ... + @property + def modulus(self) -> int: ... + @property + def inf(self) -> int: ... + @property + def nan(self) -> int: ... + @property + def imag(self) -> int: ... + @property + def algorithm(self) -> str: ... + @property + def hash_bits(self) -> int: ... + @property + def seed_bits(self) -> int: ... + @property + def cutoff(self) -> int: ... # undocumented implementation: _implementation @@ -138,20 +181,32 @@ class _implementation: version: _version_info hexversion: int cache_tag: str - _multiarch: str + # Define __getattr__, as the documentation states: + # > sys.implementation may contain additional attributes specific to the Python implementation. + # > These non-standard attributes must start with an underscore, and are not described here. + def __getattr__(self, name: str) -> Any: ... int_info: _int_info -class _int_info: - bits_per_digit: int - sizeof_digit: int - -class _version_info(Tuple[int, int, int, str, int]): - major: int - minor: int - micro: int - releaselevel: str - serial: int +@final +class _int_info(structseq[int], tuple[int, int]): + @property + def bits_per_digit(self) -> int: ... + @property + def sizeof_digit(self) -> int: ... + +@final +class _version_info(_uninstantiable_structseq, tuple[int, int, int, str, int]): + @property + def major(self) -> int: ... + @property + def minor(self) -> int: ... + @property + def micro(self) -> int: ... + @property + def releaselevel(self) -> str: ... + @property + def serial(self) -> int: ... version_info: _version_info @@ -161,7 +216,7 @@ def _current_frames() -> dict[int, FrameType]: ... def _getframe(__depth: int = ...) -> FrameType: ... def _debugmallocstats() -> None: ... def __displayhook__(value: object) -> None: ... -def __excepthook__(type_: Type[BaseException], value: BaseException, traceback: TracebackType) -> None: ... +def __excepthook__(type_: type[BaseException], value: BaseException, traceback: TracebackType | None) -> None: ... def exc_info() -> _OptExcInfo: ... # sys.exit() accepts an optional argument of anything printable @@ -192,19 +247,30 @@ _TraceFunc = Callable[[FrameType, str, Any], Optional[Callable[[FrameType, str, def gettrace() -> _TraceFunc | None: ... def settrace(tracefunc: _TraceFunc | None) -> None: ... -class _WinVersion(Tuple[int, int, int, int, str, int, int, int, int, Tuple[int, int, int]]): - major: int - minor: int - build: int - platform: int - service_pack: str - service_pack_minor: int - service_pack_major: int - suite_mast: int - product_type: int - platform_version: tuple[int, int, int] - if sys.platform == "win32": + # A tuple of length 5, even though it has more than 5 attributes. + @final + class _WinVersion(_uninstantiable_structseq, tuple[int, int, int, int, str]): + @property + def major(self) -> int: ... + @property + def minor(self) -> int: ... + @property + def build(self) -> int: ... + @property + def platform(self) -> int: ... + @property + def service_pack(self) -> str: ... + @property + def service_pack_minor(self) -> int: ... + @property + def service_pack_major(self) -> int: ... + @property + def suite_mask(self) -> int: ... + @property + def product_type(self) -> int: ... + @property + def platform_version(self) -> tuple[int, int, int]: ... def getwindowsversion() -> _WinVersion: ... def intern(__string: str) -> str: ... @@ -226,22 +292,25 @@ if sys.version_info < (3, 9): def setcheckinterval(__n: int) -> None: ... # deprecated if sys.version_info >= (3, 8): - # not exported by sys + # Doesn't exist at runtime, but exported in the stubs so pytest etc. can annotate their code more easily. class UnraisableHookArgs: - exc_type: Type[BaseException] + exc_type: type[BaseException] exc_value: BaseException | None exc_traceback: TracebackType | None err_msg: str | None object: _object | None unraisablehook: Callable[[UnraisableHookArgs], Any] - def addaudithook(hook: Callable[[str, Tuple[Any, ...]], Any]) -> None: ... + def addaudithook(hook: Callable[[str, tuple[Any, ...]], Any]) -> None: ... def audit(__event: str, *args: Any) -> None: ... _AsyncgenHook = Optional[Callable[[AsyncGenerator[Any, Any]], None]] -class _asyncgen_hooks(Tuple[_AsyncgenHook, _AsyncgenHook]): - firstiter: _AsyncgenHook - finalizer: _AsyncgenHook +@final +class _asyncgen_hooks(structseq[_AsyncgenHook], tuple[_AsyncgenHook, _AsyncgenHook]): + @property + def firstiter(self) -> _AsyncgenHook: ... + @property + def finalizer(self) -> _AsyncgenHook: ... def get_asyncgen_hooks() -> _asyncgen_hooks: ... def set_asyncgen_hooks(firstiter: _AsyncgenHook = ..., finalizer: _AsyncgenHook = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/sysconfig.pyi b/mypy/typeshed/stdlib/sysconfig.pyi index ff828d519912..17077144f6e9 100644 --- a/mypy/typeshed/stdlib/sysconfig.pyi +++ b/mypy/typeshed/stdlib/sysconfig.pyi @@ -1,12 +1,12 @@ -from typing import IO, Any, Tuple, overload +from typing import IO, Any, overload def get_config_var(name: str) -> str | None: ... @overload def get_config_vars() -> dict[str, Any]: ... @overload def get_config_vars(arg: str, *args: str) -> list[Any]: ... -def get_scheme_names() -> Tuple[str, ...]: ... -def get_path_names() -> Tuple[str, ...]: ... +def get_scheme_names() -> tuple[str, ...]: ... +def get_path_names() -> tuple[str, ...]: ... def get_path(name: str, scheme: str = ..., vars: dict[str, Any] | None = ..., expand: bool = ...) -> str: ... def get_paths(scheme: str = ..., vars: dict[str, Any] | None = ..., expand: bool = ...) -> dict[str, str]: ... def get_python_version() -> str: ... diff --git a/mypy/typeshed/stdlib/syslog.pyi b/mypy/typeshed/stdlib/syslog.pyi index 49169f40db5c..cfa8df887c1b 100644 --- a/mypy/typeshed/stdlib/syslog.pyi +++ b/mypy/typeshed/stdlib/syslog.pyi @@ -1,43 +1,47 @@ +import sys from typing import overload +from typing_extensions import Literal -LOG_ALERT: int -LOG_AUTH: int -LOG_CONS: int -LOG_CRIT: int -LOG_CRON: int -LOG_DAEMON: int -LOG_DEBUG: int -LOG_EMERG: int -LOG_ERR: int -LOG_INFO: int -LOG_KERN: int -LOG_LOCAL0: int -LOG_LOCAL1: int -LOG_LOCAL2: int -LOG_LOCAL3: int -LOG_LOCAL4: int -LOG_LOCAL5: int -LOG_LOCAL6: int -LOG_LOCAL7: int -LOG_LPR: int -LOG_MAIL: int -LOG_NDELAY: int -LOG_NEWS: int -LOG_NOTICE: int -LOG_NOWAIT: int -LOG_PERROR: int -LOG_PID: int -LOG_SYSLOG: int -LOG_USER: int -LOG_UUCP: int -LOG_WARNING: int - -def LOG_MASK(a: int) -> int: ... -def LOG_UPTO(a: int) -> int: ... -def closelog() -> None: ... -def openlog(ident: str = ..., logoption: int = ..., facility: int = ...) -> None: ... -def setlogmask(x: int) -> int: ... -@overload -def syslog(priority: int, message: str) -> None: ... -@overload -def syslog(message: str) -> None: ... +if sys.platform != "win32": + LOG_ALERT: Literal[1] + LOG_AUTH: Literal[32] + LOG_AUTHPRIV: Literal[80] + LOG_CONS: Literal[2] + LOG_CRIT: Literal[2] + LOG_CRON: Literal[72] + LOG_DAEMON: Literal[24] + LOG_DEBUG: Literal[7] + LOG_EMERG: Literal[0] + LOG_ERR: Literal[3] + LOG_INFO: Literal[6] + LOG_KERN: Literal[0] + LOG_LOCAL0: Literal[128] + LOG_LOCAL1: Literal[136] + LOG_LOCAL2: Literal[144] + LOG_LOCAL3: Literal[152] + LOG_LOCAL4: Literal[160] + LOG_LOCAL5: Literal[168] + LOG_LOCAL6: Literal[176] + LOG_LOCAL7: Literal[184] + LOG_LPR: Literal[48] + LOG_MAIL: Literal[16] + LOG_NDELAY: Literal[8] + LOG_NEWS: Literal[56] + LOG_NOTICE: Literal[5] + LOG_NOWAIT: Literal[16] + LOG_ODELAY: Literal[4] + LOG_PERROR: Literal[32] + LOG_PID: Literal[1] + LOG_SYSLOG: Literal[40] + LOG_USER: Literal[8] + LOG_UUCP: Literal[64] + LOG_WARNING: Literal[4] + def LOG_MASK(a: int) -> int: ... + def LOG_UPTO(a: int) -> int: ... + def closelog() -> None: ... + def openlog(ident: str = ..., logoption: int = ..., facility: int = ...) -> None: ... + def setlogmask(x: int) -> int: ... + @overload + def syslog(priority: int, message: str) -> None: ... + @overload + def syslog(message: str) -> None: ... diff --git a/mypy/typeshed/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi index 0134316d8107..c98608d49693 100644 --- a/mypy/typeshed/stdlib/tarfile.pyi +++ b/mypy/typeshed/stdlib/tarfile.pyi @@ -5,11 +5,9 @@ from _typeshed import Self, StrOrBytesPath, StrPath from collections.abc import Callable, Iterable, Iterator, Mapping from gzip import _ReadableFileobj as _GzipReadableFileobj, _WritableFileobj as _GzipWritableFileobj from types import TracebackType -from typing import IO, Protocol, Tuple, Type, TypeVar, overload +from typing import IO, Protocol, overload from typing_extensions import Literal -_TF = TypeVar("_TF", bound=TarFile) - class _Fileobj(Protocol): def read(self, __size: int) -> bytes: ... def write(self, __b: bytes) -> object: ... @@ -62,10 +60,10 @@ DEFAULT_FORMAT: int # tarfile constants -SUPPORTED_TYPES: Tuple[bytes, ...] -REGULAR_TYPES: Tuple[bytes, ...] -GNU_TYPES: Tuple[bytes, ...] -PAX_FIELDS: Tuple[str, ...] +SUPPORTED_TYPES: tuple[bytes, ...] +REGULAR_TYPES: tuple[bytes, ...] +GNU_TYPES: tuple[bytes, ...] +PAX_FIELDS: tuple[str, ...] PAX_NUMBER_FIELDS: dict[str, type] PAX_NAME_FIELDS: set[str] @@ -78,7 +76,7 @@ def open( bufsize: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -100,12 +98,12 @@ class TarFile: mode: Literal["r", "a", "w", "x"] fileobj: _Fileobj | None format: int | None - tarinfo: Type[TarInfo] + tarinfo: type[TarInfo] dereference: bool | None ignore_zeros: bool | None encoding: str | None errors: str - fileobject: Type[ExFileObject] + fileobject: type[ExFileObject] pax_headers: Mapping[str, str] | None debug: int | None errorlevel: int | None @@ -116,7 +114,7 @@ class TarFile: mode: Literal["r", "a", "w", "x"] = ..., fileobj: _Fileobj | None = ..., format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -128,19 +126,19 @@ class TarFile: ) -> 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 __iter__(self) -> Iterator[TarInfo]: ... @classmethod def open( - cls: Type[_TF], + cls: type[Self], name: StrOrBytesPath | None = ..., mode: str = ..., fileobj: IO[bytes] | None = ..., # depends on mode bufsize: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., @@ -148,113 +146,113 @@ class TarFile: pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @classmethod def taropen( - cls: Type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["r", "a", "w", "x"] = ..., fileobj: _Fileobj | None = ..., *, compresslevel: int = ..., format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @overload @classmethod def gzopen( - cls: Type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["r"] = ..., fileobj: _GzipReadableFileobj | None = ..., compresslevel: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @overload @classmethod def gzopen( - cls: Type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["w", "x"], fileobj: _GzipWritableFileobj | None = ..., compresslevel: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @overload @classmethod def bz2open( - cls: Type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["w", "x"], fileobj: _Bz2WritableFileobj | None = ..., compresslevel: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @overload @classmethod def bz2open( - cls: Type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["r"] = ..., fileobj: _Bz2ReadableFileobj | None = ..., compresslevel: int = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... @classmethod def xzopen( - cls: Type[_TF], + cls: type[Self], name: StrOrBytesPath | None, mode: Literal["r", "w", "x"] = ..., fileobj: IO[bytes] | None = ..., preset: int | None = ..., *, format: int | None = ..., - tarinfo: Type[TarInfo] | None = ..., + tarinfo: type[TarInfo] | None = ..., dereference: bool | None = ..., ignore_zeros: bool | None = ..., encoding: str | None = ..., pax_headers: Mapping[str, str] | None = ..., debug: int | None = ..., errorlevel: int | None = ..., - ) -> _TF: ... + ) -> Self: ... def getmember(self, name: str) -> TarInfo: ... def getmembers(self) -> _list[TarInfo]: ... def getnames(self) -> _list[str]: ... diff --git a/mypy/typeshed/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi index 119c111bc4e1..9b5e2bb82539 100644 --- a/mypy/typeshed/stdlib/tempfile.pyi +++ b/mypy/typeshed/stdlib/tempfile.pyi @@ -2,7 +2,7 @@ import os import sys from _typeshed import Self from types import TracebackType -from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, Tuple, Type, Union, overload +from typing import IO, Any, AnyStr, Generic, Iterable, Iterator, Union, overload from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -169,7 +169,7 @@ class _TemporaryFileWrapper(Generic[AnyStr], IO[AnyStr]): delete: bool def __init__(self, file: IO[AnyStr], name: str, delete: bool = ...) -> None: ... def __enter__(self: Self) -> Self: ... - def __exit__(self, exc: Type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> bool | None: ... + def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> bool | None: ... def __getattr__(self, name: str) -> Any: ... def close(self) -> None: ... # These methods don't exist directly on this object, but @@ -206,7 +206,7 @@ class SpooledTemporaryFile(IO[AnyStr]): @property def encoding(self) -> str: ... # undocumented @property - def newlines(self) -> str | Tuple[str, ...] | None: ... # undocumented + def newlines(self) -> str | tuple[str, ...] | None: ... # undocumented # bytes needs to go first, as default mode is to open as bytes if sys.version_info >= (3, 8): @overload @@ -293,7 +293,7 @@ class SpooledTemporaryFile(IO[AnyStr]): def rollover(self) -> 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 ) -> bool | None: ... # These methods are copied from the abstract methods of IO, because # SpooledTemporaryFile implements IO. @@ -346,7 +346,7 @@ class TemporaryDirectory(Generic[AnyStr]): def cleanup(self) -> None: ... def __enter__(self) -> AnyStr: ... 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: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/termios.pyi b/mypy/typeshed/stdlib/termios.pyi index ed8522dccc51..7142df15715d 100644 --- a/mypy/typeshed/stdlib/termios.pyi +++ b/mypy/typeshed/stdlib/termios.pyi @@ -1,246 +1,246 @@ +import sys from _typeshed import FileDescriptorLike -from typing import Any, List, Union +from typing import Any, Union -_Attr = List[Union[int, List[Union[bytes, int]]]] +if sys.platform != "win32": + _Attr = list[Union[int, list[Union[bytes, int]]]] -# TODO constants not really documented -B0: int -B1000000: int -B110: int -B115200: int -B1152000: int -B1200: int -B134: int -B150: int -B1500000: int -B1800: int -B19200: int -B200: int -B2000000: int -B230400: int -B2400: int -B2500000: int -B300: int -B3000000: int -B3500000: int -B38400: int -B4000000: int -B460800: int -B4800: int -B50: int -B500000: int -B57600: int -B576000: int -B600: int -B75: int -B921600: int -B9600: int -BRKINT: int -BS0: int -BS1: int -BSDLY: int -CBAUD: int -CBAUDEX: int -CDSUSP: int -CEOF: int -CEOL: int -CEOT: int -CERASE: int -CFLUSH: int -CIBAUD: int -CINTR: int -CKILL: int -CLNEXT: int -CLOCAL: int -CQUIT: int -CR0: int -CR1: int -CR2: int -CR3: int -CRDLY: int -CREAD: int -CRPRNT: int -CRTSCTS: int -CS5: int -CS6: int -CS7: int -CS8: int -CSIZE: int -CSTART: int -CSTOP: int -CSTOPB: int -CSUSP: int -CWERASE: int -ECHO: int -ECHOCTL: int -ECHOE: int -ECHOK: int -ECHOKE: int -ECHONL: int -ECHOPRT: int -EXTA: int -EXTB: int -FF0: int -FF1: int -FFDLY: int -FIOASYNC: int -FIOCLEX: int -FIONBIO: int -FIONCLEX: int -FIONREAD: int -FLUSHO: int -HUPCL: int -ICANON: int -ICRNL: int -IEXTEN: int -IGNBRK: int -IGNCR: int -IGNPAR: int -IMAXBEL: int -INLCR: int -INPCK: int -IOCSIZE_MASK: int -IOCSIZE_SHIFT: int -ISIG: int -ISTRIP: int -IUCLC: int -IXANY: int -IXOFF: int -IXON: int -NCC: int -NCCS: int -NL0: int -NL1: int -NLDLY: int -NOFLSH: int -N_MOUSE: int -N_PPP: int -N_SLIP: int -N_STRIP: int -N_TTY: int -OCRNL: int -OFDEL: int -OFILL: int -OLCUC: int -ONLCR: int -ONLRET: int -ONOCR: int -OPOST: int -PARENB: int -PARMRK: int -PARODD: int -PENDIN: int -TAB0: int -TAB1: int -TAB2: int -TAB3: int -TABDLY: int -TCFLSH: int -TCGETA: int -TCGETS: int -TCIFLUSH: int -TCIOFF: int -TCIOFLUSH: int -TCION: int -TCOFLUSH: int -TCOOFF: int -TCOON: int -TCSADRAIN: int -TCSAFLUSH: int -TCSANOW: int -TCSBRK: int -TCSBRKP: int -TCSETA: int -TCSETAF: int -TCSETAW: int -TCSETS: int -TCSETSF: int -TCSETSW: int -TCXONC: int -TIOCCONS: int -TIOCEXCL: int -TIOCGETD: int -TIOCGICOUNT: int -TIOCGLCKTRMIOS: int -TIOCGPGRP: int -TIOCGSERIAL: int -TIOCGSOFTCAR: int -TIOCGWINSZ: int -TIOCINQ: int -TIOCLINUX: int -TIOCMBIC: int -TIOCMBIS: int -TIOCMGET: int -TIOCMIWAIT: int -TIOCMSET: int -TIOCM_CAR: int -TIOCM_CD: int -TIOCM_CTS: int -TIOCM_DSR: int -TIOCM_DTR: int -TIOCM_LE: int -TIOCM_RI: int -TIOCM_RNG: int -TIOCM_RTS: int -TIOCM_SR: int -TIOCM_ST: int -TIOCNOTTY: int -TIOCNXCL: int -TIOCOUTQ: int -TIOCPKT: int -TIOCPKT_DATA: int -TIOCPKT_DOSTOP: int -TIOCPKT_FLUSHREAD: int -TIOCPKT_FLUSHWRITE: int -TIOCPKT_NOSTOP: int -TIOCPKT_START: int -TIOCPKT_STOP: int -TIOCSCTTY: int -TIOCSERCONFIG: int -TIOCSERGETLSR: int -TIOCSERGETMULTI: int -TIOCSERGSTRUCT: int -TIOCSERGWILD: int -TIOCSERSETMULTI: int -TIOCSERSWILD: int -TIOCSER_TEMT: int -TIOCSETD: int -TIOCSLCKTRMIOS: int -TIOCSPGRP: int -TIOCSSERIAL: int -TIOCSSOFTCAR: int -TIOCSTI: int -TIOCSWINSZ: int -TOSTOP: int -VDISCARD: int -VEOF: int -VEOL: int -VEOL2: int -VERASE: int -VINTR: int -VKILL: int -VLNEXT: int -VMIN: int -VQUIT: int -VREPRINT: int -VSTART: int -VSTOP: int -VSUSP: int -VSWTC: int -VSWTCH: int -VT0: int -VT1: int -VTDLY: int -VTIME: int -VWERASE: int -XCASE: int -XTABS: int - -def tcgetattr(__fd: FileDescriptorLike) -> list[Any]: ... -def tcsetattr(__fd: FileDescriptorLike, __when: int, __attributes: _Attr) -> None: ... -def tcsendbreak(__fd: FileDescriptorLike, __duration: int) -> None: ... -def tcdrain(__fd: FileDescriptorLike) -> None: ... -def tcflush(__fd: FileDescriptorLike, __queue: int) -> None: ... -def tcflow(__fd: FileDescriptorLike, __action: int) -> None: ... - -class error(Exception): ... + # TODO constants not really documented + B0: int + B1000000: int + B110: int + B115200: int + B1152000: int + B1200: int + B134: int + B150: int + B1500000: int + B1800: int + B19200: int + B200: int + B2000000: int + B230400: int + B2400: int + B2500000: int + B300: int + B3000000: int + B3500000: int + B38400: int + B4000000: int + B460800: int + B4800: int + B50: int + B500000: int + B57600: int + B576000: int + B600: int + B75: int + B921600: int + B9600: int + BRKINT: int + BS0: int + BS1: int + BSDLY: int + CBAUD: int + CBAUDEX: int + CDSUSP: int + CEOF: int + CEOL: int + CEOT: int + CERASE: int + CFLUSH: int + CIBAUD: int + CINTR: int + CKILL: int + CLNEXT: int + CLOCAL: int + CQUIT: int + CR0: int + CR1: int + CR2: int + CR3: int + CRDLY: int + CREAD: int + CRPRNT: int + CRTSCTS: int + CS5: int + CS6: int + CS7: int + CS8: int + CSIZE: int + CSTART: int + CSTOP: int + CSTOPB: int + CSUSP: int + CWERASE: int + ECHO: int + ECHOCTL: int + ECHOE: int + ECHOK: int + ECHOKE: int + ECHONL: int + ECHOPRT: int + EXTA: int + EXTB: int + FF0: int + FF1: int + FFDLY: int + FIOASYNC: int + FIOCLEX: int + FIONBIO: int + FIONCLEX: int + FIONREAD: int + FLUSHO: int + HUPCL: int + ICANON: int + ICRNL: int + IEXTEN: int + IGNBRK: int + IGNCR: int + IGNPAR: int + IMAXBEL: int + INLCR: int + INPCK: int + IOCSIZE_MASK: int + IOCSIZE_SHIFT: int + ISIG: int + ISTRIP: int + IUCLC: int + IXANY: int + IXOFF: int + IXON: int + NCC: int + NCCS: int + NL0: int + NL1: int + NLDLY: int + NOFLSH: int + N_MOUSE: int + N_PPP: int + N_SLIP: int + N_STRIP: int + N_TTY: int + OCRNL: int + OFDEL: int + OFILL: int + OLCUC: int + ONLCR: int + ONLRET: int + ONOCR: int + OPOST: int + PARENB: int + PARMRK: int + PARODD: int + PENDIN: int + TAB0: int + TAB1: int + TAB2: int + TAB3: int + TABDLY: int + TCFLSH: int + TCGETA: int + TCGETS: int + TCIFLUSH: int + TCIOFF: int + TCIOFLUSH: int + TCION: int + TCOFLUSH: int + TCOOFF: int + TCOON: int + TCSADRAIN: int + TCSAFLUSH: int + TCSANOW: int + TCSBRK: int + TCSBRKP: int + TCSETA: int + TCSETAF: int + TCSETAW: int + TCSETS: int + TCSETSF: int + TCSETSW: int + TCXONC: int + TIOCCONS: int + TIOCEXCL: int + TIOCGETD: int + TIOCGICOUNT: int + TIOCGLCKTRMIOS: int + TIOCGPGRP: int + TIOCGSERIAL: int + TIOCGSOFTCAR: int + TIOCGWINSZ: int + TIOCINQ: int + TIOCLINUX: int + TIOCMBIC: int + TIOCMBIS: int + TIOCMGET: int + TIOCMIWAIT: int + TIOCMSET: int + TIOCM_CAR: int + TIOCM_CD: int + TIOCM_CTS: int + TIOCM_DSR: int + TIOCM_DTR: int + TIOCM_LE: int + TIOCM_RI: int + TIOCM_RNG: int + TIOCM_RTS: int + TIOCM_SR: int + TIOCM_ST: int + TIOCNOTTY: int + TIOCNXCL: int + TIOCOUTQ: int + TIOCPKT: int + TIOCPKT_DATA: int + TIOCPKT_DOSTOP: int + TIOCPKT_FLUSHREAD: int + TIOCPKT_FLUSHWRITE: int + TIOCPKT_NOSTOP: int + TIOCPKT_START: int + TIOCPKT_STOP: int + TIOCSCTTY: int + TIOCSERCONFIG: int + TIOCSERGETLSR: int + TIOCSERGETMULTI: int + TIOCSERGSTRUCT: int + TIOCSERGWILD: int + TIOCSERSETMULTI: int + TIOCSERSWILD: int + TIOCSER_TEMT: int + TIOCSETD: int + TIOCSLCKTRMIOS: int + TIOCSPGRP: int + TIOCSSERIAL: int + TIOCSSOFTCAR: int + TIOCSTI: int + TIOCSWINSZ: int + TOSTOP: int + VDISCARD: int + VEOF: int + VEOL: int + VEOL2: int + VERASE: int + VINTR: int + VKILL: int + VLNEXT: int + VMIN: int + VQUIT: int + VREPRINT: int + VSTART: int + VSTOP: int + VSUSP: int + VSWTC: int + VSWTCH: int + VT0: int + VT1: int + VTDLY: int + VTIME: int + VWERASE: int + XCASE: int + XTABS: int + def tcgetattr(__fd: FileDescriptorLike) -> list[Any]: ... + def tcsetattr(__fd: FileDescriptorLike, __when: int, __attributes: _Attr) -> None: ... + def tcsendbreak(__fd: FileDescriptorLike, __duration: int) -> None: ... + def tcdrain(__fd: FileDescriptorLike) -> None: ... + def tcflush(__fd: FileDescriptorLike, __queue: int) -> None: ... + def tcflow(__fd: FileDescriptorLike, __action: int) -> None: ... + class error(Exception): ... diff --git a/mypy/typeshed/stdlib/threading.pyi b/mypy/typeshed/stdlib/threading.pyi index 64998d86bf9f..10853ff875b2 100644 --- a/mypy/typeshed/stdlib/threading.pyi +++ b/mypy/typeshed/stdlib/threading.pyi @@ -1,6 +1,6 @@ import sys from types import FrameType, TracebackType -from typing import Any, Callable, Iterable, Mapping, Optional, Type, TypeVar +from typing import Any, Callable, Iterable, Mapping, Optional, TypeVar # TODO recursive type _TF = Callable[[FrameType, str, Any], Optional[Callable[..., Any]]] @@ -11,8 +11,9 @@ _T = TypeVar("_T") __all__: list[str] def active_count() -> int: ... +def activeCount() -> int: ... # deprecated alias for active_count() def current_thread() -> Thread: ... -def currentThread() -> Thread: ... +def currentThread() -> Thread: ... # deprecated alias for current_thread() def get_ident() -> int: ... def enumerate() -> list[Thread]: ... def main_thread() -> Thread: ... @@ -22,13 +23,18 @@ if sys.version_info >= (3, 8): def settrace(func: _TF) -> None: ... def setprofile(func: _PF | None) -> None: ... + +if sys.version_info >= (3, 10): + def gettrace() -> _TF | None: ... + def getprofile() -> _PF | None: ... + def stack_size(size: int = ...) -> int: ... TIMEOUT_MAX: float class ThreadError(Exception): ... -class local(object): +class local: def __getattribute__(self, name: str) -> Any: ... def __setattr__(self, name: str, value: Any) -> None: ... def __delattr__(self, name: str) -> None: ... @@ -50,24 +56,26 @@ class Thread: def start(self) -> None: ... def run(self) -> None: ... def join(self, timeout: float | None = ...) -> None: ... - def getName(self) -> str: ... - def setName(self, name: str) -> None: ... if sys.version_info >= (3, 8): @property def native_id(self) -> int | None: ... # only available on some platforms def is_alive(self) -> bool: ... if sys.version_info < (3, 9): def isAlive(self) -> bool: ... + # the following methods are all deprecated + def getName(self) -> str: ... + def setName(self, name: str) -> None: ... def isDaemon(self) -> bool: ... def setDaemon(self, daemonic: bool) -> None: ... -class _DummyThread(Thread): ... +class _DummyThread(Thread): + def __init__(self) -> None: ... class Lock: def __init__(self) -> None: ... def __enter__(self) -> bool: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... @@ -75,12 +83,12 @@ class Lock: class _RLock: def __init__(self) -> None: ... - def __enter__(self) -> bool: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... + __enter__ = acquire + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> bool | None: ... RLock = _RLock @@ -88,7 +96,7 @@ class Condition: def __init__(self, lock: Lock | _RLock | None = ...) -> None: ... def __enter__(self) -> bool: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... def release(self) -> None: ... @@ -96,12 +104,12 @@ class Condition: def wait_for(self, predicate: Callable[[], _T], timeout: float | None = ...) -> _T: ... def notify(self, n: int = ...) -> None: ... def notify_all(self) -> None: ... - def notifyAll(self) -> None: ... + def notifyAll(self) -> None: ... # deprecated alias for notify_all() class Semaphore: def __init__(self, value: int = ...) -> None: ... 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 ) -> bool | None: ... def acquire(self, blocking: bool = ..., timeout: float | None = ...) -> bool: ... def __enter__(self, blocking: bool = ..., timeout: float | None = ...) -> bool: ... @@ -115,6 +123,7 @@ class BoundedSemaphore(Semaphore): ... class Event: def __init__(self) -> None: ... def is_set(self) -> bool: ... + def isSet(self) -> bool: ... # deprecated alias for is_set() def set(self) -> None: ... def clear(self) -> None: ... def wait(self, timeout: float | None = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi index bf370d68e83d..6e23b331d1c8 100644 --- a/mypy/typeshed/stdlib/time.pyi +++ b/mypy/typeshed/stdlib/time.pyi @@ -1,9 +1,10 @@ import sys +from _typeshed import structseq from types import SimpleNamespace -from typing import Any, NamedTuple, Tuple +from typing import Any, Union from typing_extensions import final -_TimeTuple = Tuple[int, int, int, int, int, int, int, int, int] +_TimeTuple = tuple[int, int, int, int, int, int, int, int, int] altzone: int daylight: int @@ -32,39 +33,31 @@ if sys.version_info >= (3, 8) and sys.platform == "darwin": if sys.version_info >= (3, 9) and sys.platform == "linux": CLOCK_TAI: int -class _struct_time(NamedTuple): - tm_year: int - tm_mon: int - tm_mday: int - tm_hour: int - tm_min: int - tm_sec: int - tm_wday: int - tm_yday: int - tm_isdst: int +# Constructor takes an iterable of any type, of length between 9 and 11 elements. +# However, it always *behaves* like a tuple of 9 elements, +# even if an iterable with length >9 is passed. +# https://github.com/python/typeshed/pull/6560#discussion_r767162532 +@final +class struct_time(structseq[Union[Any, int]], _TimeTuple): @property - def n_fields(self) -> int: ... + def tm_year(self) -> int: ... @property - def n_sequence_fields(self) -> int: ... + def tm_mon(self) -> int: ... @property - def n_unnamed_fields(self) -> int: ... - -@final -class struct_time(_struct_time): - def __init__( - self, - o: tuple[int, int, int, int, int, int, int, int, int] - | tuple[int, int, int, int, int, int, int, int, int, str] - | tuple[int, int, int, int, int, int, int, int, int, str, int], - _arg: Any = ..., - ) -> None: ... - def __new__( - cls, - o: tuple[int, int, int, int, int, int, int, int, int] - | tuple[int, int, int, int, int, int, int, int, int, str] - | tuple[int, int, int, int, int, int, int, int, int, str, int], - _arg: Any = ..., - ) -> struct_time: ... + def tm_mday(self) -> int: ... + @property + def tm_hour(self) -> int: ... + @property + def tm_min(self) -> int: ... + @property + def tm_sec(self) -> int: ... + @property + def tm_wday(self) -> int: ... + @property + def tm_yday(self) -> int: ... + @property + def tm_isdst(self) -> int: ... + # These final two properties only exist if a 10- or 11-item sequence was passed to the constructor. @property def tm_zone(self) -> str: ... @property diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index bda37b406fc3..bac6fe4d6824 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -2,10 +2,10 @@ import _tkinter import sys from _typeshed import StrOrBytesPath from enum import Enum -from tkinter.constants import * # comment this out to find undefined identifier names with flake8 +from tkinter.constants import * from tkinter.font import _FontDescription from types import TracebackType -from typing import Any, Callable, Generic, List, Mapping, Optional, Protocol, Sequence, Tuple, Type, TypeVar, Union, overload +from typing import Any, Callable, Generic, Mapping, Optional, Protocol, Sequence, TypeVar, Union, overload from typing_extensions import Literal, TypedDict # Using anything from tkinter.font in this file means that 'import tkinter' @@ -24,93 +24,46 @@ EXCEPTION = _tkinter.EXCEPTION # - Misc: any widget (don't use BaseWidget because Tk doesn't inherit from BaseWidget) # - Widget: anything that is meant to be put into another widget with e.g. pack or grid # -# Instructions for figuring out the correct type of each widget option: -# - See discussion on #4363. +# Don't trust tkinter's docstrings, because they have been created by copy/pasting from +# Tk's manual pages more than 10 years ago. Use the latest manual pages instead: # -# - Find the option from the manual page of the widget. Usually the manual -# page of a non-ttk widget has the same name as the tkinter class, in the -# 3tk section: +# $ sudo apt install tk-doc tcl-doc +# $ man 3tk label # tkinter.Label +# $ man 3tk ttk_label # tkinter.ttk.Label +# $ man 3tcl after # tkinter.Misc.after # -# $ sudo apt install tk-doc -# $ man 3tk label -# -# Ttk manual pages tend to have ttk_ prefixed names: -# -# $ man 3tk ttk_label -# -# Non-GUI things like the .after() method are often in the 3tcl section: -# -# $ sudo apt install tcl-doc -# $ man 3tcl after -# -# If you don't have man or apt, you can read these manual pages online: -# -# https://www.tcl.tk/doc/ -# -# Every option has '-' in front of its name in the manual page (and in Tcl). -# For example, there's an option named '-text' in the label manual page. -# -# - Tkinter has some options documented in docstrings, but don't rely on them. -# They aren't updated when a new version of Tk comes out, so the latest Tk -# manual pages (see above) are much more likely to actually contain all -# possible options. -# -# Also, reading tkinter's source code typically won't help much because it -# uses a lot of **kwargs and duck typing. Typically every argument goes into -# self.tk.call, which is _tkinter.TkappType.call, and the return value is -# whatever that returns. The type of that depends on how the Tcl interpreter -# represents the return value of the executed Tcl code. -# -# - If you think that int is an appropriate type for something, then you may -# actually want _ScreenUnits instead. -# -# - If you think that Callable[something] is an appropriate type for -# something, then you may actually want Callable[something] | str, -# because it's often possible to specify a string of Tcl code. -# -# - If you think the correct type is Iterable[Foo] or Sequence[Foo], it is -# probably list[Foo] | tuple[Foo, ...], disallowing other sequences such -# as deques: -# -# >>> tkinter.Label(font=('Helvetica', 12, collections.deque(['bold']))) -# Traceback (most recent call last): -# ... -# _tkinter.TclError: unknown font style "deque(['bold'])" -# -# - Some options can be set only in __init__, but all options are available -# when getting their values with configure's return value or cget. -# -# - Asks other tkinter users if you haven't worked much with tkinter. +# You can also read the manual pages online: https://www.tcl.tk/doc/ # Some widgets have an option named -compound that accepts different values # than the _Compound defined here. Many other options have similar things. _Anchor = Literal["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"] # manual page: Tk_GetAnchor _Bitmap = str # manual page: Tk_GetBitmap -_ButtonCommand = Union[str, Callable[[], Any]] # return value is returned from Button.invoke() +_ButtonCommand = Union[str, Callable[[], Any]] # accepts string of tcl code, return value is returned from Button.invoke() _CanvasItemId = int _Color = str # typically '#rrggbb', '#rgb' or color names. _Compound = Literal["top", "left", "center", "right", "bottom", "none"] # -compound in manual page named 'options' -_Cursor = Union[str, Tuple[str], Tuple[str, str], Tuple[str, str, str], Tuple[str, str, str, str]] # manual page: Tk_GetCursor +_Cursor = Union[str, tuple[str], tuple[str, str], tuple[str, str, str], tuple[str, str, str, str]] # manual page: Tk_GetCursor _EntryValidateCommand = Union[ - Callable[[], bool], str, List[str], Tuple[str, ...] + Callable[[], bool], str, list[str], tuple[str, ...] ] # example when it's sequence: entry['invalidcommand'] = [entry.register(print), '%P'] _GridIndex = Union[int, str, Literal["all"]] _ImageSpec = Union[_Image, str] # str can be from e.g. tkinter.image_names() _Padding = Union[ _ScreenUnits, - Tuple[_ScreenUnits], - Tuple[_ScreenUnits, _ScreenUnits], - Tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits], - Tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits], + tuple[_ScreenUnits], + tuple[_ScreenUnits, _ScreenUnits], + tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits], + tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits], ] _Relief = Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] # manual page: Tk_GetRelief -_ScreenUnits = Union[str, float] # manual page: Tk_GetPixels +_ScreenUnits = Union[str, float] # Often the right type instead of int. Manual page: Tk_GetPixels _XYScrollCommand = Union[str, Callable[[float, float], Any]] # -xscrollcommand and -yscrollcommand in 'options' manual page _TakeFocusValue = Union[int, Literal[""], Callable[[str], Optional[bool]]] # -takefocus in manual page named 'options' class EventType(str, Enum): Activate: str ButtonPress: str + Button = ButtonPress ButtonRelease: str Circulate: str CirculateRequest: str @@ -128,6 +81,7 @@ class EventType(str, Enum): GraphicsExpose: str Gravity: str KeyPress: str + Key = KeyPress KeyRelease: str Keymap: str Leave: str @@ -147,9 +101,9 @@ class EventType(str, Enum): VirtualEvent: str Visibility: str -_W = TypeVar("_W", bound="Misc") +_W = TypeVar("_W", bound=Misc) # Events considered covariant because you should never assign to event.widget. -_W_co = TypeVar("_W_co", covariant=True, bound="Misc") +_W_co = TypeVar("_W_co", covariant=True, bound=Misc) class Event(Generic[_W_co]): serial: int @@ -183,7 +137,7 @@ class Variable: def get(self) -> Any: ... def trace_add(self, mode: _TraceMode, callback: Callable[[str, str, str], Any]) -> str: ... def trace_remove(self, mode: _TraceMode, cbname: str) -> None: ... - def trace_info(self) -> list[tuple[Tuple[_TraceMode, ...], str]]: ... + def trace_info(self) -> list[tuple[tuple[_TraceMode, ...], str]]: ... def trace_variable(self, mode, callback): ... # deprecated def trace_vdelete(self, mode, cbname): ... # deprecated def trace_vinfo(self): ... # deprecated @@ -295,7 +249,7 @@ class Misc: def winfo_geometry(self) -> str: ... def winfo_height(self) -> int: ... def winfo_id(self) -> int: ... - def winfo_interps(self, displayof: Literal[0] | Misc | None = ...) -> Tuple[str, ...]: ... + def winfo_interps(self, displayof: Literal[0] | Misc | None = ...) -> tuple[str, ...]: ... def winfo_ismapped(self) -> bool: ... def winfo_manager(self) -> str: ... def winfo_name(self) -> str: ... @@ -466,9 +420,9 @@ class Misc: x: _ScreenUnits = ..., y: _ScreenUnits = ..., ) -> None: ... - def event_info(self, virtual: str | None = ...) -> Tuple[str, ...]: ... - def image_names(self) -> Tuple[str, ...]: ... - def image_types(self) -> Tuple[str, ...]: ... + def event_info(self, virtual: str | None = ...) -> tuple[str, ...]: ... + def image_names(self) -> tuple[str, ...]: ... + def image_types(self) -> tuple[str, ...]: ... # See #4363 and #4891 def __setitem__(self, key: str, value: Any) -> None: ... def __getitem__(self, key: str) -> Any: ... @@ -514,7 +468,7 @@ class Wm: ) -> tuple[int, int, int, int] | None: ... aspect = wm_aspect @overload - def wm_attributes(self) -> Tuple[Any, ...]: ... + def wm_attributes(self) -> tuple[Any, ...]: ... @overload def wm_attributes(self, __option: str) -> Any: ... @overload @@ -525,7 +479,7 @@ class Wm: @overload def wm_colormapwindows(self) -> list[Misc]: ... @overload - def wm_colormapwindows(self, __wlist: list[Misc] | Tuple[Misc, ...]) -> None: ... + def wm_colormapwindows(self, __wlist: list[Misc] | tuple[Misc, ...]) -> None: ... @overload def wm_colormapwindows(self, __first_wlist_item: Misc, *other_wlist_items: Misc) -> None: ... colormapwindows = wm_colormapwindows @@ -589,7 +543,7 @@ class Wm: @overload def wm_protocol(self, name: str, func: None = ...) -> str: ... @overload - def wm_protocol(self, name: None = ..., func: None = ...) -> Tuple[str, ...]: ... + def wm_protocol(self, name: None = ..., func: None = ...) -> tuple[str, ...]: ... protocol = wm_protocol @overload def wm_resizable(self, width: None = ..., height: None = ...) -> tuple[bool, bool]: ... @@ -617,7 +571,7 @@ class Wm: withdraw = wm_withdraw class _ExceptionReportingCallback(Protocol): - def __call__(self, __exc: Type[BaseException], __val: BaseException, __tb: TracebackType | None) -> Any: ... + def __call__(self, __exc: type[BaseException], __val: BaseException, __tb: TracebackType | None) -> Any: ... class Tk(Misc, Wm): master: None @@ -656,43 +610,38 @@ class Tk(Misc, Wm): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure - def loadtk(self) -> None: ... # differs from _tkinter.TkappType.loadtk def destroy(self) -> None: ... def readprofile(self, baseName: str, className: str) -> None: ... report_callback_exception: _ExceptionReportingCallback # Tk has __getattr__ so that tk_instance.foo falls back to tk_instance.tk.foo - # Please keep in sync with _tkinter.TkappType - call: Callable[..., Any] - def eval(self, __code: str) -> str: ... - adderrorinfo: Any - createcommand: Any - createfilehandler: Any - createtimerhandler: Any - deletecommand: Any - deletefilehandler: Any - dooneevent: Any - evalfile: Any - exprboolean: Any - exprdouble: Any - exprlong: Any - exprstring: Any - getboolean: Any - getdouble: Any - getint: Any - getvar: Any - globalgetvar: Any - globalsetvar: Any - globalunsetvar: Any - interpaddr: Any - mainloop: Any - quit: Any - record: Any - setvar: Any - split: Any - splitlist: Any - unsetvar: Any - wantobjects: Any - willdispatch: Any + # Please keep in sync with _tkinter.TkappType. + # Some methods are intentionally missing because they are inherited from Misc instead. + def adderrorinfo(self, __msg): ... + def call(self, __command: Any, *args: Any) -> Any: ... + def createcommand(self, __name, __func): ... + if sys.platform != "win32": + def createfilehandler(self, __file, __mask, __func): ... + def deletefilehandler(self, __file): ... + def createtimerhandler(self, __milliseconds, __func): ... + def dooneevent(self, __flags: int = ...): ... + def eval(self, __script: str) -> str: ... + def evalfile(self, __fileName): ... + def exprboolean(self, __s): ... + def exprdouble(self, __s): ... + def exprlong(self, __s): ... + def exprstring(self, __s): ... + def globalgetvar(self, *args, **kwargs): ... + def globalsetvar(self, *args, **kwargs): ... + def globalunsetvar(self, *args, **kwargs): ... + def interpaddr(self): ... + def loadtk(self) -> None: ... + def record(self, __script): ... + if sys.version_info < (3, 11): + def split(self, __arg): ... + def splitlist(self, __arg): ... + def unsetvar(self, *args, **kwargs): ... + def wantobjects(self, *args, **kwargs): ... + def willdispatch(self): ... def Tcl(screenName: Any | None = ..., baseName: Any | None = ..., className: str = ..., useTk: bool = ...): ... @@ -739,14 +688,6 @@ class Pack: pack = pack_configure forget = pack_forget propagate = Misc.pack_propagate - # commented out to avoid mypy getting confused with multiple - # inheritance and how things get overridden with different things - # info = pack_info - # pack_propagate = Misc.pack_propagate - # configure = pack_configure - # config = pack_configure - # slaves = Misc.pack_slaves - # pack_slaves = Misc.pack_slaves class _PlaceInfo(_InMiscNonTotal): # empty dict if widget hasn't been placed anchor: _Anchor @@ -783,13 +724,6 @@ class Place: def place_info(self) -> _PlaceInfo: ... place = place_configure info = place_info - # commented out to avoid mypy getting confused with multiple - # inheritance and how things get overridden with different things - # config = place_configure - # configure = place_configure - # forget = place_forget - # slaves = Misc.place_slaves - # place_slaves = Misc.place_slaves class _GridInfo(_InMiscNonTotal): # empty dict if widget hasn't been gridded column: int @@ -825,24 +759,6 @@ class Grid: grid = grid_configure location = Misc.grid_location size = Misc.grid_size - # commented out to avoid mypy getting confused with multiple - # inheritance and how things get overridden with different things - # bbox = Misc.grid_bbox - # grid_bbox = Misc.grid_bbox - # forget = grid_forget - # info = grid_info - # grid_location = Misc.grid_location - # grid_propagate = Misc.grid_propagate - # grid_size = Misc.grid_size - # rowconfigure = Misc.grid_rowconfigure - # grid_rowconfigure = Misc.grid_rowconfigure - # grid_columnconfigure = Misc.grid_columnconfigure - # columnconfigure = Misc.grid_columnconfigure - # config = grid_configure - # configure = grid_configure - # propagate = Misc.grid_propagate - # slaves = Misc.grid_slaves - # grid_slaves = Misc.grid_slaves class BaseWidget(Misc): master: Misc @@ -1121,21 +1037,19 @@ class Canvas(Widget, XView, YView): def addtag_overlapping(self, newtag: str, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: _ScreenUnits) -> None: ... def addtag_withtag(self, newtag: str, tagOrId: str | _CanvasItemId) -> None: ... def find(self, *args): ... # internal method - def find_above(self, tagOrId: str | _CanvasItemId) -> Tuple[_CanvasItemId, ...]: ... - def find_all(self) -> Tuple[_CanvasItemId, ...]: ... - def find_below(self, tagOrId: str | _CanvasItemId) -> Tuple[_CanvasItemId, ...]: ... + def find_above(self, tagOrId: str | _CanvasItemId) -> tuple[_CanvasItemId, ...]: ... + def find_all(self) -> tuple[_CanvasItemId, ...]: ... + def find_below(self, tagOrId: str | _CanvasItemId) -> tuple[_CanvasItemId, ...]: ... def find_closest( self, x: _ScreenUnits, y: _ScreenUnits, halo: _ScreenUnits | None = ..., start: str | _CanvasItemId | None = ... - ) -> Tuple[_CanvasItemId, ...]: ... + ) -> tuple[_CanvasItemId, ...]: ... def find_enclosed( self, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: _ScreenUnits - ) -> Tuple[_CanvasItemId, ...]: ... - def find_overlapping(self, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: float) -> Tuple[_CanvasItemId, ...]: ... - def find_withtag(self, tagOrId: str | _CanvasItemId) -> Tuple[_CanvasItemId, ...]: ... - # Canvas.bbox() args are `str | _CanvasItemId`, but mypy rejects that - # description because it's incompatible with Misc.bbox(), an alias for - # Misc.grid_bbox(). Yes it is, but there's not much we can do about it. - def bbox(self, *args: str | _CanvasItemId) -> tuple[int, int, int, int]: ... # type: ignore + ) -> tuple[_CanvasItemId, ...]: ... + def find_overlapping(self, x1: _ScreenUnits, y1: _ScreenUnits, x2: _ScreenUnits, y2: float) -> tuple[_CanvasItemId, ...]: ... + def find_withtag(self, tagOrId: str | _CanvasItemId) -> tuple[_CanvasItemId, ...]: ... + # Incompatible with Misc.bbox(), tkinter violates LSP + def bbox(self, *args: str | _CanvasItemId) -> tuple[int, int, int, int]: ... # type: ignore[override] @overload def tag_bind( self, @@ -1156,7 +1070,7 @@ class Canvas(Widget, XView, YView): @overload def coords(self) -> list[float]: ... @overload - def coords(self, __args: list[int] | list[float] | Tuple[float, ...]) -> None: ... + def coords(self, __args: list[int] | list[float] | tuple[float, ...]) -> None: ... @overload def coords(self, __x1: float, __y1: float, *args: float) -> None: ... # create_foo() methods accept coords as a list, a tuple, or as separate arguments. @@ -1172,16 +1086,16 @@ class Canvas(Widget, XView, YView): __x1: float, __y1: float, *, - activedash: str | list[int] | Tuple[int, ...] = ..., + activedash: str | list[int] | tuple[int, ...] = ..., activefill: _Color = ..., activestipple: str = ..., activewidth: _ScreenUnits = ..., arrow: Literal["first", "last", "both"] = ..., arrowshape: tuple[float, float, float] = ..., capstyle: Literal["round", "projecting", "butt"] = ..., - dash: str | list[int] | Tuple[int, ...] = ..., + dash: str | list[int] | tuple[int, ...] = ..., dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., + disableddash: str | list[int] | tuple[int, ...] = ..., disabledfill: _Color = ..., disabledstipple: _Bitmap = ..., disabledwidth: _ScreenUnits = ..., @@ -1192,7 +1106,7 @@ class Canvas(Widget, XView, YView): splinesteps: float = ..., state: Literal["normal", "active", "disabled"] = ..., stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., ) -> _CanvasItemId: ... @overload @@ -1200,16 +1114,16 @@ class Canvas(Widget, XView, YView): self, __coords: tuple[float, float, float, float] | list[int] | list[float], *, - activedash: str | list[int] | Tuple[int, ...] = ..., + activedash: str | list[int] | tuple[int, ...] = ..., activefill: _Color = ..., activestipple: str = ..., activewidth: _ScreenUnits = ..., arrow: Literal["first", "last", "both"] = ..., arrowshape: tuple[float, float, float] = ..., capstyle: Literal["round", "projecting", "butt"] = ..., - dash: str | list[int] | Tuple[int, ...] = ..., + dash: str | list[int] | tuple[int, ...] = ..., dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., + disableddash: str | list[int] | tuple[int, ...] = ..., disabledfill: _Color = ..., disabledstipple: _Bitmap = ..., disabledwidth: _ScreenUnits = ..., @@ -1220,7 +1134,7 @@ class Canvas(Widget, XView, YView): splinesteps: float = ..., state: Literal["normal", "active", "disabled"] = ..., stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., ) -> _CanvasItemId: ... @overload @@ -1231,15 +1145,15 @@ class Canvas(Widget, XView, YView): __x1: float, __y1: float, *, - activedash: str | list[int] | Tuple[int, ...] = ..., + activedash: str | list[int] | tuple[int, ...] = ..., activefill: _Color = ..., activeoutline: _Color = ..., activeoutlinestipple: _Color = ..., activestipple: str = ..., activewidth: _ScreenUnits = ..., - dash: str | list[int] | Tuple[int, ...] = ..., + dash: str | list[int] | tuple[int, ...] = ..., dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., + disableddash: str | list[int] | tuple[int, ...] = ..., disabledfill: _Color = ..., disabledoutline: _Color = ..., disabledoutlinestipple: _Color = ..., @@ -1252,7 +1166,7 @@ class Canvas(Widget, XView, YView): outlinestipple: _Bitmap = ..., state: Literal["normal", "active", "disabled"] = ..., stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., ) -> _CanvasItemId: ... @overload @@ -1260,15 +1174,15 @@ class Canvas(Widget, XView, YView): self, __coords: tuple[float, float, float, float] | list[int] | list[float], *, - activedash: str | list[int] | Tuple[int, ...] = ..., + activedash: str | list[int] | tuple[int, ...] = ..., activefill: _Color = ..., activeoutline: _Color = ..., activeoutlinestipple: _Color = ..., activestipple: str = ..., activewidth: _ScreenUnits = ..., - dash: str | list[int] | Tuple[int, ...] = ..., + dash: str | list[int] | tuple[int, ...] = ..., dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., + disableddash: str | list[int] | tuple[int, ...] = ..., disabledfill: _Color = ..., disabledoutline: _Color = ..., disabledoutlinestipple: _Color = ..., @@ -1281,7 +1195,7 @@ class Canvas(Widget, XView, YView): outlinestipple: _Bitmap = ..., state: Literal["normal", "active", "disabled"] = ..., stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., ) -> _CanvasItemId: ... @overload @@ -1292,15 +1206,15 @@ class Canvas(Widget, XView, YView): __x1: float, __y1: float, *xy_pairs: float, - activedash: str | list[int] | Tuple[int, ...] = ..., + activedash: str | list[int] | tuple[int, ...] = ..., activefill: _Color = ..., activeoutline: _Color = ..., activeoutlinestipple: _Color = ..., activestipple: str = ..., activewidth: _ScreenUnits = ..., - dash: str | list[int] | Tuple[int, ...] = ..., + dash: str | list[int] | tuple[int, ...] = ..., dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., + disableddash: str | list[int] | tuple[int, ...] = ..., disabledfill: _Color = ..., disabledoutline: _Color = ..., disabledoutlinestipple: _Color = ..., @@ -1316,23 +1230,23 @@ class Canvas(Widget, XView, YView): splinesteps: float = ..., state: Literal["normal", "active", "disabled"] = ..., stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., ) -> _CanvasItemId: ... @overload def create_polygon( self, - __coords: Tuple[float, ...] | list[int] | list[float], + __coords: tuple[float, ...] | list[int] | list[float], *, - activedash: str | list[int] | Tuple[int, ...] = ..., + activedash: str | list[int] | tuple[int, ...] = ..., activefill: _Color = ..., activeoutline: _Color = ..., activeoutlinestipple: _Color = ..., activestipple: str = ..., activewidth: _ScreenUnits = ..., - dash: str | list[int] | Tuple[int, ...] = ..., + dash: str | list[int] | tuple[int, ...] = ..., dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., + disableddash: str | list[int] | tuple[int, ...] = ..., disabledfill: _Color = ..., disabledoutline: _Color = ..., disabledoutlinestipple: _Color = ..., @@ -1348,7 +1262,7 @@ class Canvas(Widget, XView, YView): splinesteps: float = ..., state: Literal["normal", "active", "disabled"] = ..., stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., ) -> _CanvasItemId: ... @overload @@ -1359,15 +1273,15 @@ class Canvas(Widget, XView, YView): __x1: float, __y1: float, *, - activedash: str | list[int] | Tuple[int, ...] = ..., + activedash: str | list[int] | tuple[int, ...] = ..., activefill: _Color = ..., activeoutline: _Color = ..., activeoutlinestipple: _Color = ..., activestipple: str = ..., activewidth: _ScreenUnits = ..., - dash: str | list[int] | Tuple[int, ...] = ..., + dash: str | list[int] | tuple[int, ...] = ..., dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., + disableddash: str | list[int] | tuple[int, ...] = ..., disabledfill: _Color = ..., disabledoutline: _Color = ..., disabledoutlinestipple: _Color = ..., @@ -1380,7 +1294,7 @@ class Canvas(Widget, XView, YView): outlinestipple: _Bitmap = ..., state: Literal["normal", "active", "disabled"] = ..., stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., ) -> _CanvasItemId: ... @overload @@ -1388,15 +1302,15 @@ class Canvas(Widget, XView, YView): self, __coords: tuple[float, float, float, float] | list[int] | list[float], *, - activedash: str | list[int] | Tuple[int, ...] = ..., + activedash: str | list[int] | tuple[int, ...] = ..., activefill: _Color = ..., activeoutline: _Color = ..., activeoutlinestipple: _Color = ..., activestipple: str = ..., activewidth: _ScreenUnits = ..., - dash: str | list[int] | Tuple[int, ...] = ..., + dash: str | list[int] | tuple[int, ...] = ..., dashoffset: _ScreenUnits = ..., - disableddash: str | list[int] | Tuple[int, ...] = ..., + disableddash: str | list[int] | tuple[int, ...] = ..., disabledfill: _Color = ..., disabledoutline: _Color = ..., disabledoutlinestipple: _Color = ..., @@ -1409,7 +1323,7 @@ class Canvas(Widget, XView, YView): outlinestipple: _Bitmap = ..., state: Literal["normal", "active", "disabled"] = ..., stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., ) -> _CanvasItemId: ... @overload @@ -1429,7 +1343,7 @@ class Canvas(Widget, XView, YView): offset: _ScreenUnits = ..., state: Literal["normal", "active", "disabled"] = ..., stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., text: float | str = ..., width: _ScreenUnits = ..., ) -> _CanvasItemId: ... @@ -1449,7 +1363,7 @@ class Canvas(Widget, XView, YView): offset: _ScreenUnits = ..., state: Literal["normal", "active", "disabled"] = ..., stipple: _Bitmap = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., text: float | str = ..., width: _ScreenUnits = ..., ) -> _CanvasItemId: ... @@ -1462,7 +1376,7 @@ class Canvas(Widget, XView, YView): anchor: _Anchor = ..., height: _ScreenUnits = ..., state: Literal["normal", "active", "disabled"] = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., window: Widget = ..., ) -> _CanvasItemId: ... @@ -1474,7 +1388,7 @@ class Canvas(Widget, XView, YView): anchor: _Anchor = ..., height: _ScreenUnits = ..., state: Literal["normal", "active", "disabled"] = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., width: _ScreenUnits = ..., window: Widget = ..., ) -> _CanvasItemId: ... @@ -1485,7 +1399,7 @@ class Canvas(Widget, XView, YView): @overload def dtag(self, __id: _CanvasItemId, __tag_to_delete: str) -> None: ... def focus(self, *args): ... - def gettags(self, __tagOrId: str | _CanvasItemId) -> Tuple[str, ...]: ... + def gettags(self, __tagOrId: str | _CanvasItemId) -> tuple[str, ...]: ... def icursor(self, *args): ... def index(self, *args): ... def insert(self, *args): ... @@ -1505,10 +1419,10 @@ class Canvas(Widget, XView, YView): # # But mypy doesn't like aliasing here (maybe because Misc defines the same names) def tag_lower(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... - def lower(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... # type: ignore + def lower(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... # type: ignore[override] def tag_raise(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... - def tkraise(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... # type: ignore - def lift(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... # type: ignore + def tkraise(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... # type: ignore[override] + def lift(self, __first: str | _CanvasItemId, __second: str | _CanvasItemId | None = ...) -> None: ... # type: ignore[override] def scale(self, *args): ... def scan_mark(self, x, y): ... def scan_dragto(self, x, y, gain: int = ...): ... @@ -1737,7 +1651,7 @@ class Entry(Widget, XView): def scan_mark(self, x): ... def scan_dragto(self, x): ... def selection_adjust(self, index: _EntryIndex) -> None: ... - def selection_clear(self) -> None: ... # type: ignore + def selection_clear(self) -> None: ... # type: ignore[override] def selection_from(self, index: _EntryIndex) -> None: ... def selection_present(self) -> bool: ... def selection_range(self, start: _EntryIndex, end: _EntryIndex) -> None: ... @@ -1760,9 +1674,9 @@ class Frame(Widget): bg: _Color = ..., border: _ScreenUnits = ..., borderwidth: _ScreenUnits = ..., - class_: str = ..., - colormap: Literal["new", ""] | Misc = ..., - container: bool = ..., + class_: str = ..., # can't be changed with configure() + colormap: Literal["new", ""] | Misc = ..., # can't be changed with configure() + container: bool = ..., # can't be changed with configure() cursor: _Cursor = ..., height: _ScreenUnits = ..., highlightbackground: _Color = ..., @@ -1773,7 +1687,7 @@ class Frame(Widget): pady: _ScreenUnits = ..., relief: _Relief = ..., takefocus: _TakeFocusValue = ..., - visual: str | tuple[str, int] = ..., + visual: str | tuple[str, int] = ..., # can't be changed with configure() width: _ScreenUnits = ..., ) -> None: ... @overload @@ -1983,7 +1897,7 @@ class Listbox(Widget, XView, YView): def see(self, index): ... def selection_anchor(self, index): ... select_anchor: Any - def selection_clear(self, first, last: Any | None = ...): ... # type: ignore + def selection_clear(self, first, last: Any | None = ...): ... # type: ignore[override] select_clear: Any def selection_includes(self, index): ... select_includes: Any @@ -2730,7 +2644,7 @@ class Text(Widget, XView, YView): startline: int | Literal[""] = ..., state: Literal["normal", "disabled"] = ..., # Literal inside Tuple doesn't actually work - tabs: _ScreenUnits | str | Tuple[_ScreenUnits | str, ...] = ..., + tabs: _ScreenUnits | str | tuple[_ScreenUnits | str, ...] = ..., tabstyle: Literal["tabular", "wordprocessor"] = ..., takefocus: _TakeFocusValue = ..., undo: bool = ..., @@ -2781,7 +2695,7 @@ class Text(Widget, XView, YView): spacing3: _ScreenUnits = ..., startline: int | Literal[""] = ..., state: Literal["normal", "disabled"] = ..., - tabs: _ScreenUnits | str | Tuple[_ScreenUnits | str, ...] = ..., + tabs: _ScreenUnits | str | tuple[_ScreenUnits | str, ...] = ..., tabstyle: Literal["tabular", "wordprocessor"] = ..., takefocus: _TakeFocusValue = ..., undo: bool = ..., @@ -2793,7 +2707,7 @@ class Text(Widget, XView, YView): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure - def bbox(self, index: _TextIndex) -> tuple[int, int, int, int] | None: ... # type: ignore + def bbox(self, index: _TextIndex) -> tuple[int, int, int, int] | None: ... # type: ignore[override] def compare(self, index1: _TextIndex, op: Literal["<", "<=", "==", ">=", ">", "!="], index2: _TextIndex) -> bool: ... def count(self, index1, index2, *args): ... # TODO @overload @@ -2860,20 +2774,20 @@ class Text(Widget, XView, YView): def image_create(self, index, cnf=..., **kw): ... def image_names(self): ... def index(self, index: _TextIndex) -> str: ... - def insert(self, index: _TextIndex, chars: str, *args: str | list[str] | Tuple[str, ...]) -> None: ... + def insert(self, index: _TextIndex, chars: str, *args: str | list[str] | tuple[str, ...]) -> None: ... @overload def mark_gravity(self, markName: str, direction: None = ...) -> Literal["left", "right"]: ... @overload def mark_gravity(self, markName: str, direction: Literal["left", "right"]) -> None: ... # actually returns empty string - def mark_names(self) -> Tuple[str, ...]: ... + def mark_names(self) -> tuple[str, ...]: ... def mark_set(self, markName: str, index: _TextIndex) -> None: ... def mark_unset(self, *markNames: str) -> None: ... def mark_next(self, index: _TextIndex) -> str | None: ... def mark_previous(self, index: _TextIndex) -> str | None: ... # **kw of peer_create is same as the kwargs of Text.__init__ def peer_create(self, newPathName: str | Text, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def peer_names(self) -> Tuple[_tkinter.Tcl_Obj, ...]: ... - def replace(self, index1: _TextIndex, index2: _TextIndex, chars: str, *args: str | list[str] | Tuple[str, ...]) -> None: ... + def peer_names(self) -> tuple[_tkinter.Tcl_Obj, ...]: ... + def replace(self, index1: _TextIndex, index2: _TextIndex, chars: str, *args: str | list[str] | tuple[str, ...]) -> None: ... def scan_mark(self, x: int, y: int) -> None: ... def scan_dragto(self, x: int, y: int) -> None: ... def search( @@ -2945,11 +2859,11 @@ class Text(Widget, XView, YView): tag_config = tag_configure def tag_delete(self, __first_tag_name: str, *tagNames: str) -> None: ... # error if no tag names given def tag_lower(self, tagName: str, belowThis: str | None = ...) -> None: ... - def tag_names(self, index: _TextIndex | None = ...) -> Tuple[str, ...]: ... + def tag_names(self, index: _TextIndex | None = ...) -> tuple[str, ...]: ... def tag_nextrange(self, tagName: str, index1: _TextIndex, index2: _TextIndex | None = ...) -> tuple[str, str] | tuple[()]: ... def tag_prevrange(self, tagName: str, index1: _TextIndex, index2: _TextIndex | None = ...) -> tuple[str, str] | tuple[()]: ... def tag_raise(self, tagName: str, aboveThis: str | None = ...) -> None: ... - def tag_ranges(self, tagName: str) -> Tuple[_tkinter.Tcl_Obj, ...]: ... + def tag_ranges(self, tagName: str) -> tuple[_tkinter.Tcl_Obj, ...]: ... # tag_remove and tag_delete are different def tag_remove(self, tagName: str, index1: _TextIndex, index2: _TextIndex | None = ...) -> None: ... # TODO: window_* methods @@ -3039,10 +2953,10 @@ class PhotoImage(Image): str | list[str] | list[list[_Color]] - | list[Tuple[_Color, ...]] - | Tuple[str, ...] - | Tuple[list[_Color], ...] - | Tuple[Tuple[_Color, ...], ...] + | list[tuple[_Color, ...]] + | tuple[str, ...] + | tuple[list[_Color], ...] + | tuple[tuple[_Color, ...], ...] ), to: tuple[int, int] | None = ..., ) -> None: ... @@ -3066,8 +2980,8 @@ class BitmapImage(Image): maskfile: StrOrBytesPath = ..., ) -> None: ... -def image_names() -> Tuple[str, ...]: ... -def image_types() -> Tuple[str, ...]: ... +def image_names() -> tuple[str, ...]: ... +def image_types() -> tuple[str, ...]: ... class Spinbox(Widget, XView): def __init__( @@ -3086,7 +3000,7 @@ class Spinbox(Widget, XView): buttondownrelief: _Relief = ..., buttonuprelief: _Relief = ..., # percent substitutions don't seem to be supported, it's similar to Entry's validation stuff - command: Callable[[], Any] | str | list[str] | Tuple[str, ...] = ..., + command: Callable[[], Any] | str | list[str] | tuple[str, ...] = ..., cursor: _Cursor = ..., disabledbackground: _Color = ..., disabledforeground: _Color = ..., @@ -3123,7 +3037,7 @@ class Spinbox(Widget, XView): validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., validatecommand: _EntryValidateCommand = ..., vcmd: _EntryValidateCommand = ..., - values: list[str] | Tuple[str, ...] = ..., + values: list[str] | tuple[str, ...] = ..., width: int = ..., wrap: bool = ..., xscrollcommand: _XYScrollCommand = ..., @@ -3143,7 +3057,7 @@ class Spinbox(Widget, XView): buttoncursor: _Cursor = ..., buttondownrelief: _Relief = ..., buttonuprelief: _Relief = ..., - command: Callable[[], Any] | str | list[str] | Tuple[str, ...] = ..., + command: Callable[[], Any] | str | list[str] | tuple[str, ...] = ..., cursor: _Cursor = ..., disabledbackground: _Color = ..., disabledforeground: _Color = ..., @@ -3179,7 +3093,7 @@ class Spinbox(Widget, XView): validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., validatecommand: _EntryValidateCommand = ..., vcmd: _EntryValidateCommand = ..., - values: list[str] | Tuple[str, ...] = ..., + values: list[str] | tuple[str, ...] = ..., width: int = ..., wrap: bool = ..., xscrollcommand: _XYScrollCommand = ..., @@ -3199,7 +3113,7 @@ class Spinbox(Widget, XView): def scan(self, *args): ... def scan_mark(self, x): ... def scan_dragto(self, x): ... - def selection(self, *args: Any) -> Tuple[int, ...]: ... + def selection(self, *args: Any) -> tuple[int, ...]: ... def selection_adjust(self, index): ... def selection_clear(self): ... def selection_element(self, element: Any | None = ...): ... @@ -3220,9 +3134,9 @@ class LabelFrame(Widget): bg: _Color = ..., border: _ScreenUnits = ..., borderwidth: _ScreenUnits = ..., - class_: str = ..., - colormap: Literal["new", ""] | Misc = ..., - container: bool = ..., # undocumented + class_: str = ..., # can't be changed with configure() + colormap: Literal["new", ""] | Misc = ..., # can't be changed with configure() + container: bool = ..., # undocumented, can't be changed with configure() cursor: _Cursor = ..., fg: _Color = ..., font: _FontDescription = ..., @@ -3240,7 +3154,7 @@ class LabelFrame(Widget): relief: _Relief = ..., takefocus: _TakeFocusValue = ..., text: float | str = ..., - visual: str | tuple[str, int] = ..., + visual: str | tuple[str, int] = ..., # can't be changed with configure() width: _ScreenUnits = ..., ) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/tkinter/filedialog.pyi b/mypy/typeshed/stdlib/tkinter/filedialog.pyi index 0fc7d6e8a3bc..b818d5e8253e 100644 --- a/mypy/typeshed/stdlib/tkinter/filedialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/filedialog.pyi @@ -1,6 +1,6 @@ from _typeshed import StrOrBytesPath from tkinter import Button, Entry, Frame, Listbox, Misc, Scrollbar, StringVar, Toplevel, commondialog -from typing import IO, Any, ClassVar, Iterable, Tuple +from typing import IO, Any, ClassVar, Iterable from typing_extensions import Literal dialogstates: dict[Any, tuple[Any, Any]] @@ -64,7 +64,7 @@ def asksaveasfilename( *, confirmoverwrite: bool | None = ..., defaultextension: str | None = ..., - filetypes: Iterable[tuple[str, str | list[str] | Tuple[str, ...]]] | None = ..., + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., initialdir: StrOrBytesPath | None = ..., initialfile: StrOrBytesPath | None = ..., parent: Misc | None = ..., @@ -74,7 +74,7 @@ def asksaveasfilename( def askopenfilename( *, defaultextension: str | None = ..., - filetypes: Iterable[tuple[str, str | list[str] | Tuple[str, ...]]] | None = ..., + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., initialdir: StrOrBytesPath | None = ..., initialfile: StrOrBytesPath | None = ..., parent: Misc | None = ..., @@ -84,13 +84,13 @@ def askopenfilename( def askopenfilenames( *, defaultextension: str | None = ..., - filetypes: Iterable[tuple[str, str | list[str] | Tuple[str, ...]]] | None = ..., + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., initialdir: StrOrBytesPath | None = ..., initialfile: StrOrBytesPath | None = ..., parent: Misc | None = ..., title: str | None = ..., typevariable: StringVar | str | None = ..., -) -> Literal[""] | Tuple[str, ...]: ... +) -> Literal[""] | tuple[str, ...]: ... def askdirectory( *, initialdir: StrOrBytesPath | None = ..., mustexist: bool | None = ..., parent: Misc | None = ..., title: str | None = ... ) -> str: ... # can be empty string @@ -101,7 +101,7 @@ def asksaveasfile( *, confirmoverwrite: bool | None = ..., defaultextension: str | None = ..., - filetypes: Iterable[tuple[str, str | list[str] | Tuple[str, ...]]] | None = ..., + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., initialdir: StrOrBytesPath | None = ..., initialfile: StrOrBytesPath | None = ..., parent: Misc | None = ..., @@ -112,7 +112,7 @@ def askopenfile( mode: str = ..., *, defaultextension: str | None = ..., - filetypes: Iterable[tuple[str, str | list[str] | Tuple[str, ...]]] | None = ..., + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., initialdir: StrOrBytesPath | None = ..., initialfile: StrOrBytesPath | None = ..., parent: Misc | None = ..., @@ -123,11 +123,11 @@ def askopenfiles( mode: str = ..., *, defaultextension: str | None = ..., - filetypes: Iterable[tuple[str, str | list[str] | Tuple[str, ...]]] | None = ..., + filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ..., initialdir: StrOrBytesPath | None = ..., initialfile: StrOrBytesPath | None = ..., parent: Misc | None = ..., title: str | None = ..., typevariable: StringVar | str | None = ..., -) -> Tuple[IO[Any], ...]: ... # can be empty tuple +) -> tuple[IO[Any], ...]: ... # can be empty tuple def test() -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/font.pyi b/mypy/typeshed/stdlib/tkinter/font.pyi index fccc0fbf1f0a..211e8ec9a0be 100644 --- a/mypy/typeshed/stdlib/tkinter/font.pyi +++ b/mypy/typeshed/stdlib/tkinter/font.pyi @@ -1,7 +1,7 @@ import _tkinter import sys import tkinter -from typing import Any, List, Tuple, Union, overload +from typing import Any, Union, overload from typing_extensions import Literal, TypedDict NORMAL: Literal["normal"] @@ -15,8 +15,8 @@ _FontDescription = Union[ # A font object constructed in Python Font, # ("Helvetica", 12, BOLD) - List[Any], - Tuple[Any, ...], + list[Any], + tuple[Any, ...], # A font object constructed in Tcl _tkinter.Tcl_Obj, ] @@ -102,8 +102,8 @@ class Font: def metrics(self, *, displayof: tkinter.Misc | None = ...) -> _MetricsDict: ... def measure(self, text: str, displayof: tkinter.Misc | None = ...) -> int: ... -def families(root: tkinter.Misc | None = ..., displayof: tkinter.Misc | None = ...) -> Tuple[str, ...]: ... -def names(root: tkinter.Misc | None = ...) -> Tuple[str, ...]: ... +def families(root: tkinter.Misc | None = ..., displayof: tkinter.Misc | None = ...) -> tuple[str, ...]: ... +def names(root: tkinter.Misc | None = ...) -> tuple[str, ...]: ... if sys.version_info >= (3, 10): def nametofont(name: str, root: tkinter.Misc | None = ...) -> Font: ... diff --git a/mypy/typeshed/stdlib/tkinter/tix.pyi b/mypy/typeshed/stdlib/tkinter/tix.pyi index 3037212c0ad1..6842ab7b1108 100644 --- a/mypy/typeshed/stdlib/tkinter/tix.pyi +++ b/mypy/typeshed/stdlib/tkinter/tix.pyi @@ -1,5 +1,5 @@ import tkinter -from typing import Any, Tuple +from typing import Any from typing_extensions import Literal WINDOW: Literal["window"] @@ -194,7 +194,7 @@ class HList(TixWidget, tkinter.XView, tkinter.YView): def indicator_size(self, entry: str) -> int: ... def info_anchor(self) -> str: ... def info_bbox(self, entry: str) -> tuple[int, int, int, int]: ... - def info_children(self, entry: str | None = ...) -> Tuple[str, ...]: ... + def info_children(self, entry: str | None = ...) -> tuple[str, ...]: ... def info_data(self, entry: str) -> Any: ... def info_dragsite(self) -> str: ... def info_dropsite(self) -> str: ... @@ -203,7 +203,7 @@ class HList(TixWidget, tkinter.XView, tkinter.YView): def info_next(self, entry: str) -> str: ... def info_parent(self, entry: str) -> str: ... def info_prev(self, entry: str) -> str: ... - def info_selection(self) -> Tuple[str, ...]: ... + def info_selection(self) -> tuple[str, ...]: ... def item_cget(self, entry: str, col: int, opt: Any) -> Any: ... def item_configure(self, entry: str, col: int, cnf: dict[str, Any] = ..., **kw: Any) -> Any | None: ... def item_create(self, entry: str, col: int, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... @@ -224,7 +224,7 @@ class CheckList(TixWidget): def close(self, entrypath: str) -> None: ... def getmode(self, entrypath: str) -> str: ... def open(self, entrypath: str) -> None: ... - def getselection(self, mode: str = ...) -> Tuple[str, ...]: ... + def getselection(self, mode: str = ...) -> tuple[str, ...]: ... def getstatus(self, entrypath: str) -> str: ... def setstatus(self, entrypath: str, mode: str = ...) -> None: ... @@ -253,7 +253,7 @@ class TList(TixWidget, tkinter.XView, tkinter.YView): def info_down(self, index: int) -> int: ... def info_left(self, index: int) -> int: ... def info_right(self, index: int) -> int: ... - def info_selection(self) -> Tuple[int, ...]: ... + def info_selection(self) -> tuple[int, ...]: ... def info_size(self) -> int: ... def info_up(self, index: int) -> int: ... def nearest(self, x: int, y: int) -> int: ... @@ -266,7 +266,7 @@ class PanedWindow(TixWidget): def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... def add(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... def delete(self, name: str) -> None: ... - def forget(self, name: str) -> None: ... # type: ignore + def forget(self, name: str) -> None: ... # type: ignore[override] def panecget(self, entry: str, opt: Any) -> Any: ... def paneconfigure(self, entry: str, cnf: dict[str, Any] = ..., **kw: Any) -> Any | None: ... def panes(self) -> list[tkinter.Widget]: ... diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index be0713ec2e4b..a09255625433 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -2,7 +2,7 @@ import _tkinter import sys import tkinter from tkinter.font import _FontDescription -from typing import Any, Callable, Tuple, Union, overload +from typing import Any, Callable, Union, overload from typing_extensions import Literal, TypedDict def tclobjs_to_py(adict): ... @@ -24,7 +24,7 @@ class Style: def element_options(self, elementname): ... def theme_create(self, themename, parent: Any | None = ..., settings: Any | None = ...): ... def theme_settings(self, themename, settings): ... - def theme_names(self) -> Tuple[str, ...]: ... + def theme_names(self) -> tuple[str, ...]: ... @overload def theme_use(self, themename: str) -> None: ... @overload @@ -158,7 +158,7 @@ class Entry(Widget, tkinter.Entry): width: int = ..., xscrollcommand: tkinter._XYScrollCommand = ..., ) -> None: ... - @overload # type: ignore + @overload # type: ignore[override] def configure( self, cnf: dict[str, Any] | None = ..., @@ -183,7 +183,7 @@ class Entry(Widget, tkinter.Entry): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... # config must be copy/pasted, otherwise ttk.Entry().config is mypy error (don't know why) - @overload # type: ignore + @overload # type: ignore[override] def config( self, cnf: dict[str, Any] | None = ..., @@ -234,11 +234,11 @@ class Combobox(Entry): textvariable: tkinter.Variable = ..., validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., # undocumented validatecommand: tkinter._EntryValidateCommand = ..., # undocumented - values: list[str] | Tuple[str, ...] = ..., + values: list[str] | tuple[str, ...] = ..., width: int = ..., xscrollcommand: tkinter._XYScrollCommand = ..., # undocumented ) -> None: ... - @overload # type: ignore + @overload # type: ignore[override] def configure( self, cnf: dict[str, Any] | None = ..., @@ -259,14 +259,14 @@ class Combobox(Entry): textvariable: tkinter.Variable = ..., validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., validatecommand: tkinter._EntryValidateCommand = ..., - values: list[str] | Tuple[str, ...] = ..., + values: list[str] | tuple[str, ...] = ..., width: int = ..., xscrollcommand: tkinter._XYScrollCommand = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... # config must be copy/pasted, otherwise ttk.Combobox().config is mypy error (don't know why) - @overload # type: ignore + @overload # type: ignore[override] def config( self, cnf: dict[str, Any] | None = ..., @@ -287,7 +287,7 @@ class Combobox(Entry): textvariable: tkinter.Variable = ..., validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., validatecommand: tkinter._EntryValidateCommand = ..., - values: list[str] | Tuple[str, ...] = ..., + values: list[str] | tuple[str, ...] = ..., width: int = ..., xscrollcommand: tkinter._XYScrollCommand = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @@ -541,13 +541,13 @@ class Panedwindow(Widget, tkinter.PanedWindow): # width and height for tkinter.ttk.Panedwindow are int but for tkinter.PanedWindow they are screen units height: int = ..., name: str = ..., - orient: Literal["vertical", "horizontal"] = ..., + orient: Literal["vertical", "horizontal"] = ..., # can't be changed with configure() style: str = ..., takefocus: tkinter._TakeFocusValue = ..., width: int = ..., ) -> None: ... def add(self, child: tkinter.Widget, *, weight: int = ..., **kw) -> None: ... - @overload # type: ignore + @overload # type: ignore[override] def configure( self, cnf: dict[str, Any] | None = ..., @@ -561,7 +561,7 @@ class Panedwindow(Widget, tkinter.PanedWindow): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... # config must be copy/pasted, otherwise ttk.Panedwindow().config is mypy error (don't know why) - @overload # type: ignore + @overload # type: ignore[override] def config( self, cnf: dict[str, Any] | None = ..., @@ -688,7 +688,7 @@ class Scale(Widget, tkinter.Scale): value: float = ..., variable: tkinter.IntVar | tkinter.DoubleVar = ..., ) -> None: ... - @overload # type: ignore + @overload # type: ignore[override] def configure( self, cnf: dict[str, Any] | None = ..., @@ -708,7 +708,7 @@ class Scale(Widget, tkinter.Scale): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... # config must be copy/pasted, otherwise ttk.Scale().config is mypy error (don't know why) - @overload # type: ignore + @overload # type: ignore[override] def config( self, cnf: dict[str, Any] | None = ..., @@ -742,7 +742,7 @@ class Scrollbar(Widget, tkinter.Scrollbar): style: str = ..., takefocus: tkinter._TakeFocusValue = ..., ) -> None: ... - @overload # type: ignore + @overload # type: ignore[override] def configure( self, cnf: dict[str, Any] | None = ..., @@ -756,7 +756,7 @@ class Scrollbar(Widget, tkinter.Scrollbar): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... # config must be copy/pasted, otherwise ttk.Scrollbar().config is mypy error (don't know why) - @overload # type: ignore + @overload # type: ignore[override] def config( self, cnf: dict[str, Any] | None = ..., @@ -828,7 +828,7 @@ if sys.version_info >= (3, 7): *, background: tkinter._Color = ..., # undocumented class_: str = ..., - command: Callable[[], Any] | str | list[str] | Tuple[str, ...] = ..., + command: Callable[[], Any] | str | list[str] | tuple[str, ...] = ..., cursor: tkinter._Cursor = ..., exportselection: bool = ..., # undocumented font: _FontDescription = ..., # undocumented @@ -847,18 +847,18 @@ if sys.version_info >= (3, 7): to: float = ..., validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., validatecommand: tkinter._EntryValidateCommand = ..., - values: list[str] | Tuple[str, ...] = ..., + values: list[str] | tuple[str, ...] = ..., width: int = ..., # undocumented wrap: bool = ..., xscrollcommand: tkinter._XYScrollCommand = ..., ) -> None: ... - @overload # type: ignore + @overload # type: ignore[override] def configure( self, cnf: dict[str, Any] | None = ..., *, background: tkinter._Color = ..., - command: Callable[[], Any] | str | list[str] | Tuple[str, ...] = ..., + command: Callable[[], Any] | str | list[str] | tuple[str, ...] = ..., cursor: tkinter._Cursor = ..., exportselection: bool = ..., font: _FontDescription = ..., @@ -876,14 +876,14 @@ if sys.version_info >= (3, 7): to: float = ..., validate: Literal["none", "focus", "focusin", "focusout", "key", "all"] = ..., validatecommand: tkinter._EntryValidateCommand = ..., - values: list[str] | Tuple[str, ...] = ..., + values: list[str] | tuple[str, ...] = ..., width: int = ..., wrap: bool = ..., xscrollcommand: tkinter._XYScrollCommand = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... - config = configure # type: ignore + config = configure # type: ignore[assignment] def set(self, value: Any) -> None: ... class _TreeviewItemDict(TypedDict): @@ -922,9 +922,9 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): master: tkinter.Misc | None = ..., *, class_: str = ..., - columns: str | list[str] | Tuple[str, ...] = ..., + columns: str | list[str] | tuple[str, ...] = ..., cursor: tkinter._Cursor = ..., - displaycolumns: str | list[str] | Tuple[str, ...] | list[int] | Tuple[int, ...] | Literal["#all"] = ..., + displaycolumns: str | list[str] | tuple[str, ...] | list[int] | tuple[int, ...] | Literal["#all"] = ..., height: int = ..., name: str = ..., padding: tkinter._Padding = ..., @@ -933,7 +933,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): # # 'tree headings' is same as ['tree', 'headings'], and I wouldn't be # surprised if someone is using it. - show: Literal["tree", "headings", "tree headings", ""] | list[str] | Tuple[str, ...] = ..., + show: Literal["tree", "headings", "tree headings", ""] | list[str] | tuple[str, ...] = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., xscrollcommand: tkinter._XYScrollCommand = ..., @@ -944,13 +944,13 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): self, cnf: dict[str, Any] | None = ..., *, - columns: str | list[str] | Tuple[str, ...] = ..., + columns: str | list[str] | tuple[str, ...] = ..., cursor: tkinter._Cursor = ..., - displaycolumns: str | list[str] | Tuple[str, ...] | list[int] | Tuple[int, ...] | Literal["#all"] = ..., + displaycolumns: str | list[str] | tuple[str, ...] | list[int] | tuple[int, ...] | Literal["#all"] = ..., height: int = ..., padding: tkinter._Padding = ..., selectmode: Literal["extended", "browse", "none"] = ..., - show: Literal["tree", "headings", "tree headings", ""] | list[str] | Tuple[str, ...] = ..., + show: Literal["tree", "headings", "tree headings", ""] | list[str] | tuple[str, ...] = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., xscrollcommand: tkinter._XYScrollCommand = ..., @@ -959,8 +959,8 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure - def bbox(self, item, column: _TreeviewColumnId | None = ...) -> tuple[int, int, int, int] | Literal[""]: ... # type: ignore - def get_children(self, item: str | None = ...) -> Tuple[str, ...]: ... + def bbox(self, item, column: _TreeviewColumnId | None = ...) -> tuple[int, int, int, int] | Literal[""]: ... # type: ignore[override] + def get_children(self, item: str | None = ...) -> tuple[str, ...]: ... def set_children(self, item: str, *newchildren: str) -> None: ... @overload def column(self, column: _TreeviewColumnId, option: Literal["width", "minwidth"]) -> int: ... @@ -987,7 +987,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def delete(self, *items: str) -> None: ... def detach(self, *items: str) -> None: ... def exists(self, item: str) -> bool: ... - @overload # type: ignore + @overload # type: ignore[override] def focus(self, item: None = ...) -> str: ... # can return empty string @overload def focus(self, item: str) -> Literal[""]: ... @@ -1027,20 +1027,20 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): id: str = ..., # same as iid text: str = ..., image: tkinter._ImageSpec = ..., - values: list[Any] | Tuple[Any, ...] = ..., + values: list[Any] | tuple[Any, ...] = ..., open: bool = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., ) -> str: ... @overload def item(self, item: str, option: Literal["text"]) -> str: ... @overload def item(self, item: str, option: Literal["image"]) -> tuple[str] | Literal[""]: ... @overload - def item(self, item: str, option: Literal["values"]) -> Tuple[Any, ...] | Literal[""]: ... + def item(self, item: str, option: Literal["values"]) -> tuple[Any, ...] | Literal[""]: ... @overload def item(self, item: str, option: Literal["open"]) -> bool: ... # actually 0 or 1 @overload - def item(self, item: str, option: Literal["tags"]) -> Tuple[str, ...] | Literal[""]: ... + def item(self, item: str, option: Literal["tags"]) -> tuple[str, ...] | Literal[""]: ... @overload def item(self, item: str, option: str) -> Any: ... @overload @@ -1051,9 +1051,9 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): *, text: str = ..., image: tkinter._ImageSpec = ..., - values: list[Any] | Tuple[Any, ...] | Literal[""] = ..., + values: list[Any] | tuple[Any, ...] | Literal[""] = ..., open: bool = ..., - tags: str | list[str] | Tuple[str, ...] = ..., + tags: str | list[str] | tuple[str, ...] = ..., ) -> _TreeviewItemDict | None: ... def move(self, item: str, parent: str, index: int) -> None: ... reattach = move @@ -1062,13 +1062,13 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def prev(self, item: str) -> str: ... # returning empty string means first item def see(self, item: str) -> None: ... if sys.version_info >= (3, 8): - def selection(self) -> Tuple[str, ...]: ... + def selection(self) -> tuple[str, ...]: ... else: - def selection(self, selop: Any | None = ..., items: Any | None = ...) -> Tuple[str, ...]: ... - def selection_set(self, items: str | list[str] | Tuple[str, ...]) -> None: ... - def selection_add(self, items: str | list[str] | Tuple[str, ...]) -> None: ... - def selection_remove(self, items: str | list[str] | Tuple[str, ...]) -> None: ... - def selection_toggle(self, items: str | list[str] | Tuple[str, ...]) -> None: ... + def selection(self, selop: Any | None = ..., items: Any | None = ...) -> tuple[str, ...]: ... + def selection_set(self, items: str | list[str] | tuple[str, ...]) -> None: ... + def selection_add(self, items: str | list[str] | tuple[str, ...]) -> None: ... + def selection_remove(self, items: str | list[str] | tuple[str, ...]) -> None: ... + def selection_toggle(self, items: str | list[str] | tuple[str, ...]) -> None: ... @overload def set(self, item: str, column: None = ..., value: None = ...) -> dict[str, Any]: ... @overload @@ -1104,7 +1104,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): image: tkinter._ImageSpec = ..., ) -> _TreeviewTagDict | Any: ... # can be None but annoying to check @overload - def tag_has(self, tagname: str, item: None = ...) -> Tuple[str, ...]: ... + def tag_has(self, tagname: str, item: None = ...) -> tuple[str, ...]: ... @overload def tag_has(self, tagname: str, item: str) -> bool: ... @@ -1119,7 +1119,7 @@ class LabeledScale(Frame): from_: float = ..., to: float = ..., *, - compound: Literal["top"] | Literal["bottom"] = ..., + compound: Literal["top", "bottom"] = ..., **kw: Any, ) -> None: ... # destroy is overridden, signature does not change @@ -1134,7 +1134,7 @@ class OptionMenu(Menubutton): *values: str, # rest of these are keyword-only because *args syntax used above style: str = ..., - direction: Literal["above"] | Literal["below"] | Literal["left"] | Literal["right"] | Literal["flush"] = ..., + direction: Literal["above", "below", "left", "right", "flush"] = ..., command: Callable[[tkinter.StringVar], Any] | None = ..., ) -> None: ... # configure, config, cget, destroy are inherited from Menubutton diff --git a/mypy/typeshed/stdlib/token.pyi b/mypy/typeshed/stdlib/token.pyi index 90381833511b..9451015e9df5 100644 --- a/mypy/typeshed/stdlib/token.pyi +++ b/mypy/typeshed/stdlib/token.pyi @@ -71,6 +71,8 @@ if sys.version_info >= (3, 8): TYPE_IGNORE: int COLONEQUAL: int EXACT_TOKEN_TYPES: dict[str, int] +if sys.version_info >= (3, 10): + SOFT_KEYWORD: int def ISTERMINAL(x: int) -> bool: ... def ISNONTERMINAL(x: int) -> bool: ... diff --git a/mypy/typeshed/stdlib/tokenize.pyi b/mypy/typeshed/stdlib/tokenize.pyi index a8294adb653f..7614ebfe403e 100644 --- a/mypy/typeshed/stdlib/tokenize.pyi +++ b/mypy/typeshed/stdlib/tokenize.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import StrOrBytesPath from builtins import open as _builtin_open from token import * # noqa: F403 -from typing import Any, Callable, Generator, Iterable, NamedTuple, Pattern, Sequence, TextIO, Tuple, Union +from typing import Any, Callable, Generator, Iterable, NamedTuple, Pattern, Sequence, TextIO, Union if sys.version_info < (3, 7): COMMENT: int @@ -12,7 +12,7 @@ if sys.version_info < (3, 7): cookie_re: Pattern[str] blank_re: Pattern[bytes] -_Position = Tuple[int, int] +_Position = tuple[int, int] class _TokenInfo(NamedTuple): type: int diff --git a/mypy/typeshed/stdlib/trace.pyi b/mypy/typeshed/stdlib/trace.pyi index bab75c9ada8d..ee8dffa67820 100644 --- a/mypy/typeshed/stdlib/trace.pyi +++ b/mypy/typeshed/stdlib/trace.pyi @@ -1,13 +1,13 @@ import sys import types from _typeshed import StrPath -from typing import Any, Callable, Mapping, Optional, Sequence, Tuple, TypeVar +from typing import Any, Callable, Mapping, Optional, Sequence, TypeVar from typing_extensions import ParamSpec _T = TypeVar("_T") _P = ParamSpec("_P") _localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] -_fileModuleFunction = Tuple[str, Optional[str], str] +_fileModuleFunction = tuple[str, Optional[str], str] class CoverageResults: def __init__( @@ -43,9 +43,9 @@ class Trace: self, cmd: str | types.CodeType, globals: Mapping[str, Any] | None = ..., locals: Mapping[str, Any] | None = ... ) -> None: ... if sys.version_info >= (3, 9): - def runfunc(self, __func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... # type: ignore + def runfunc(self, __func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... else: - def runfunc(self, func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... # type: ignore + def runfunc(self, func: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs) -> _T: ... def file_module_function_of(self, frame: types.FrameType) -> _fileModuleFunction: ... def globaltrace_trackcallers(self, frame: types.FrameType, why: str, arg: Any) -> None: ... def globaltrace_countfuncs(self, frame: types.FrameType, why: str, arg: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi index e685b09a6ae4..09d817cf2f25 100644 --- a/mypy/typeshed/stdlib/traceback.pyi +++ b/mypy/typeshed/stdlib/traceback.pyi @@ -1,31 +1,53 @@ import sys from _typeshed import SupportsWrite from types import FrameType, TracebackType -from typing import IO, Any, Generator, Iterable, Iterator, List, Mapping, Optional, Tuple, Type +from typing import IO, Any, Generator, Iterable, Iterator, Mapping, Optional, overload -_PT = Tuple[str, int, str, Optional[str]] +_PT = tuple[str, int, str, Optional[str]] def print_tb(tb: TracebackType | None, limit: int | None = ..., file: IO[str] | None = ...) -> None: ... if sys.version_info >= (3, 10): + @overload def print_exception( - __exc: Type[BaseException] | None, + __exc: type[BaseException] | None, value: BaseException | None = ..., tb: TracebackType | None = ..., limit: int | None = ..., file: IO[str] | None = ..., chain: bool = ..., ) -> None: ... + @overload + def print_exception( + __exc: BaseException, *, limit: int | None = ..., file: IO[str] | None = ..., chain: bool = ... + ) -> None: ... + @overload + def format_exception( + __exc: type[BaseException] | None, + value: BaseException | None = ..., + tb: TracebackType | None = ..., + limit: int | None = ..., + chain: bool = ..., + ) -> list[str]: ... + @overload + def format_exception(__exc: BaseException, *, limit: int | None = ..., chain: bool = ...) -> list[str]: ... else: def print_exception( - etype: Type[BaseException] | None, + etype: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None, limit: int | None = ..., file: IO[str] | None = ..., chain: bool = ..., ) -> None: ... + def format_exception( + etype: type[BaseException] | None, + value: BaseException | None, + tb: TracebackType | None, + limit: int | None = ..., + chain: bool = ..., + ) -> list[str]: ... def print_exc(limit: int | None = ..., file: IO[str] | None = ..., chain: bool = ...) -> None: ... def print_last(limit: int | None = ..., file: IO[str] | None = ..., chain: bool = ...) -> None: ... @@ -38,28 +60,10 @@ def format_list(extracted_list: list[FrameSummary]) -> list[str]: ... def print_list(extracted_list: list[FrameSummary], file: SupportsWrite[str] | None = ...) -> None: ... if sys.version_info >= (3, 10): - def format_exception_only(__exc: Type[BaseException] | None, value: BaseException | None = ...) -> list[str]: ... - -else: - def format_exception_only(etype: Type[BaseException] | None, value: BaseException | None) -> list[str]: ... - -if sys.version_info >= (3, 10): - def format_exception( - __exc: Type[BaseException] | None, - value: BaseException | None = ..., - tb: TracebackType | None = ..., - limit: int | None = ..., - chain: bool = ..., - ) -> list[str]: ... + def format_exception_only(__exc: type[BaseException] | None, value: BaseException | None = ...) -> list[str]: ... else: - def format_exception( - etype: Type[BaseException] | None, - value: BaseException | None, - tb: TracebackType | None, - limit: int | None = ..., - chain: bool = ..., - ) -> list[str]: ... + def format_exception_only(etype: type[BaseException] | None, value: BaseException | None) -> list[str]: ... def format_exc(limit: int | None = ..., chain: bool = ...) -> str: ... def format_tb(tb: TracebackType | None, limit: int | None = ...) -> list[str]: ... @@ -73,7 +77,7 @@ class TracebackException: __context__: TracebackException __suppress_context__: bool stack: StackSummary - exc_type: Type[BaseException] + exc_type: type[BaseException] filename: str lineno: int text: str @@ -82,9 +86,9 @@ class TracebackException: if sys.version_info >= (3, 10): def __init__( self, - exc_type: Type[BaseException], + exc_type: type[BaseException], exc_value: BaseException, - exc_traceback: TracebackType, + exc_traceback: TracebackType | None, *, limit: int | None = ..., lookup_lines: bool = ..., @@ -105,9 +109,9 @@ class TracebackException: else: def __init__( self, - exc_type: Type[BaseException], + exc_type: type[BaseException], exc_value: BaseException, - exc_traceback: TracebackType, + exc_traceback: TracebackType | None, *, limit: int | None = ..., lookup_lines: bool = ..., @@ -142,7 +146,7 @@ class FrameSummary(Iterable[Any]): def __getitem__(self, i: int) -> Any: ... def __iter__(self) -> Iterator[Any]: ... -class StackSummary(List[FrameSummary]): +class StackSummary(list[FrameSummary]): @classmethod def extract( cls, diff --git a/mypy/typeshed/stdlib/tracemalloc.pyi b/mypy/typeshed/stdlib/tracemalloc.pyi index ca4d5901b870..4d7bbb7994a6 100644 --- a/mypy/typeshed/stdlib/tracemalloc.pyi +++ b/mypy/typeshed/stdlib/tracemalloc.pyi @@ -1,6 +1,7 @@ import sys from _tracemalloc import * -from typing import Optional, Sequence, Tuple, Union, overload +from typing import Optional, Sequence, Union, overload +from typing_extensions import SupportsIndex def get_object_traceback(obj: object) -> Traceback | None: ... def take_snapshot() -> Snapshot: ... @@ -34,7 +35,7 @@ class StatisticDiff: traceback: Traceback def __init__(self, traceback: Traceback, size: int, size_diff: int, count: int, count_diff: int) -> None: ... -_FrameTupleT = Tuple[str, int] +_FrameTupleT = tuple[str, int] class Frame: filename: str @@ -42,9 +43,9 @@ class Frame: def __init__(self, frame: _FrameTupleT) -> None: ... if sys.version_info >= (3, 9): - _TraceTupleT = Union[Tuple[int, int, Sequence[_FrameTupleT], Optional[int]], Tuple[int, int, Sequence[_FrameTupleT]]] + _TraceTupleT = Union[tuple[int, int, Sequence[_FrameTupleT], Optional[int]], tuple[int, int, Sequence[_FrameTupleT]]] else: - _TraceTupleT = Tuple[int, int, Sequence[_FrameTupleT]] + _TraceTupleT = tuple[int, int, Sequence[_FrameTupleT]] class Trace: domain: int @@ -63,7 +64,7 @@ class Traceback(Sequence[Frame]): else: def format(self, limit: int | None = ...) -> list[str]: ... @overload - def __getitem__(self, i: int) -> Frame: ... + def __getitem__(self, i: SupportsIndex) -> Frame: ... @overload def __getitem__(self, s: slice) -> Sequence[Frame]: ... def __len__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/tty.pyi b/mypy/typeshed/stdlib/tty.pyi index c0dc418e9933..015669a68084 100644 --- a/mypy/typeshed/stdlib/tty.pyi +++ b/mypy/typeshed/stdlib/tty.pyi @@ -1,15 +1,16 @@ +import sys from typing import IO, Union -_FD = Union[int, IO[str]] +if sys.platform != "win32": + _FD = Union[int, IO[str]] -# XXX: Undocumented integer constants -IFLAG: int -OFLAG: int -CFLAG: int -LFLAG: int -ISPEED: int -OSPEED: int -CC: int - -def setraw(fd: _FD, when: int = ...) -> None: ... -def setcbreak(fd: _FD, when: int = ...) -> None: ... + # XXX: Undocumented integer constants + IFLAG: int + OFLAG: int + CFLAG: int + LFLAG: int + ISPEED: int + OSPEED: int + CC: int + def setraw(fd: _FD, when: int = ...) -> None: ... + def setcbreak(fd: _FD, when: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/turtle.pyi b/mypy/typeshed/stdlib/turtle.pyi index 9371f2a7a547..521ac5838b62 100644 --- a/mypy/typeshed/stdlib/turtle.pyi +++ b/mypy/typeshed/stdlib/turtle.pyi @@ -1,24 +1,37 @@ -from tkinter import Canvas, PhotoImage -from typing import Any, Callable, Dict, Sequence, Tuple, TypeVar, Union, overload +from _typeshed import Self +from tkinter import Canvas, Frame, Misc, PhotoImage, Scrollbar +from typing import Any, Callable, ClassVar, Sequence, Union, overload # Note: '_Color' is the alias we use for arguments and _AnyColor is the # alias we use for return types. Really, these two aliases should be the # same, but as per the "no union returns" typeshed policy, we'll return # Any instead. -_Color = Union[str, Tuple[float, float, float]] +_Color = Union[str, tuple[float, float, float]] _AnyColor = Any # TODO: Replace this with a TypedDict once it becomes standardized. -_PenState = Dict[str, Any] +_PenState = dict[str, Any] _Speed = Union[str, float] -_PolygonCoords = Sequence[Tuple[float, float]] +_PolygonCoords = Sequence[tuple[float, float]] # TODO: Type this more accurately # Vec2D is actually a custom subclass of 'tuple'. -Vec2D = Tuple[float, float] +Vec2D = tuple[float, float] -class TurtleScreenBase(object): +# Does not actually inherit from Canvas, but dynamically gets all methods of Canvas +class ScrolledCanvas(Canvas, Frame): # type: ignore[misc] + bg: str + hscroll: Scrollbar + vscroll: Scrollbar + def __init__( + self, master: Misc | None, width: int = ..., height: int = ..., canvwidth: int = ..., canvheight: int = ... + ) -> None: ... + canvwidth: int + canvheight: int + def reset(self, canvwidth: int | None = ..., canvheight: int | None = ..., bg: str | None = ...) -> None: ... + +class TurtleScreenBase: cv: Canvas canvwidth: int canvheight: int @@ -34,7 +47,7 @@ class TurtleScreenBase(object): class Terminator(Exception): ... class TurtleGraphicsError(Exception): ... -class Shape(object): +class Shape: def __init__(self, type_: str, data: _PolygonCoords | PhotoImage | None = ...) -> None: ... def addcomponent(self, poly: _PolygonCoords, fill: _Color, outline: _Color | None = ...) -> None: ... @@ -92,7 +105,7 @@ class TurtleScreen(TurtleScreenBase): def onkeypress(self, fun: Callable[[], Any], key: str | None = ...) -> None: ... onkeyrelease = onkey -class TNavigator(object): +class TNavigator: START_ORIENTATION: dict[str, Vec2D] DEFAULT_MODE: str DEFAULT_ANGLEOFFSET: int @@ -136,7 +149,7 @@ class TNavigator(object): setposition = goto seth = setheading -class TPen(object): +class TPen: def __init__(self, resizemode: str = ...) -> None: ... @overload def resizemode(self, rmode: None = ...) -> str: ... @@ -178,7 +191,7 @@ class TPen(object): def isvisible(self) -> bool: ... # Note: signatures 1 and 2 overlap unsafely when no arguments are provided @overload - def pen(self) -> _PenState: ... # type: ignore + def pen(self) -> _PenState: ... # type: ignore[misc] @overload def pen( self, @@ -203,9 +216,9 @@ class TPen(object): st = showturtle ht = hideturtle -_T = TypeVar("_T") - class RawTurtle(TPen, TNavigator): + screen: TurtleScreen + screens: ClassVar[list[TurtleScreen]] def __init__( self, canvas: Canvas | TurtleScreen | None = ..., shape: str = ..., undobuffersize: int = ..., visible: bool = ... ) -> None: ... @@ -213,14 +226,14 @@ class RawTurtle(TPen, TNavigator): def setundobuffer(self, size: int | None) -> None: ... def undobufferentries(self) -> int: ... def clear(self) -> None: ... - def clone(self: _T) -> _T: ... + def clone(self: Self) -> Self: ... @overload def shape(self, name: None = ...) -> str: ... @overload def shape(self, name: str) -> None: ... # Unsafely overlaps when no arguments are provided @overload - def shapesize(self) -> tuple[float, float, float]: ... # type: ignore + def shapesize(self) -> tuple[float, float, float]: ... # type: ignore[misc] @overload def shapesize( self, stretch_wid: float | None = ..., stretch_len: float | None = ..., outline: float | None = ... @@ -231,7 +244,7 @@ class RawTurtle(TPen, TNavigator): def shearfactor(self, shear: float) -> None: ... # Unsafely overlaps when no arguments are provided @overload - def shapetransform(self) -> tuple[float, float, float, float]: ... # type: ignore + def shapetransform(self) -> tuple[float, float, float, float]: ... # type: ignore[misc] @overload def shapetransform( self, t11: float | None = ..., t12: float | None = ..., t21: float | None = ..., t22: float | None = ... @@ -247,7 +260,7 @@ class RawTurtle(TPen, TNavigator): # a compound stamp or not. So, as per the "no Union return" policy, # we return Any. def stamp(self) -> Any: ... - def clearstamp(self, stampid: int | Tuple[int, ...]) -> None: ... + def clearstamp(self, stampid: int | tuple[int, ...]) -> None: ... def clearstamps(self, n: int | None = ...) -> None: ... def filling(self) -> bool: ... def begin_fill(self) -> None: ... @@ -258,7 +271,7 @@ class RawTurtle(TPen, TNavigator): def end_poly(self) -> None: ... def get_poly(self) -> _PolygonCoords | None: ... def getscreen(self) -> TurtleScreen: ... - def getturtle(self: _T) -> _T: ... + def getturtle(self: Self) -> Self: ... getpen = getturtle def onclick(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... def onrelease(self, fun: Callable[[float, float], Any], btn: int = ..., add: bool | None = ...) -> None: ... @@ -449,7 +462,7 @@ def isvisible() -> bool: ... # Note: signatures 1 and 2 overlap unsafely when no arguments are provided @overload -def pen() -> _PenState: ... # type: ignore +def pen() -> _PenState: ... # type: ignore[misc] @overload def pen( pen: _PenState | None = ..., @@ -485,7 +498,7 @@ def shape(name: str) -> None: ... # Unsafely overlaps when no arguments are provided @overload -def shapesize() -> tuple[float, float, float]: ... # type: ignore +def shapesize() -> tuple[float, float, float]: ... # type: ignore[misc] @overload def shapesize(stretch_wid: float | None = ..., stretch_len: float | None = ..., outline: float | None = ...) -> None: ... @overload @@ -495,7 +508,7 @@ def shearfactor(shear: float) -> None: ... # Unsafely overlaps when no arguments are provided @overload -def shapetransform() -> tuple[float, float, float, float]: ... # type: ignore +def shapetransform() -> tuple[float, float, float, float]: ... # type: ignore[misc] @overload def shapetransform( t11: float | None = ..., t12: float | None = ..., t21: float | None = ..., t22: float | None = ... @@ -512,7 +525,7 @@ def tilt(angle: float) -> None: ... # a compound stamp or not. So, as per the "no Union return" policy, # we return Any. def stamp() -> Any: ... -def clearstamp(stampid: int | Tuple[int, ...]) -> None: ... +def clearstamp(stampid: int | tuple[int, ...]) -> None: ... def clearstamps(n: int | None = ...) -> None: ... def filling() -> bool: ... def begin_fill() -> None: ... diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index 899024f2dd4d..a2926fac6aaa 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import SupportsKeysAndGetItem from importlib.abc import _LoaderProtocol from importlib.machinery import ModuleSpec from typing import ( @@ -15,8 +16,6 @@ from typing import ( KeysView, Mapping, MutableSequence, - Tuple, - Type, TypeVar, ValuesView, overload, @@ -25,7 +24,6 @@ from typing_extensions import Literal, ParamSpec, final # Note, all classes "defined" here require special handling. -_T = TypeVar("_T") _T1 = TypeVar("_T1") _T2 = TypeVar("_T2") _T_co = TypeVar("_T_co", covariant=True) @@ -36,14 +34,15 @@ _V_co = TypeVar("_V_co", covariant=True) @final class _Cell: - __hash__: None # type: ignore + __hash__: None # type: ignore[assignment] cell_contents: Any +# Make sure this class definition stays roughly in line with `builtins.function` @final class FunctionType: - __closure__: Tuple[_Cell, ...] | None + __closure__: tuple[_Cell, ...] | None __code__: CodeType - __defaults__: Tuple[Any, ...] | None + __defaults__: tuple[Any, ...] | None __dict__: dict[str, Any] __globals__: dict[str, Any] __name__: str @@ -55,18 +54,16 @@ class FunctionType: code: CodeType, globals: dict[str, Any], name: str | None = ..., - argdefs: Tuple[object, ...] | None = ..., - closure: Tuple[_Cell, ...] | None = ..., + argdefs: tuple[object, ...] | None = ..., + closure: tuple[_Cell, ...] | None = ..., ) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def __get__(self, obj: object | None, type: type | None) -> MethodType: ... + def __get__(self, obj: object | None, type: type | None = ...) -> MethodType: ... LambdaType = FunctionType @final class CodeType: - """Create a code object. Not for the faint of heart.""" - co_argcount: int if sys.version_info >= (3, 8): co_posonlyargcount: int @@ -75,15 +72,15 @@ class CodeType: co_stacksize: int co_flags: int co_code: bytes - co_consts: Tuple[Any, ...] - co_names: Tuple[str, ...] - co_varnames: Tuple[str, ...] + co_consts: tuple[Any, ...] + co_names: tuple[str, ...] + co_varnames: tuple[str, ...] co_filename: str co_name: str co_firstlineno: int co_lnotab: bytes - co_freevars: Tuple[str, ...] - co_cellvars: Tuple[str, ...] + co_freevars: tuple[str, ...] + co_cellvars: tuple[str, ...] if sys.version_info >= (3, 8): def __init__( self, @@ -94,15 +91,15 @@ class CodeType: stacksize: int, flags: int, codestring: bytes, - constants: Tuple[Any, ...], - names: Tuple[str, ...], - varnames: Tuple[str, ...], + constants: tuple[Any, ...], + names: tuple[str, ...], + varnames: tuple[str, ...], filename: str, name: str, firstlineno: int, lnotab: bytes, - freevars: Tuple[str, ...] = ..., - cellvars: Tuple[str, ...] = ..., + freevars: tuple[str, ...] = ..., + cellvars: tuple[str, ...] = ..., ) -> None: ... else: def __init__( @@ -113,17 +110,40 @@ class CodeType: stacksize: int, flags: int, codestring: bytes, - constants: Tuple[Any, ...], - names: Tuple[str, ...], - varnames: Tuple[str, ...], + constants: tuple[Any, ...], + names: tuple[str, ...], + varnames: tuple[str, ...], filename: str, name: str, firstlineno: int, lnotab: bytes, - freevars: Tuple[str, ...] = ..., - cellvars: Tuple[str, ...] = ..., + freevars: tuple[str, ...] = ..., + cellvars: tuple[str, ...] = ..., ) -> None: ... - if sys.version_info >= (3, 8): + if sys.version_info >= (3, 10): + def replace( + self, + *, + co_argcount: int = ..., + co_posonlyargcount: int = ..., + co_kwonlyargcount: int = ..., + co_nlocals: int = ..., + co_stacksize: int = ..., + co_flags: int = ..., + co_firstlineno: int = ..., + co_code: bytes = ..., + co_consts: tuple[Any, ...] = ..., + co_names: tuple[str, ...] = ..., + co_varnames: tuple[str, ...] = ..., + co_freevars: tuple[str, ...] = ..., + co_cellvars: tuple[str, ...] = ..., + co_filename: str = ..., + co_name: str = ..., + co_linetable: object = ..., + ) -> CodeType: ... + def co_lines(self) -> Iterator[tuple[int, int, int | None]]: ... + co_linetable: object + elif sys.version_info >= (3, 8): def replace( self, *, @@ -135,11 +155,11 @@ class CodeType: co_flags: int = ..., co_firstlineno: int = ..., co_code: bytes = ..., - co_consts: Tuple[Any, ...] = ..., - co_names: Tuple[str, ...] = ..., - co_varnames: Tuple[str, ...] = ..., - co_freevars: Tuple[str, ...] = ..., - co_cellvars: Tuple[str, ...] = ..., + co_consts: tuple[Any, ...] = ..., + co_names: tuple[str, ...] = ..., + co_varnames: tuple[str, ...] = ..., + co_freevars: tuple[str, ...] = ..., + co_cellvars: tuple[str, ...] = ..., co_filename: str = ..., co_name: str = ..., co_lnotab: bytes = ..., @@ -149,8 +169,8 @@ class CodeType: @final class MappingProxyType(Mapping[_KT, _VT_co], Generic[_KT, _VT_co]): - __hash__: None # type: ignore - def __init__(self, mapping: Mapping[_KT, _VT_co]) -> None: ... + __hash__: None # type: ignore[assignment] + def __init__(self, mapping: SupportsKeysAndGetItem[_KT, _VT_co]) -> None: ... def __getitem__(self, k: _KT) -> _VT_co: ... def __iter__(self) -> Iterator[_KT]: ... def __len__(self) -> int: ... @@ -165,7 +185,7 @@ class MappingProxyType(Mapping[_KT, _VT_co], Generic[_KT, _VT_co]): def __ror__(self, __value: Mapping[_T1, _T2]) -> dict[_KT | _T1, _VT_co | _T2]: ... class SimpleNamespace: - __hash__: None # type: ignore + __hash__: None # type: ignore[assignment] def __init__(self, **kwargs: Any) -> None: ... def __getattribute__(self, name: str) -> Any: ... def __setattr__(self, name: str, value: Any) -> None: ... @@ -197,7 +217,7 @@ class GeneratorType(Generator[_T_co, _T_contra, _V_co]): def send(self, __arg: _T_contra) -> _T_co: ... @overload def throw( - self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... + self, __typ: type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... ) -> _T_co: ... @overload def throw(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> _T_co: ... @@ -213,11 +233,13 @@ class AsyncGeneratorType(AsyncGenerator[_T_co, _T_contra]): def asend(self, __val: _T_contra) -> Awaitable[_T_co]: ... @overload def athrow( - self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... + self, __typ: type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... ) -> Awaitable[_T_co]: ... @overload def athrow(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> Awaitable[_T_co]: ... def aclose(self) -> Awaitable[None]: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, __item: Any) -> GenericAlias: ... @final class CoroutineType(Coroutine[_T_co, _T_contra, _V_co]): @@ -232,31 +254,27 @@ class CoroutineType(Coroutine[_T_co, _T_contra, _V_co]): def send(self, __arg: _T_contra) -> _T_co: ... @overload def throw( - self, __typ: Type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... + self, __typ: type[BaseException], __val: BaseException | object = ..., __tb: TracebackType | None = ... ) -> _T_co: ... @overload def throw(self, __typ: BaseException, __val: None = ..., __tb: TracebackType | None = ...) -> _T_co: ... class _StaticFunctionType: - """Fictional type to correct the type of MethodType.__func__. - - FunctionType is a descriptor, so mypy follows the descriptor protocol and - converts MethodType.__func__ back to MethodType (the return type of - FunctionType.__get__). But this is actually a special case; MethodType is - implemented in C and its attribute access doesn't go through - __getattribute__. - - By wrapping FunctionType in _StaticFunctionType, we get the right result; - similar to wrapping a function in staticmethod() at runtime to prevent it - being bound as a method. - """ - + # Fictional type to correct the type of MethodType.__func__. + # FunctionType is a descriptor, so mypy follows the descriptor protocol and + # converts MethodType.__func__ back to MethodType (the return type of + # FunctionType.__get__). But this is actually a special case; MethodType is + # implemented in C and its attribute access doesn't go through + # __getattribute__. + # By wrapping FunctionType in _StaticFunctionType, we get the right result; + # similar to wrapping a function in staticmethod() at runtime to prevent it + # being bound as a method. def __get__(self, obj: object | None, type: type | None) -> FunctionType: ... @final class MethodType: - __closure__: Tuple[_Cell, ...] | None # inherited from the added function - __defaults__: Tuple[Any, ...] | None # inherited from the added function + __closure__: tuple[_Cell, ...] | None # inherited from the added function + __defaults__: tuple[Any, ...] | None # inherited from the added function __func__: _StaticFunctionType __self__: object __name__: str # inherited from the added function @@ -328,7 +346,10 @@ class FrameType: f_code: CodeType f_globals: dict[str, Any] f_lasti: int - f_lineno: int + # see discussion in #6769: f_lineno *can* sometimes be None, + # but you should probably file a bug report with CPython if you encounter it being None in the wild. + # An `int | None` annotation here causes too many false-positive errors. + f_lineno: int | Any f_locals: dict[str, Any] f_trace: Callable[[FrameType, str, Any], Any] | None if sys.version_info >= (3, 7): @@ -359,18 +380,18 @@ if sys.version_info >= (3, 7): kwds: dict[str, Any] | None = ..., exec_body: Callable[[dict[str, Any]], None] | None = ..., ) -> type: ... - def resolve_bases(bases: Iterable[object]) -> Tuple[Any, ...]: ... + def resolve_bases(bases: Iterable[object]) -> tuple[Any, ...]: ... else: def new_class( name: str, - bases: Tuple[type, ...] = ..., + bases: tuple[type, ...] = ..., kwds: dict[str, Any] | None = ..., exec_body: Callable[[dict[str, Any]], None] | None = ..., ) -> type: ... def prepare_class( - name: str, bases: Tuple[type, ...] = ..., kwds: dict[str, Any] | None = ... + name: str, bases: tuple[type, ...] = ..., kwds: dict[str, Any] | None = ... ) -> tuple[type, dict[str, Any], dict[str, Any]]: ... # Actually a different type, but `property` is special and we want that too. @@ -381,10 +402,11 @@ _R = TypeVar("_R") _P = ParamSpec("_P") # it's not really an Awaitable, but can be used in an await expression. Real type: Generator & Awaitable +# The type: ignore is due to overlapping overloads, not the use of ParamSpec @overload -def coroutine(func: Callable[_P, Generator[_R, Any, Any]]) -> Callable[_P, Awaitable[_R]]: ... # type: ignore +def coroutine(func: Callable[_P, Generator[_R, Any, Any]]) -> Callable[_P, Awaitable[_R]]: ... # type: ignore[misc] @overload -def coroutine(func: _Fn) -> _Fn: ... # type: ignore +def coroutine(func: _Fn) -> _Fn: ... if sys.version_info >= (3, 8): CellType = _Cell @@ -392,8 +414,8 @@ if sys.version_info >= (3, 8): if sys.version_info >= (3, 9): class GenericAlias: __origin__: type - __args__: Tuple[Any, ...] - __parameters__: Tuple[Any, ...] + __args__: tuple[Any, ...] + __parameters__: tuple[Any, ...] def __init__(self, origin: type, args: Any) -> None: ... def __getattr__(self, name: str) -> Any: ... # incomplete @@ -407,6 +429,6 @@ if sys.version_info >= (3, 10): NotImplementedType = _NotImplementedType # noqa F811 from builtins @final class UnionType: - __args__: Tuple[Any, ...] + __args__: tuple[Any, ...] def __or__(self, obj: Any) -> UnionType: ... def __ror__(self, obj: Any) -> UnionType: ... diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 4656add7ec21..c4f9819edc45 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -1,5 +1,6 @@ import collections # Needed by aliases like DefaultDict, see mypy issue 2986 import sys +from _typeshed import Self, SupportsKeysAndGetItem 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, final as _final @@ -10,30 +11,29 @@ if sys.version_info >= (3, 7): if sys.version_info >= (3, 9): from types import GenericAlias -# Definitions of special type checking related constructs. Their definitions -# are not used, so their value does not matter. - Any = object() class TypeVar: __name__: str - __bound__: Type[Any] | None - __constraints__: Tuple[Type[Any], ...] + __bound__: Any | None + __constraints__: Tuple[Any, ...] __covariant__: bool __contravariant__: bool def __init__( - self, - name: str, - *constraints: Type[Any], - bound: None | Type[Any] | str = ..., - covariant: bool = ..., - contravariant: bool = ..., + self, name: str, *constraints: Any, bound: Any | None = ..., covariant: bool = ..., contravariant: bool = ... ) -> None: ... + if sys.version_info >= (3, 10): + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... +# Used for an undocumented mypy feature. Does not exist at runtime. _promote = object() class _SpecialForm: def __getitem__(self, typeargs: Any) -> object: ... + if sys.version_info >= (3, 10): + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... _F = TypeVar("_F", bound=Callable[..., Any]) _P = _ParamSpec("_P") @@ -70,19 +70,28 @@ if sys.version_info >= (3, 10): def __init__(self, origin: ParamSpec) -> None: ... class ParamSpec: __name__: str - __bound__: Type[Any] | None + __bound__: Any | None __covariant__: bool __contravariant__: bool - def __init__( - self, name: str, *, bound: None | Type[Any] | str = ..., contravariant: bool = ..., covariant: bool = ... - ) -> None: ... + def __init__(self, name: str, *, bound: Any | None = ..., contravariant: bool = ..., covariant: bool = ...) -> None: ... @property def args(self) -> ParamSpecArgs: ... @property def kwargs(self) -> ParamSpecKwargs: ... + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... Concatenate: _SpecialForm = ... TypeAlias: _SpecialForm = ... TypeGuard: _SpecialForm = ... + class NewType: + def __init__(self, name: str, tp: type) -> None: ... + def __call__(self, x: _T) -> _T: ... + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... + __supertype__: type + +else: + def NewType(name: str, tp: Type[_T]) -> Type[_T]: ... # These type variables are used by the container types. _S = TypeVar("_S") @@ -96,7 +105,7 @@ _T_contra = TypeVar("_T_contra", contravariant=True) # Ditto contravariant. _TC = TypeVar("_TC", bound=Type[object]) def no_type_check(arg: _F) -> _F: ... -def no_type_check_decorator(decorator: Callable[_P, _T]) -> Callable[_P, _T]: ... # type: ignore +def no_type_check_decorator(decorator: Callable[_P, _T]) -> Callable[_P, _T]: ... # type: ignore[misc] # Type aliases and type constructors @@ -120,7 +129,15 @@ if sys.version_info >= (3, 9): Annotated: _SpecialForm = ... # Predefined type variables. -AnyStr = TypeVar("AnyStr", str, bytes) +AnyStr = TypeVar("AnyStr", str, bytes) # noqa: Y001 + +if sys.version_info >= (3, 8): + # This class did actually exist in 3.7, but had a different base. + # We'll just pretend it didn't exist though: the main external use case for _ProtocolMeta is + # to inherit from for your own custom protocol metaclasses. If you're using 3.7, at runtime + # you'd use typing_extensions.Protocol, which would be unrelated to typing._ProtocolMeta and + # so you'd run into metaclass conflicts at runtime if you used typing._ProtocolMeta. + class _ProtocolMeta(ABCMeta): ... # Abstract base classes. @@ -246,7 +263,7 @@ class Coroutine(Awaitable[_V_co], Generic[_T_co, _T_contra, _V_co]): @abstractmethod def close(self) -> None: ... -# NOTE: This type does not exist in typing.py or PEP 484. +# NOTE: This type does not exist in typing.py or PEP 484 but mypy needs it to exist. # The parameters correspond to Generator, but the 4th is the original type. class AwaitableGenerator( Awaitable[_V_co], Generator[_T_co, _T_contra, _V_co], Generic[_T_co, _T_contra, _V_co, _S], metaclass=ABCMeta @@ -451,9 +468,13 @@ class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): @overload def pop(self, __key: _KT) -> _VT: ... @overload - def pop(self, __key: _KT, __default: _VT | _T = ...) -> _VT | _T: ... + def pop(self, __key: _KT, __default: _VT | _T) -> _VT | _T: ... def popitem(self) -> tuple[_KT, _VT]: ... - def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ... + # This overload should be allowed only if the value type is compatible with None. + @overload + def setdefault(self: MutableMapping[_KT, _T | None], __key: _KT) -> _T | None: ... + @overload + def setdefault(self, __key: _KT, __default: _VT) -> _VT: ... # 'update' used to take a Union, but using overloading is better. # The second overloaded type here is a bit too general, because # Mapping[Tuple[_KT, _VT], W] is a subclass of Iterable[Tuple[_KT, _VT]], @@ -464,8 +485,16 @@ class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]): # mypy will commit to using the first overload when the argument is # known to be a Mapping with unknown type parameters, which is closer # to the behavior we want. See mypy issue #1430. + # + # Various mapping classes have __ior__ methods that should be kept roughly in line with .update(): + # -- dict.__ior__ + # -- os._Environ.__ior__ + # -- collections.UserDict.__ior__ + # -- collections.ChainMap.__ior__ + # -- weakref.WeakValueDictionary.__ior__ + # -- weakref.WeakKeyDictionary.__ior__ @overload - def update(self, __m: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... + def update(self, __m: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... @overload def update(self, __m: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... @overload @@ -475,6 +504,9 @@ Text = str TYPE_CHECKING = True +# In stubs, the arguments of the IO class are marked as positional-only. +# This differs from runtime, but better reflects the fact that in reality +# classes deriving from IO use different names for the arguments. class IO(Iterator[AnyStr], Generic[AnyStr]): # TODO use abstract properties @property @@ -492,27 +524,27 @@ class IO(Iterator[AnyStr], Generic[AnyStr]): @abstractmethod def isatty(self) -> bool: ... @abstractmethod - def read(self, n: int = ...) -> AnyStr: ... + def read(self, __n: int = ...) -> AnyStr: ... @abstractmethod def readable(self) -> bool: ... @abstractmethod - def readline(self, limit: int = ...) -> AnyStr: ... + def readline(self, __limit: int = ...) -> AnyStr: ... @abstractmethod - def readlines(self, hint: int = ...) -> list[AnyStr]: ... + def readlines(self, __hint: int = ...) -> list[AnyStr]: ... @abstractmethod - def seek(self, offset: int, whence: int = ...) -> int: ... + def seek(self, __offset: int, __whence: int = ...) -> int: ... @abstractmethod def seekable(self) -> bool: ... @abstractmethod def tell(self) -> int: ... @abstractmethod - def truncate(self, size: int | None = ...) -> int: ... + def truncate(self, __size: int | None = ...) -> int: ... @abstractmethod def writable(self) -> bool: ... @abstractmethod - def write(self, s: AnyStr) -> int: ... + def write(self, __s: AnyStr) -> int: ... @abstractmethod - def writelines(self, lines: Iterable[AnyStr]) -> None: ... + def writelines(self, __lines: Iterable[AnyStr]) -> None: ... @abstractmethod def __next__(self) -> AnyStr: ... @abstractmethod @@ -521,7 +553,7 @@ class IO(Iterator[AnyStr], Generic[AnyStr]): def __enter__(self) -> IO[AnyStr]: ... @abstractmethod def __exit__( - self, t: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, __t: Type[BaseException] | None, __value: BaseException | None, __traceback: TracebackType | None ) -> bool | None: ... class BinaryIO(IO[bytes]): @@ -550,7 +582,7 @@ class Match(Generic[AnyStr]): pos: int endpos: int lastindex: int | None - lastgroup: AnyStr | None + lastgroup: str | None string: AnyStr # The regular expression object whose match() or search() method produced @@ -598,7 +630,7 @@ class Pattern(Generic[AnyStr]): def search(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Match[AnyStr] | None: ... def match(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Match[AnyStr] | None: ... def fullmatch(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Match[AnyStr] | None: ... - def split(self, string: AnyStr, maxsplit: int = ...) -> list[AnyStr]: ... + def split(self, string: AnyStr, maxsplit: int = ...) -> list[AnyStr | Any]: ... def findall(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> list[Any]: ... def finditer(self, string: AnyStr, pos: int = ..., endpos: int = ...) -> Iterator[Match[AnyStr]]: ... @overload @@ -657,9 +689,11 @@ def cast(typ: object, val: Any) -> Any: ... # Type constructors -# NamedTuple is special-cased in the type checker class NamedTuple(Tuple[Any, ...]): - _field_types: collections.OrderedDict[str, Type[Any]] + if sys.version_info < (3, 8): + _field_types: collections.OrderedDict[str, type] + elif sys.version_info < (3, 9): + _field_types: dict[str, type] _field_defaults: dict[str, Any] _fields: Tuple[str, ...] _source: str @@ -673,11 +707,11 @@ class NamedTuple(Tuple[Any, ...]): def _asdict(self) -> dict[str, Any]: ... else: def _asdict(self) -> collections.OrderedDict[str, Any]: ... - def _replace(self: _T, **kwargs: Any) -> _T: ... + def _replace(self: Self, **kwargs: Any) -> Self: ... # Internal mypy fallback type for all typed dicts (does not exist at runtime) class _TypedDict(Mapping[str, object], metaclass=ABCMeta): - def copy(self: _T) -> _T: ... + def copy(self: Self) -> Self: ... # Using NoReturn so that only calls using mypy plugin hook that specialize the signature # can go through. def setdefault(self, k: NoReturn, default: object) -> object: ... @@ -688,10 +722,8 @@ class _TypedDict(Mapping[str, object], metaclass=ABCMeta): def items(self) -> ItemsView[str, object]: ... def keys(self) -> KeysView[str]: ... def values(self) -> ValuesView[object]: ... - def __or__(self: _T, __value: _T) -> _T: ... - def __ior__(self: _T, __value: _T) -> _T: ... - -def NewType(name: str, tp: Type[_T]) -> Type[_T]: ... + def __or__(self: Self, __value: Self) -> Self: ... + def __ior__(self: Self, __value: Self) -> Self: ... # This itself is only available during type checking def type_check_only(func_or_cls: _F) -> _F: ... @@ -704,14 +736,16 @@ if sys.version_info >= (3, 7): __forward_value__: Any | None __forward_is_argument__: bool if sys.version_info >= (3, 9): - # The module argument was added in Python 3.9.7. - def __init__(self, arg: str, is_argument: bool = ..., module: Any | None = ...) -> None: ... + # The module and is_class arguments were added in later Python 3.9 versions. + def __init__(self, arg: str, is_argument: bool = ..., module: Any | None = ..., *, is_class: bool = ...) -> None: ... else: def __init__(self, arg: str, is_argument: bool = ...) -> None: ... def _evaluate(self, globalns: dict[str, Any] | None, localns: dict[str, Any] | None) -> Any | None: ... def __eq__(self, other: Any) -> bool: ... def __hash__(self) -> int: ... - def __repr__(self) -> str: ... + if sys.version_info >= (3, 11): + def __or__(self, other: Any) -> _SpecialForm: ... + def __ror__(self, other: Any) -> _SpecialForm: ... if sys.version_info >= (3, 10): - def is_typeddict(tp: Any) -> bool: ... + def is_typeddict(tp: object) -> bool: ... diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index ce407f996022..8a1dcd4fc477 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -1,6 +1,7 @@ import abc import sys -from typing import ( +from _typeshed import Self as TypeshedSelf # see #6932 for why the alias cannot have a leading underscore +from typing import ( # noqa Y022 TYPE_CHECKING as TYPE_CHECKING, Any, AsyncContextManager as AsyncContextManager, @@ -22,7 +23,6 @@ from typing import ( NewType as NewType, NoReturn as NoReturn, Text as Text, - Tuple, Type as Type, TypeVar, ValuesView, @@ -32,7 +32,7 @@ from typing import ( _T = TypeVar("_T") _F = TypeVar("_F", bound=Callable[..., Any]) -_TC = TypeVar("_TC", bound=Type[object]) +_TC = TypeVar("_TC", bound=type[object]) class _SpecialForm: def __getitem__(self, typeargs: Any) -> Any: ... @@ -53,12 +53,17 @@ Literal: _SpecialForm = ... def IntVar(name: str) -> Any: ... # returns a new TypeVar +if sys.version_info < (3, 8): + # Technically in 3.6 this inherited from GenericMeta. But let's not reflect that, since + # type checkers tend to assume that Protocols all have the ABCMeta metaclass. + class _ProtocolMeta(abc.ABCMeta): ... + # 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: ... + def copy(self: TypeshedSelf) -> TypeshedSelf: ... # Using NoReturn so that only calls using mypy plugin hook that specialize the signature # can go through. def setdefault(self, k: NoReturn, default: object) -> object: ... @@ -82,7 +87,7 @@ if sys.version_info >= (3, 7): localns: dict[str, Any] | None = ..., include_extras: bool = ..., ) -> dict[str, Any]: ... - def get_args(tp: Any) -> Tuple[Any, ...]: ... + def get_args(tp: Any) -> tuple[Any, ...]: ... def get_origin(tp: Any) -> Any | None: ... Annotated: _SpecialForm = ... @@ -95,7 +100,13 @@ class SupportsIndex(Protocol, metaclass=abc.ABCMeta): # PEP 612 support for Python < 3.9 if sys.version_info >= (3, 10): - from typing import Concatenate as Concatenate, ParamSpec as ParamSpec, TypeAlias as TypeAlias, TypeGuard as TypeGuard + from typing import ( + Concatenate as Concatenate, + ParamSpec as ParamSpec, + TypeAlias as TypeAlias, + TypeGuard as TypeGuard, + is_typeddict as is_typeddict, + ) else: class ParamSpecArgs: __origin__: ParamSpec @@ -105,11 +116,11 @@ else: def __init__(self, origin: ParamSpec) -> None: ... class ParamSpec: __name__: str - __bound__: Type[Any] | None + __bound__: type[Any] | None __covariant__: bool __contravariant__: bool def __init__( - self, name: str, *, bound: None | Type[Any] | str = ..., contravariant: bool = ..., covariant: bool = ... + self, name: str, *, bound: None | type[Any] | str = ..., contravariant: bool = ..., covariant: bool = ... ) -> None: ... @property def args(self) -> ParamSpecArgs: ... @@ -118,3 +129,4 @@ else: Concatenate: _SpecialForm = ... TypeAlias: _SpecialForm = ... TypeGuard: _SpecialForm = ... + def is_typeddict(tp: object) -> bool: ... diff --git a/mypy/typeshed/stdlib/unicodedata.pyi b/mypy/typeshed/stdlib/unicodedata.pyi index 66c93f7439f7..ead25ba4062c 100644 --- a/mypy/typeshed/stdlib/unicodedata.pyi +++ b/mypy/typeshed/stdlib/unicodedata.pyi @@ -24,7 +24,7 @@ def name(__chr: str, __default: _T = ...) -> str | _T: ... def normalize(__form: str, __unistr: str) -> str: ... def numeric(__chr: str, __default: _T = ...) -> float | _T: ... -class UCD(object): +class UCD: # The methods below are constructed from the same array in C # (unicodedata_functions) and hence identical to the methods above. unidata_version: str diff --git a/mypy/typeshed/stdlib/unittest/__init__.pyi b/mypy/typeshed/stdlib/unittest/__init__.pyi index 8f0ef896fa0c..2a9e002cb7fb 100644 --- a/mypy/typeshed/stdlib/unittest/__init__.pyi +++ b/mypy/typeshed/stdlib/unittest/__init__.pyi @@ -1,5 +1,4 @@ import sys -from unittest.async_case import * from .case import ( FunctionTestCase as FunctionTestCase, @@ -10,15 +9,27 @@ from .case import ( skipIf as skipIf, skipUnless as skipUnless, ) +from .loader import ( + TestLoader as TestLoader, + defaultTestLoader as defaultTestLoader, + findTestCases as findTestCases, + getTestCaseNames as getTestCaseNames, + makeSuite as makeSuite, +) +from .main import TestProgram as TestProgram, main as main +from .result import TestResult as TestResult +from .runner import TextTestResult as TextTestResult, TextTestRunner as TextTestRunner +from .signals import ( + installHandler as installHandler, + registerResult as registerResult, + removeHandler as removeHandler, + removeResult as removeResult, +) +from .suite import BaseTestSuite as BaseTestSuite, TestSuite as TestSuite if sys.version_info >= (3, 8): - from .case import addModuleCleanup as addModuleCleanup + from unittest.async_case import * -from unittest.loader import * -from unittest.main import * -from unittest.result import TestResult as TestResult -from unittest.runner import * -from unittest.signals import * -from unittest.suite import * + from .case import addModuleCleanup as addModuleCleanup def load_tests(loader: TestLoader, tests: TestSuite, pattern: str | None) -> TestSuite: ... diff --git a/mypy/typeshed/stdlib/unittest/_log.pyi b/mypy/typeshed/stdlib/unittest/_log.pyi new file mode 100644 index 000000000000..947a2158ddff --- /dev/null +++ b/mypy/typeshed/stdlib/unittest/_log.pyi @@ -0,0 +1,27 @@ +import logging +import sys +from types import TracebackType +from typing import ClassVar, Generic, NamedTuple, TypeVar +from unittest.case import TestCase + +_L = TypeVar("_L", None, _LoggingWatcher) + +class _LoggingWatcher(NamedTuple): + records: list[logging.LogRecord] + output: list[str] + +class _AssertLogsContext(Generic[_L]): + LOGGING_FORMAT: ClassVar[str] + test_case: TestCase + logger_name: str + level: int + msg: None + if sys.version_info >= (3, 10): + def __init__(self, test_case: TestCase, logger_name: str, level: int, no_logs: bool) -> None: ... + no_logs: bool + else: + def __init__(self, test_case: TestCase, logger_name: str, level: int) -> None: ... + def __enter__(self) -> _L: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> bool | None: ... diff --git a/mypy/typeshed/stdlib/unittest/async_case.pyi b/mypy/typeshed/stdlib/unittest/async_case.pyi index bdf534b37c9f..f61256633e8c 100644 --- a/mypy/typeshed/stdlib/unittest/async_case.pyi +++ b/mypy/typeshed/stdlib/unittest/async_case.pyi @@ -1,10 +1,8 @@ -import sys from typing import Any, Awaitable, Callable from .case import TestCase -if sys.version_info >= (3, 8): - class IsolatedAsyncioTestCase(TestCase): - async def asyncSetUp(self) -> None: ... - async def asyncTearDown(self) -> None: ... - def addAsyncCleanup(self, __func: Callable[..., Awaitable[Any]], *args: Any, **kwargs: Any) -> None: ... +class IsolatedAsyncioTestCase(TestCase): + async def asyncSetUp(self) -> None: ... + async def asyncTearDown(self) -> None: ... + def addAsyncCleanup(self, __func: Callable[..., Awaitable[Any]], *args: Any, **kwargs: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/unittest/case.pyi b/mypy/typeshed/stdlib/unittest/case.pyi index 2ae07144373c..2ff01a32b90a 100644 --- a/mypy/typeshed/stdlib/unittest/case.pyi +++ b/mypy/typeshed/stdlib/unittest/case.pyi @@ -3,13 +3,14 @@ import logging import sys import unittest.result from _typeshed import Self -from collections.abc import Set # equivalent to typing.AbstractSet, not builtins.set +from collections.abc import Set as AbstractSet from contextlib import AbstractContextManager from types import TracebackType from typing import ( Any, AnyStr, Callable, + ClassVar, Container, Generic, Iterable, @@ -18,8 +19,6 @@ from typing import ( NoReturn, Pattern, Sequence, - Tuple, - Type, TypeVar, overload, ) @@ -31,6 +30,33 @@ if sys.version_info >= (3, 9): _E = TypeVar("_E", bound=BaseException) _FT = TypeVar("_FT", bound=Callable[..., Any]) +DIFF_OMITTED: str + +class _BaseTestCaseContext: + def __init__(self, test_case: TestCase) -> None: ... + +if sys.version_info >= (3, 9): + from unittest._log import _AssertLogsContext, _LoggingWatcher +else: + # Unused dummy for _AssertLogsContext. Starting with Python 3.10, + # this is generic over the logging watcher, but in lower versions + # the watcher is hard-coded. + _L = TypeVar("_L") + class _LoggingWatcher(NamedTuple): + records: list[logging.LogRecord] + output: list[str] + class _AssertLogsContext(_BaseTestCaseContext, Generic[_L]): + LOGGING_FORMAT: ClassVar[str] + test_case: TestCase + logger_name: str + level: int + msg: None + def __init__(self, test_case: TestCase, logger_name: str, level: int) -> None: ... + def __enter__(self) -> _LoggingWatcher: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> bool | None: ... + if sys.version_info >= (3, 8): def addModuleCleanup(__function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... def doModuleCleanups() -> None: ... @@ -44,7 +70,7 @@ class SkipTest(Exception): def __init__(self, reason: str) -> None: ... class TestCase: - failureException: Type[BaseException] + failureException: type[BaseException] longMessage: bool maxDiff: int | None # undocumented @@ -74,26 +100,26 @@ class TestCase: def assertIsNotNone(self, obj: Any, msg: Any = ...) -> None: ... def assertIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = ...) -> None: ... def assertNotIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = ...) -> None: ... - def assertIsInstance(self, obj: Any, cls: type | Tuple[type, ...], msg: Any = ...) -> None: ... - def assertNotIsInstance(self, obj: Any, cls: type | Tuple[type, ...], msg: Any = ...) -> None: ... + def assertIsInstance(self, obj: Any, cls: type | tuple[type, ...], msg: Any = ...) -> None: ... + def assertNotIsInstance(self, obj: Any, cls: type | tuple[type, ...], msg: Any = ...) -> None: ... def assertGreater(self, a: Any, b: Any, msg: Any = ...) -> None: ... def assertGreaterEqual(self, a: Any, b: Any, msg: Any = ...) -> None: ... def assertLess(self, a: Any, b: Any, msg: Any = ...) -> None: ... def assertLessEqual(self, a: Any, b: Any, msg: Any = ...) -> None: ... @overload - def assertRaises( # type: ignore + def assertRaises( # type: ignore[misc] self, - expected_exception: Type[BaseException] | Tuple[Type[BaseException], ...], + expected_exception: type[BaseException] | tuple[type[BaseException], ...], callable: Callable[..., Any], *args: Any, **kwargs: Any, ) -> None: ... @overload - def assertRaises(self, expected_exception: Type[_E] | Tuple[Type[_E], ...], msg: Any = ...) -> _AssertRaisesContext[_E]: ... + def assertRaises(self, expected_exception: type[_E] | tuple[type[_E], ...], msg: Any = ...) -> _AssertRaisesContext[_E]: ... @overload - def assertRaisesRegex( # type: ignore + def assertRaisesRegex( # type: ignore[misc] self, - expected_exception: Type[BaseException] | Tuple[Type[BaseException], ...], + expected_exception: type[BaseException] | tuple[type[BaseException], ...], expected_regex: str | bytes | Pattern[str] | Pattern[bytes], callable: Callable[..., Any], *args: Any, @@ -102,20 +128,20 @@ class TestCase: @overload def assertRaisesRegex( self, - expected_exception: Type[_E] | Tuple[Type[_E], ...], + expected_exception: type[_E] | tuple[type[_E], ...], expected_regex: str | bytes | Pattern[str] | Pattern[bytes], msg: Any = ..., ) -> _AssertRaisesContext[_E]: ... @overload - def assertWarns( # type: ignore - self, expected_warning: Type[Warning] | Tuple[Type[Warning], ...], callable: Callable[..., Any], *args: Any, **kwargs: Any + def assertWarns( # type: ignore[misc] + self, expected_warning: type[Warning] | tuple[type[Warning], ...], callable: Callable[..., Any], *args: Any, **kwargs: Any ) -> None: ... @overload - def assertWarns(self, expected_warning: Type[Warning] | Tuple[Type[Warning], ...], msg: Any = ...) -> _AssertWarnsContext: ... + def assertWarns(self, expected_warning: type[Warning] | tuple[type[Warning], ...], msg: Any = ...) -> _AssertWarnsContext: ... @overload - def assertWarnsRegex( # type: ignore + def assertWarnsRegex( # type: ignore[misc] self, - expected_warning: Type[Warning] | Tuple[Type[Warning], ...], + expected_warning: type[Warning] | tuple[type[Warning], ...], expected_regex: str | bytes | Pattern[str] | Pattern[bytes], callable: Callable[..., Any], *args: Any, @@ -124,11 +150,17 @@ class TestCase: @overload def assertWarnsRegex( self, - expected_warning: Type[Warning] | Tuple[Type[Warning], ...], + expected_warning: type[Warning] | tuple[type[Warning], ...], expected_regex: str | bytes | Pattern[str] | Pattern[bytes], msg: Any = ..., ) -> _AssertWarnsContext: ... - def assertLogs(self, logger: str | logging.Logger | None = ..., level: int | str | None = ...) -> _AssertLogsContext: ... + def assertLogs( + self, logger: str | logging.Logger | None = ..., level: int | str | None = ... + ) -> _AssertLogsContext[_LoggingWatcher]: ... + if sys.version_info >= (3, 10): + def assertNoLogs( + self, logger: str | logging.Logger | None = ..., level: int | str | None = ... + ) -> _AssertLogsContext[None]: ... @overload def assertAlmostEqual( self, first: float, second: float, places: int | None = ..., msg: Any = ..., delta: float | None = ... @@ -160,14 +192,14 @@ class TestCase: def assertRegex(self, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... def assertNotRegex(self, text: AnyStr, unexpected_regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... def assertCountEqual(self, first: Iterable[Any], second: Iterable[Any], msg: Any = ...) -> None: ... - def addTypeEqualityFunc(self, typeobj: Type[Any], function: Callable[..., None]) -> None: ... + def addTypeEqualityFunc(self, typeobj: type[Any], function: Callable[..., None]) -> None: ... def assertMultiLineEqual(self, first: str, second: str, msg: Any = ...) -> None: ... def assertSequenceEqual( - self, seq1: Sequence[Any], seq2: Sequence[Any], msg: Any = ..., seq_type: Type[Sequence[Any]] | None = ... + self, seq1: Sequence[Any], seq2: Sequence[Any], msg: Any = ..., seq_type: type[Sequence[Any]] | None = ... ) -> None: ... def assertListEqual(self, list1: list[Any], list2: list[Any], msg: Any = ...) -> None: ... - def assertTupleEqual(self, tuple1: Tuple[Any, ...], tuple2: Tuple[Any, ...], msg: Any = ...) -> None: ... - def assertSetEqual(self, set1: Set[object], set2: Set[object], msg: Any = ...) -> None: ... + def assertTupleEqual(self, tuple1: tuple[Any, ...], tuple2: tuple[Any, ...], msg: Any = ...) -> None: ... + def assertSetEqual(self, set1: AbstractSet[object], set2: AbstractSet[object], msg: Any = ...) -> None: ... def assertDictEqual(self, d1: Mapping[Any, object], d2: Mapping[Any, object], msg: Any = ...) -> None: ... def fail(self, msg: Any = ...) -> NoReturn: ... def countTestCases(self) -> int: ... @@ -186,49 +218,53 @@ class TestCase: def doClassCleanups(cls) -> None: ... def _formatMessage(self, msg: str | None, standardMsg: str) -> str: ... # undocumented def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented - # below is deprecated - def failUnlessEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... - def assertEquals(self, first: Any, second: Any, msg: Any = ...) -> None: ... - def failIfEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... - def assertNotEquals(self, first: Any, second: Any, msg: Any = ...) -> None: ... - def failUnless(self, expr: bool, msg: Any = ...) -> None: ... - def assert_(self, expr: bool, msg: Any = ...) -> None: ... - def failIf(self, expr: bool, msg: Any = ...) -> None: ... - @overload - def failUnlessRaises( # type: ignore - self, - exception: Type[BaseException] | Tuple[Type[BaseException], ...], - callable: Callable[..., Any] = ..., - *args: Any, - **kwargs: Any, - ) -> None: ... - @overload - def failUnlessRaises(self, exception: Type[_E] | Tuple[Type[_E], ...], msg: Any = ...) -> _AssertRaisesContext[_E]: ... - def failUnlessAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... - def assertAlmostEquals(self, first: float, second: float, places: int = ..., msg: Any = ..., delta: float = ...) -> None: ... - def failIfAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... - def assertNotAlmostEquals( - self, first: float, second: float, places: int = ..., msg: Any = ..., delta: float = ... - ) -> None: ... - def assertRegexpMatches(self, text: AnyStr, regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... - def assertNotRegexpMatches(self, text: AnyStr, regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... - @overload - def assertRaisesRegexp( # type: ignore - self, - exception: Type[BaseException] | Tuple[Type[BaseException], ...], - expected_regex: str | bytes | Pattern[str] | Pattern[bytes], - callable: Callable[..., Any], - *args: Any, - **kwargs: Any, - ) -> None: ... - @overload - def assertRaisesRegexp( - self, - exception: Type[_E] | Tuple[Type[_E], ...], - expected_regex: str | bytes | Pattern[str] | Pattern[bytes], - msg: Any = ..., - ) -> _AssertRaisesContext[_E]: ... - def assertDictContainsSubset(self, subset: Mapping[Any, Any], dictionary: Mapping[Any, Any], msg: object = ...) -> None: ... + if sys.version_info < (3, 11): + def failUnlessEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... + def assertEquals(self, first: Any, second: Any, msg: Any = ...) -> None: ... + def failIfEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... + def assertNotEquals(self, first: Any, second: Any, msg: Any = ...) -> None: ... + def failUnless(self, expr: bool, msg: Any = ...) -> None: ... + def assert_(self, expr: bool, msg: Any = ...) -> None: ... + def failIf(self, expr: bool, msg: Any = ...) -> None: ... + @overload + def failUnlessRaises( # type: ignore[misc] + self, + exception: type[BaseException] | tuple[type[BaseException], ...], + callable: Callable[..., Any] = ..., + *args: Any, + **kwargs: Any, + ) -> None: ... + @overload + def failUnlessRaises(self, exception: type[_E] | tuple[type[_E], ...], msg: Any = ...) -> _AssertRaisesContext[_E]: ... + def failUnlessAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... + def assertAlmostEquals( + self, first: float, second: float, places: int = ..., msg: Any = ..., delta: float = ... + ) -> None: ... + def failIfAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... + def assertNotAlmostEquals( + self, first: float, second: float, places: int = ..., msg: Any = ..., delta: float = ... + ) -> None: ... + def assertRegexpMatches(self, text: AnyStr, regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... + def assertNotRegexpMatches(self, text: AnyStr, regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... + @overload + def assertRaisesRegexp( # type: ignore[misc] + self, + exception: type[BaseException] | tuple[type[BaseException], ...], + expected_regex: str | bytes | Pattern[str] | Pattern[bytes], + callable: Callable[..., Any], + *args: Any, + **kwargs: Any, + ) -> None: ... + @overload + def assertRaisesRegexp( + self, + exception: type[_E] | tuple[type[_E], ...], + expected_regex: str | bytes | Pattern[str] | Pattern[bytes], + msg: Any = ..., + ) -> _AssertRaisesContext[_E]: ... + def assertDictContainsSubset( + self, subset: Mapping[Any, Any], dictionary: Mapping[Any, Any], msg: object = ... + ) -> None: ... class FunctionTestCase(TestCase): def __init__( @@ -240,15 +276,11 @@ class FunctionTestCase(TestCase): ) -> None: ... def runTest(self) -> None: ... -class _LoggingWatcher(NamedTuple): - records: list[logging.LogRecord] - output: list[str] - class _AssertRaisesContext(Generic[_E]): exception: _E 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 ) -> bool: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -260,18 +292,5 @@ class _AssertWarnsContext: warnings: list[WarningMessage] 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: ... - -class _AssertLogsContext: - LOGGING_FORMAT: str - records: list[logging.LogRecord] - output: list[str] - def __init__(self, test_case: TestCase, logger_name: str, level: int) -> None: ... - if sys.version_info >= (3, 10): - def __enter__(self) -> _LoggingWatcher | None: ... - else: - def __enter__(self) -> _LoggingWatcher: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... diff --git a/mypy/typeshed/stdlib/unittest/loader.pyi b/mypy/typeshed/stdlib/unittest/loader.pyi index d3cb4cef733b..8b3c82233cec 100644 --- a/mypy/typeshed/stdlib/unittest/loader.pyi +++ b/mypy/typeshed/stdlib/unittest/loader.pyi @@ -3,13 +3,15 @@ import unittest.case import unittest.result import unittest.suite from types import ModuleType -from typing import Any, Callable, List, Sequence, Type +from typing import Any, Callable, Pattern, Sequence _SortComparisonMethod = Callable[[str, str], int] -_SuiteClass = Callable[[List[unittest.case.TestCase]], unittest.suite.TestSuite] +_SuiteClass = Callable[[list[unittest.case.TestCase]], unittest.suite.TestSuite] + +VALID_MODULE_NAME: Pattern[str] class TestLoader: - errors: list[Type[BaseException]] + errors: list[type[BaseException]] testMethodPrefix: str sortTestMethodsUsing: _SortComparisonMethod @@ -17,18 +19,18 @@ class TestLoader: testNamePatterns: list[str] | None suiteClass: _SuiteClass - def loadTestsFromTestCase(self, testCaseClass: Type[unittest.case.TestCase]) -> unittest.suite.TestSuite: ... + def loadTestsFromTestCase(self, testCaseClass: type[unittest.case.TestCase]) -> unittest.suite.TestSuite: ... def loadTestsFromModule(self, module: ModuleType, *args: Any, pattern: Any = ...) -> unittest.suite.TestSuite: ... def loadTestsFromName(self, name: str, module: ModuleType | None = ...) -> unittest.suite.TestSuite: ... def loadTestsFromNames(self, names: Sequence[str], module: ModuleType | None = ...) -> unittest.suite.TestSuite: ... - def getTestCaseNames(self, testCaseClass: Type[unittest.case.TestCase]) -> Sequence[str]: ... + def getTestCaseNames(self, testCaseClass: type[unittest.case.TestCase]) -> Sequence[str]: ... def discover(self, start_dir: str, pattern: str = ..., top_level_dir: str | None = ...) -> unittest.suite.TestSuite: ... defaultTestLoader: TestLoader if sys.version_info >= (3, 7): def getTestCaseNames( - testCaseClass: Type[unittest.case.TestCase], + testCaseClass: type[unittest.case.TestCase], prefix: str, sortUsing: _SortComparisonMethod = ..., testNamePatterns: list[str] | None = ..., @@ -36,11 +38,11 @@ if sys.version_info >= (3, 7): else: def getTestCaseNames( - testCaseClass: Type[unittest.case.TestCase], prefix: str, sortUsing: _SortComparisonMethod = ... + testCaseClass: type[unittest.case.TestCase], prefix: str, sortUsing: _SortComparisonMethod = ... ) -> Sequence[str]: ... def makeSuite( - testCaseClass: Type[unittest.case.TestCase], + testCaseClass: type[unittest.case.TestCase], prefix: str = ..., sortUsing: _SortComparisonMethod = ..., suiteClass: _SuiteClass = ..., diff --git a/mypy/typeshed/stdlib/unittest/main.pyi b/mypy/typeshed/stdlib/unittest/main.pyi index cd887cec27d0..16c48ebdd990 100644 --- a/mypy/typeshed/stdlib/unittest/main.pyi +++ b/mypy/typeshed/stdlib/unittest/main.pyi @@ -4,7 +4,10 @@ import unittest.loader import unittest.result import unittest.suite from types import ModuleType -from typing import Any, Iterable, Protocol, Type +from typing import Any, Iterable, Protocol + +MAIN_EXAMPLES: str +MODULE_EXAMPLES: str class _TestRunner(Protocol): def run(self, test: unittest.suite.TestSuite | unittest.case.TestCase) -> unittest.result.TestResult: ... @@ -27,7 +30,7 @@ class TestProgram: module: None | str | ModuleType = ..., defaultTest: str | Iterable[str] | None = ..., argv: list[str] | None = ..., - testRunner: Type[_TestRunner] | _TestRunner | None = ..., + testRunner: type[_TestRunner] | _TestRunner | None = ..., testLoader: unittest.loader.TestLoader = ..., exit: bool = ..., verbosity: int = ..., diff --git a/mypy/typeshed/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi index 567ce346f464..eb6942d5d876 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -1,27 +1,61 @@ import sys -from typing import Any, Callable, Generic, Iterable, List, Mapping, Sequence, Tuple, Type, TypeVar, overload +from typing import Any, Awaitable, Callable, Generic, Iterable, Mapping, Sequence, TypeVar, overload _T = TypeVar("_T") -_TT = TypeVar("_TT", bound=Type[Any]) +_TT = TypeVar("_TT", bound=type[Any]) _R = TypeVar("_R") -__all__ = [ - "Mock", - "MagicMock", - "patch", - "sentinel", - "DEFAULT", - "ANY", - "call", - "create_autospec", - "AsyncMock", - "FILTER_DIR", - "NonCallableMock", - "NonCallableMagicMock", - "mock_open", - "PropertyMock", - "seal", -] +if sys.version_info >= (3, 8): + __all__ = ( + "Mock", + "MagicMock", + "patch", + "sentinel", + "DEFAULT", + "ANY", + "call", + "create_autospec", + "AsyncMock", + "FILTER_DIR", + "NonCallableMock", + "NonCallableMagicMock", + "mock_open", + "PropertyMock", + "seal", + ) +elif sys.version_info >= (3, 7): + __all__ = ( + "Mock", + "MagicMock", + "patch", + "sentinel", + "DEFAULT", + "ANY", + "call", + "create_autospec", + "FILTER_DIR", + "NonCallableMock", + "NonCallableMagicMock", + "mock_open", + "PropertyMock", + "seal", + ) +else: + __all__ = ( + "Mock", + "MagicMock", + "patch", + "sentinel", + "DEFAULT", + "ANY", + "call", + "create_autospec", + "FILTER_DIR", + "NonCallableMock", + "NonCallableMagicMock", + "mock_open", + "PropertyMock", + ) __version__: str FILTER_DIR: Any @@ -39,7 +73,7 @@ class _Sentinel: sentinel: Any DEFAULT: Any -class _Call(Tuple[Any, ...]): +class _Call(tuple[Any, ...]): def __new__( cls, value: Any = ..., name: Any | None = ..., parent: Any | None = ..., two: bool = ..., from_kall: bool = ... ) -> Any: ... @@ -53,32 +87,29 @@ class _Call(Tuple[Any, ...]): __ne__: Any def __call__(self, *args: Any, **kwargs: Any) -> _Call: ... def __getattr__(self, attr: Any) -> Any: ... - def count(self, *args: Any, **kwargs: Any) -> Any: ... - def index(self, *args: Any, **kwargs: Any) -> Any: ... + if sys.version_info >= (3, 8): + @property + def args(self): ... + @property + def kwargs(self): ... def call_list(self) -> Any: ... call: _Call -class _CallList(List[_Call]): +class _CallList(list[_Call]): def __contains__(self, value: Any) -> bool: ... -class _MockIter: - obj: Any - def __init__(self, obj: Any) -> None: ... - def __iter__(self) -> Any: ... - def __next__(self) -> Any: ... - class Base: def __init__(self, *args: Any, **kwargs: Any) -> None: ... -class NonCallableMock(Base, Any): # type: ignore +class NonCallableMock(Base, Any): def __new__(__cls, *args: Any, **kw: Any) -> NonCallableMock: ... def __init__( self, - spec: list[str] | object | Type[object] | None = ..., + spec: list[str] | object | type[object] | None = ..., wraps: Any | None = ..., name: str | None = ..., - spec_set: list[str] | object | Type[object] | None = ..., + spec_set: list[str] | object | type[object] | None = ..., parent: NonCallableMock | None = ..., _spec_state: Any | None = ..., _new_name: str = ..., @@ -124,7 +155,7 @@ class NonCallableMock(Base, Any): # type: ignore call_args_list: _CallList mock_calls: _CallList def _format_mock_call_signature(self, args: Any, kwargs: Any) -> str: ... - def _call_matcher(self, _call: Tuple[_Call, ...]) -> _Call: ... + def _call_matcher(self, _call: tuple[_Call, ...]) -> _Call: ... def _get_child_mock(self, **kw: Any) -> NonCallableMock: ... class CallableMixin(Base): @@ -143,7 +174,10 @@ class CallableMixin(Base): _new_parent: Any | None = ..., **kwargs: Any, ) -> None: ... - def __call__(_mock_self, *args: Any, **kwargs: Any) -> Any: ... + if sys.version_info >= (3, 8): + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + else: + def __call__(_mock_self, *args: Any, **kwargs: Any) -> Any: ... class Mock(CallableMixin, NonCallableMock): ... @@ -162,25 +196,45 @@ class _patch(Generic[_T]): additional_patchers: Any # If new==DEFAULT, self is _patch[Any]. Ideally we'd be able to add an overload for it so that self is _patch[MagicMock], # but that's impossible with the current type system. - def __init__( - self: _patch[_T], - getter: Callable[[], Any], - attribute: str, - new: _T, - spec: Any | None, - create: bool, - spec_set: Any | None, - autospec: Any | None, - new_callable: Any | None, - kwargs: Mapping[str, Any], - ) -> None: ... + if sys.version_info >= (3, 10): + def __init__( + self: _patch[_T], + getter: Callable[[], Any], + attribute: str, + new: _T, + spec: Any | None, + create: bool, + spec_set: Any | None, + autospec: Any | None, + new_callable: Any | None, + kwargs: Mapping[str, Any], + *, + unsafe: bool = ..., + ) -> None: ... + else: + def __init__( + self: _patch[_T], + getter: Callable[[], Any], + attribute: str, + new: _T, + spec: Any | None, + create: bool, + spec_set: Any | None, + autospec: Any | None, + new_callable: Any | None, + kwargs: Mapping[str, Any], + ) -> None: ... def copy(self) -> _patch[_T]: ... @overload def __call__(self, func: _TT) -> _TT: ... @overload def __call__(self, func: Callable[..., _R]) -> Callable[..., _R]: ... + if sys.version_info >= (3, 8): + def decoration_helper(self, patched, args, keywargs): ... def decorate_class(self, klass: _TT) -> _TT: ... def decorate_callable(self, func: Callable[..., _R]) -> Callable[..., _R]: ... + if sys.version_info >= (3, 8): + def decorate_async_callable(self, func: Callable[..., Awaitable[_R]]) -> Callable[..., Awaitable[_R]]: ... def get_original(self) -> tuple[Any, bool]: ... target: Any temp_original: Any @@ -204,13 +258,13 @@ class _patch_dict: class _patcher: TEST_PREFIX: str - dict: Type[_patch_dict] + dict: type[_patch_dict] if sys.version_info >= (3, 8): # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any]. # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock], # but that's impossible with the current type system. @overload - def __call__( # type: ignore + def __call__( # type: ignore[misc] self, target: Any, new: _T, @@ -222,7 +276,7 @@ class _patcher: **kwargs: Any, ) -> _patch[_T]: ... @overload - def __call__( # type: ignore + def __call__( self, target: Any, *, @@ -235,7 +289,7 @@ class _patcher: ) -> _patch[MagicMock | AsyncMock]: ... else: @overload - def __call__( # type: ignore + def __call__( # type: ignore[misc] self, target: Any, new: _T, @@ -247,7 +301,7 @@ class _patcher: **kwargs: Any, ) -> _patch[_T]: ... @overload - def __call__( # type: ignore + def __call__( self, target: Any, *, @@ -260,7 +314,7 @@ class _patcher: ) -> _patch[MagicMock]: ... if sys.version_info >= (3, 8): @overload - def object( # type: ignore + def object( # type: ignore[misc] self, target: Any, attribute: str, @@ -273,7 +327,7 @@ class _patcher: **kwargs: Any, ) -> _patch[_T]: ... @overload - def object( # type: ignore + def object( self, target: Any, attribute: str, @@ -287,7 +341,7 @@ class _patcher: ) -> _patch[MagicMock | AsyncMock]: ... else: @overload - def object( # type: ignore + def object( # type: ignore[misc] self, target: Any, attribute: str, @@ -300,7 +354,7 @@ class _patcher: **kwargs: Any, ) -> _patch[_T]: ... @overload - def object( # type: ignore + def object( self, target: Any, attribute: str, @@ -352,15 +406,16 @@ if sys.version_info >= (3, 8): await_args_list: _CallList class AsyncMagicMixin(MagicMixin): def __init__(self, *args: Any, **kw: Any) -> None: ... - class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): ... + class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): ... # type: ignore # argument disparities between base classes class MagicProxy: name: Any parent: Any - def __init__(self, name: Any, parent: Any) -> None: ... - def __call__(self, *args: Any, **kwargs: Any) -> Any: ... - def create_mock(self) -> Any: ... - def __get__(self, obj: Any, _type: Any | None = ...) -> Any: ... + def __init__(self, name, parent) -> None: ... + if sys.version_info < (3, 8): + def __call__(self, *args: Any, **kwargs: Any) -> Any: ... + def create_mock(self): ... + def __get__(self, obj, _type: Any | None = ...): ... class _ANY: def __eq__(self, other: Any) -> bool: ... diff --git a/mypy/typeshed/stdlib/unittest/result.pyi b/mypy/typeshed/stdlib/unittest/result.pyi index 20c43cf38aa4..1c79f8ab648c 100644 --- a/mypy/typeshed/stdlib/unittest/result.pyi +++ b/mypy/typeshed/stdlib/unittest/result.pyi @@ -1,11 +1,14 @@ import unittest.case from types import TracebackType -from typing import Any, Callable, TextIO, Tuple, Type, TypeVar, Union +from typing import Any, Callable, TextIO, TypeVar, Union -_SysExcInfoType = Union[Tuple[Type[BaseException], BaseException, TracebackType], Tuple[None, None, None]] +_SysExcInfoType = Union[tuple[type[BaseException], BaseException, TracebackType], tuple[None, None, None]] _F = TypeVar("_F", bound=Callable[..., Any]) +STDOUT_LINE: str +STDERR_LINE: str + # undocumented def failfast(method: _F) -> _F: ... diff --git a/mypy/typeshed/stdlib/unittest/runner.pyi b/mypy/typeshed/stdlib/unittest/runner.pyi index bf8f3c05c1cd..eb6383074b8c 100644 --- a/mypy/typeshed/stdlib/unittest/runner.pyi +++ b/mypy/typeshed/stdlib/unittest/runner.pyi @@ -1,7 +1,7 @@ import unittest.case import unittest.result import unittest.suite -from typing import Callable, TextIO, Type +from typing import Callable, TextIO _ResultClassType = Callable[[TextIO, bool, int], unittest.result.TestResult] @@ -17,7 +17,7 @@ class TextTestResult(unittest.result.TestResult): def printErrors(self) -> None: ... def printErrorList(self, flavour: str, errors: tuple[unittest.case.TestCase, str]) -> None: ... -class TextTestRunner(object): +class TextTestRunner: resultclass: _ResultClassType def __init__( self, @@ -27,7 +27,7 @@ class TextTestRunner(object): failfast: bool = ..., buffer: bool = ..., resultclass: _ResultClassType | None = ..., - warnings: Type[Warning] | None = ..., + warnings: type[Warning] | None = ..., *, tb_locals: bool = ..., ) -> None: ... diff --git a/mypy/typeshed/stdlib/unittest/signals.pyi b/mypy/typeshed/stdlib/unittest/signals.pyi index 375b7d736a35..e6f5f95e1eb1 100644 --- a/mypy/typeshed/stdlib/unittest/signals.pyi +++ b/mypy/typeshed/stdlib/unittest/signals.pyi @@ -11,4 +11,4 @@ def removeResult(result: unittest.result.TestResult) -> bool: ... @overload def removeHandler(method: None = ...) -> None: ... @overload -def removeHandler(method: Callable[_P, _T]) -> Callable[_P, _T]: ... # type: ignore +def removeHandler(method: Callable[_P, _T]) -> Callable[_P, _T]: ... diff --git a/mypy/typeshed/stdlib/unittest/util.pyi b/mypy/typeshed/stdlib/unittest/util.pyi index ab6ed053a6ff..680ca24b7c33 100644 --- a/mypy/typeshed/stdlib/unittest/util.pyi +++ b/mypy/typeshed/stdlib/unittest/util.pyi @@ -1,7 +1,7 @@ -from typing import Any, Sequence, Tuple, TypeVar +from typing import Any, Sequence, TypeVar _T = TypeVar("_T") -_Mismatch = Tuple[_T, _T, int] +_Mismatch = tuple[_T, _T, int] _MAX_LENGTH: int _PLACEHOLDER_LEN: int diff --git a/mypy/typeshed/stdlib/urllib/parse.pyi b/mypy/typeshed/stdlib/urllib/parse.pyi index a2467e96c43c..613049bbbcc9 100644 --- a/mypy/typeshed/stdlib/urllib/parse.pyi +++ b/mypy/typeshed/stdlib/urllib/parse.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, AnyStr, Callable, Generic, Mapping, NamedTuple, Sequence, Tuple, Union, overload +from typing import Any, AnyStr, Callable, Generic, Mapping, NamedTuple, Sequence, Union, overload if sys.version_info >= (3, 9): from types import GenericAlias @@ -21,7 +21,7 @@ class _ResultMixinBase(Generic[AnyStr]): class _ResultMixinStr(_ResultMixinBase[str]): def encode(self, encoding: str = ..., errors: str = ...) -> _ResultMixinBytes: ... -class _ResultMixinBytes(_ResultMixinBase[str]): +class _ResultMixinBytes(_ResultMixinBase[bytes]): def decode(self, encoding: str = ..., errors: str = ...) -> _ResultMixinStr: ... class _NetlocResultMixinBase(Generic[AnyStr]): @@ -35,7 +35,7 @@ class _NetlocResultMixinBase(Generic[AnyStr]): class _NetlocResultMixinStr(_NetlocResultMixinBase[str], _ResultMixinStr): ... class _NetlocResultMixinBytes(_NetlocResultMixinBase[bytes], _ResultMixinBytes): ... -class _DefragResultBase(Tuple[Any, ...], Generic[AnyStr]): +class _DefragResultBase(tuple[Any, ...], Generic[AnyStr]): url: AnyStr fragment: AnyStr @@ -116,10 +116,10 @@ def urldefrag(url: bytes | None) -> DefragResultBytes: ... def urlencode( query: Mapping[Any, Any] | Mapping[Any, Sequence[Any]] | Sequence[tuple[Any, Any]] | Sequence[tuple[Any, Sequence[Any]]], doseq: bool = ..., - safe: AnyStr = ..., + safe: _Str = ..., encoding: str = ..., errors: str = ..., - quote_via: Callable[[str, AnyStr, str, str], str] = ..., + quote_via: Callable[[AnyStr, _Str, str, str], str] = ..., ) -> str: ... def urljoin(base: AnyStr, url: AnyStr | None, allow_fragments: bool = ...) -> AnyStr: ... @overload diff --git a/mypy/typeshed/stdlib/urllib/request.pyi b/mypy/typeshed/stdlib/urllib/request.pyi index 3c8a6facde6f..3749d7a390ea 100644 --- a/mypy/typeshed/stdlib/urllib/request.pyi +++ b/mypy/typeshed/stdlib/urllib/request.pyi @@ -4,7 +4,7 @@ from _typeshed import StrOrBytesPath from email.message import Message from http.client import HTTPMessage, HTTPResponse, _HTTPConnectionProtocol from http.cookiejar import CookieJar -from typing import IO, Any, Callable, ClassVar, Mapping, NoReturn, Pattern, Sequence, Tuple, TypeVar, overload +from typing import IO, Any, Callable, ClassVar, Mapping, NoReturn, Pattern, Sequence, TypeVar, overload from urllib.error import HTTPError from urllib.response import addclosehook, addinfourl @@ -196,9 +196,9 @@ class HTTPSHandler(AbstractHTTPHandler): def https_request(self, request: Request) -> Request: ... # undocumented class FileHandler(BaseHandler): - names: ClassVar[Tuple[str, ...] | None] # undocumented + names: ClassVar[tuple[str, ...] | None] # undocumented def file_open(self, req: Request) -> addinfourl: ... - def get_names(self) -> Tuple[str, ...]: ... # undocumented + def get_names(self) -> tuple[str, ...]: ... # undocumented def open_local_file(self, req: Request) -> addinfourl: ... # undocumented class DataHandler(BaseHandler): diff --git a/mypy/typeshed/stdlib/urllib/response.pyi b/mypy/typeshed/stdlib/urllib/response.pyi index 647ebf874432..9065f3a94ccb 100644 --- a/mypy/typeshed/stdlib/urllib/response.pyi +++ b/mypy/typeshed/stdlib/urllib/response.pyi @@ -2,18 +2,16 @@ import sys from _typeshed import Self from email.message import Message from types import TracebackType -from typing import IO, Any, BinaryIO, Callable, Iterable, Tuple, Type, TypeVar - -_AIUT = TypeVar("_AIUT", bound=addbase) +from typing import IO, Any, BinaryIO, Callable, Iterable class addbase(BinaryIO): fp: IO[bytes] def __init__(self, fp: IO[bytes]) -> None: ... def __enter__(self: Self) -> Self: ... def __exit__( - self, type: Type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... - def __iter__(self: _AIUT) -> _AIUT: ... + def __iter__(self: Self) -> Self: ... def __next__(self) -> bytes: ... def close(self) -> None: ... # These methods don't actually exist, but the class inherits at runtime from @@ -37,7 +35,7 @@ class addbase(BinaryIO): class addclosehook(addbase): closehook: Callable[..., object] - hookargs: Tuple[Any, ...] + hookargs: tuple[Any, ...] def __init__(self, fp: IO[bytes], closehook: Callable[..., object], *hookargs: Any) -> None: ... class addinfo(addbase): diff --git a/mypy/typeshed/stdlib/uuid.pyi b/mypy/typeshed/stdlib/uuid.pyi index da13d819fbdf..782c0491ffb2 100644 --- a/mypy/typeshed/stdlib/uuid.pyi +++ b/mypy/typeshed/stdlib/uuid.pyi @@ -1,10 +1,10 @@ import sys -from typing import Any, Tuple +from typing import Any # Because UUID has properties called int and bytes we need to rename these temporarily. _Int = int _Bytes = bytes -_FieldsType = Tuple[int, int, int, int, int, int] +_FieldsType = tuple[int, int, int, int, int, int] if sys.version_info >= (3, 7): from enum import Enum diff --git a/mypy/typeshed/stdlib/venv/__init__.pyi b/mypy/typeshed/stdlib/venv/__init__.pyi index 25cf615a3243..7650e87d98b4 100644 --- a/mypy/typeshed/stdlib/venv/__init__.pyi +++ b/mypy/typeshed/stdlib/venv/__init__.pyi @@ -3,6 +3,9 @@ from _typeshed import StrOrBytesPath from types import SimpleNamespace from typing import Sequence +if sys.version_info >= (3, 9): + CORE_VENV_DEPS: tuple[str, ...] + class EnvBuilder: system_site_packages: bool clear: bool diff --git a/mypy/typeshed/stdlib/warnings.pyi b/mypy/typeshed/stdlib/warnings.pyi index b1c9f4dda8ed..714356162fde 100644 --- a/mypy/typeshed/stdlib/warnings.pyi +++ b/mypy/typeshed/stdlib/warnings.pyi @@ -1,32 +1,32 @@ 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 import Any, Sequence, TextIO, overload from typing_extensions import Literal _ActionKind = Literal["default", "error", "ignore", "always", "module", "once"] -filters: Sequence[tuple[str, str | None, Type[Warning], str | None, int]] # undocumented, do not mutate +filters: Sequence[tuple[str, str | None, type[Warning], str | None, int]] # undocumented, do not mutate def showwarning( - message: Warning | str, category: Type[Warning], filename: str, lineno: int, file: TextIO | None = ..., line: str | None = ... + message: Warning | str, category: type[Warning], filename: str, lineno: int, file: TextIO | None = ..., line: str | None = ... ) -> None: ... -def formatwarning(message: Warning | str, category: Type[Warning], filename: str, lineno: int, line: str | None = ...) -> str: ... +def formatwarning(message: Warning | str, category: type[Warning], filename: str, lineno: int, line: str | None = ...) -> str: ... def filterwarnings( action: _ActionKind, message: str = ..., - category: Type[Warning] = ..., + category: type[Warning] = ..., module: str = ..., lineno: int = ..., append: bool = ..., ) -> None: ... -def simplefilter(action: _ActionKind, category: Type[Warning] = ..., lineno: int = ..., append: bool = ...) -> None: ... +def simplefilter(action: _ActionKind, category: type[Warning] = ..., lineno: int = ..., append: bool = ...) -> None: ... def resetwarnings() -> None: ... class _OptionError(Exception): ... class WarningMessage: message: Warning | str - category: Type[Warning] + category: type[Warning] filename: str lineno: int file: TextIO | None @@ -35,7 +35,7 @@ class WarningMessage: def __init__( self, message: Warning | str, - category: Type[Warning], + category: type[Warning], filename: str, lineno: int, file: TextIO | None = ..., @@ -52,7 +52,7 @@ class catch_warnings: def __new__(cls, *, record: bool, module: ModuleType | None = ...) -> catch_warnings: ... def __enter__(self) -> list[WarningMessage] | None: ... 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: ... class _catch_warnings_without_records(catch_warnings): diff --git a/mypy/typeshed/stdlib/weakref.pyi b/mypy/typeshed/stdlib/weakref.pyi index dbb6b49f2f2e..742970a60bf3 100644 --- a/mypy/typeshed/stdlib/weakref.pyi +++ b/mypy/typeshed/stdlib/weakref.pyi @@ -1,5 +1,7 @@ +import sys +from _typeshed import Self, SupportsKeysAndGetItem from _weakrefset import WeakSet as WeakSet -from typing import Any, Callable, Generic, Iterable, Iterator, Mapping, MutableMapping, Tuple, Type, TypeVar, overload +from typing import Any, Callable, Generic, Iterable, Iterator, Mapping, MutableMapping, TypeVar, overload from _weakref import ( CallableProxyType as CallableProxyType, @@ -11,13 +13,14 @@ from _weakref import ( ref as ref, ) -_S = TypeVar("_S") _T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") _KT = TypeVar("_KT") _VT = TypeVar("_VT") _CallableT = TypeVar("_CallableT", bound=Callable[..., Any]) -ProxyTypes: Tuple[Type[Any], ...] +ProxyTypes: tuple[type[Any], ...] class WeakMethod(ref[_CallableT], Generic[_CallableT]): def __new__(cls, meth: _CallableT, callback: Callable[[_CallableT], object] | None = ...) -> WeakMethod[_CallableT]: ... @@ -34,12 +37,11 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): def __delitem__(self, v: _KT) -> None: ... def __contains__(self, o: object) -> bool: ... def __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... def copy(self) -> WeakValueDictionary[_KT, _VT]: ... # These are incompatible with Mapping - def keys(self) -> Iterator[_KT]: ... # type: ignore - def values(self) -> Iterator[_VT]: ... # type: ignore - def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore + def keys(self) -> Iterator[_KT]: ... # type: ignore[override] + def values(self) -> Iterator[_VT]: ... # type: ignore[override] + def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override] def itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: ... def valuerefs(self) -> list[KeyedRef[_KT, _VT]]: ... def setdefault(self, key: _KT, default: _VT = ...) -> _VT: ... @@ -47,6 +49,14 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): def pop(self, key: _KT) -> _VT: ... @overload def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... + if sys.version_info >= (3, 9): + def __or__(self, other: Mapping[_T1, _T2]) -> WeakValueDictionary[_KT | _T1, _VT | _T2]: ... + def __ror__(self, other: Mapping[_T1, _T2]) -> WeakValueDictionary[_KT | _T1, _VT | _T2]: ... + # WeakValueDictionary.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self: Self, value: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self: Self, value: Iterable[tuple[_KT, _VT]]) -> Self: ... class KeyedRef(ref[_T], Generic[_KT, _T]): key: _KT @@ -65,23 +75,30 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def __delitem__(self, v: _KT) -> None: ... def __contains__(self, o: object) -> bool: ... def __iter__(self) -> Iterator[_KT]: ... - def __str__(self) -> str: ... def copy(self) -> WeakKeyDictionary[_KT, _VT]: ... # These are incompatible with Mapping - def keys(self) -> Iterator[_KT]: ... # type: ignore - def values(self) -> Iterator[_VT]: ... # type: ignore - def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore + def keys(self) -> Iterator[_KT]: ... # type: ignore[override] + def values(self) -> Iterator[_VT]: ... # type: ignore[override] + def items(self) -> Iterator[tuple[_KT, _VT]]: ... # type: ignore[override] def keyrefs(self) -> list[ref[_KT]]: ... def setdefault(self, key: _KT, default: _VT = ...) -> _VT: ... @overload def pop(self, key: _KT) -> _VT: ... @overload def pop(self, key: _KT, default: _VT | _T = ...) -> _VT | _T: ... + if sys.version_info >= (3, 9): + def __or__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ... + def __ror__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ... + # WeakKeyDictionary.__ior__ should be kept roughly in line with MutableMapping.update() + @overload # type: ignore[misc] + def __ior__(self: Self, value: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ... + @overload + def __ior__(self: Self, value: Iterable[tuple[_KT, _VT]]) -> Self: ... class finalize: def __init__(self, __obj: object, __func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... def __call__(self, _: Any = ...) -> Any | None: ... - def detach(self) -> tuple[Any, Any, Tuple[Any, ...], dict[str, Any]] | None: ... - def peek(self) -> tuple[Any, Any, Tuple[Any, ...], dict[str, Any]] | None: ... + def detach(self) -> tuple[Any, Any, tuple[Any, ...], dict[str, Any]] | None: ... + def peek(self) -> tuple[Any, Any, tuple[Any, ...], dict[str, Any]] | None: ... alive: bool atexit: bool diff --git a/mypy/typeshed/stdlib/webbrowser.pyi b/mypy/typeshed/stdlib/webbrowser.pyi index c85288cc562f..459d886ac930 100644 --- a/mypy/typeshed/stdlib/webbrowser.pyi +++ b/mypy/typeshed/stdlib/webbrowser.pyi @@ -28,14 +28,9 @@ class BaseBrowser: def open_new_tab(self, url: str) -> bool: ... class GenericBrowser(BaseBrowser): - args: list[str] - name: str - basename: str def __init__(self, name: str | Sequence[str]) -> None: ... - def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... -class BackgroundBrowser(GenericBrowser): - def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... +class BackgroundBrowser(GenericBrowser): ... class UnixBrowser(BaseBrowser): raise_opts: list[str] | None @@ -45,59 +40,21 @@ class UnixBrowser(BaseBrowser): remote_action: str remote_action_newwin: str remote_action_newtab: str - def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... -class Mozilla(UnixBrowser): - remote_args: list[str] - remote_action: str - remote_action_newwin: str - remote_action_newtab: str - background: bool +class Mozilla(UnixBrowser): ... class Galeon(UnixBrowser): raise_opts: list[str] - remote_args: list[str] - remote_action: str - remote_action_newwin: str - background: bool -class Chrome(UnixBrowser): - remote_args: list[str] - remote_action: str - remote_action_newwin: str - remote_action_newtab: str - background: bool - -class Opera(UnixBrowser): - remote_args: list[str] - remote_action: str - remote_action_newwin: str - remote_action_newtab: str - background: bool - -class Elinks(UnixBrowser): - remote_args: list[str] - remote_action: str - remote_action_newwin: str - remote_action_newtab: str - background: bool - redirect_stdout: bool - -class Konqueror(BaseBrowser): - def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... - -class Grail(BaseBrowser): - def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... +class Chrome(UnixBrowser): ... +class Opera(UnixBrowser): ... +class Elinks(UnixBrowser): ... +class Konqueror(BaseBrowser): ... +class Grail(BaseBrowser): ... if sys.platform == "win32": - class WindowsDefault(BaseBrowser): - def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... + class WindowsDefault(BaseBrowser): ... if sys.platform == "darwin": - class MacOSX(BaseBrowser): - name: str - def __init__(self, name: str) -> None: ... - def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... - class MacOSXOSAScript(BaseBrowser): - def __init__(self, name: str) -> None: ... - def open(self, url: str, new: int = ..., autoraise: bool = ...) -> bool: ... + class MacOSX(BaseBrowser): ... + class MacOSXOSAScript(BaseBrowser): ... # In runtime this class does not have `name` and `basename` diff --git a/mypy/typeshed/stdlib/winreg.pyi b/mypy/typeshed/stdlib/winreg.pyi index 5fff1104e246..1730c651c6b8 100644 --- a/mypy/typeshed/stdlib/winreg.pyi +++ b/mypy/typeshed/stdlib/winreg.pyi @@ -1,101 +1,101 @@ +import sys from _typeshed import Self from types import TracebackType -from typing import Any, Type, Union -from typing_extensions import final +from typing import Any, Union +from typing_extensions import Literal, final -_KeyType = Union[HKEYType, int] +if sys.platform == "win32": + _KeyType = Union[HKEYType, int] + def CloseKey(__hkey: _KeyType) -> None: ... + def ConnectRegistry(__computer_name: str | None, __key: _KeyType) -> HKEYType: ... + def CreateKey(__key: _KeyType, __sub_key: str | None) -> HKEYType: ... + def CreateKeyEx(key: _KeyType, sub_key: str | None, reserved: int = ..., access: int = ...) -> HKEYType: ... + def DeleteKey(__key: _KeyType, __sub_key: str) -> None: ... + def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = ..., reserved: int = ...) -> None: ... + def DeleteValue(__key: _KeyType, __value: str) -> None: ... + def EnumKey(__key: _KeyType, __index: int) -> str: ... + def EnumValue(__key: _KeyType, __index: int) -> tuple[str, Any, int]: ... + def ExpandEnvironmentStrings(__str: str) -> str: ... + def FlushKey(__key: _KeyType) -> None: ... + def LoadKey(__key: _KeyType, __sub_key: str, __file_name: str) -> None: ... + def OpenKey(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... + def OpenKeyEx(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... + def QueryInfoKey(__key: _KeyType) -> tuple[int, int, int]: ... + def QueryValue(__key: _KeyType, __sub_key: str | None) -> str: ... + def QueryValueEx(__key: _KeyType, __name: str) -> tuple[Any, int]: ... + def SaveKey(__key: _KeyType, __file_name: str) -> None: ... + def SetValue(__key: _KeyType, __sub_key: str, __type: int, __value: str) -> None: ... + def SetValueEx( + __key: _KeyType, __value_name: str | None, __reserved: Any, __type: int, __value: str | int + ) -> None: ... # reserved is ignored + def DisableReflectionKey(__key: _KeyType) -> None: ... + def EnableReflectionKey(__key: _KeyType) -> None: ... + def QueryReflectionKey(__key: _KeyType) -> bool: ... + HKEY_CLASSES_ROOT: int + HKEY_CURRENT_USER: int + HKEY_LOCAL_MACHINE: int + HKEY_USERS: int + HKEY_PERFORMANCE_DATA: int + HKEY_CURRENT_CONFIG: int + HKEY_DYN_DATA: int -def CloseKey(__hkey: _KeyType) -> None: ... -def ConnectRegistry(__computer_name: str | None, __key: _KeyType) -> HKEYType: ... -def CreateKey(__key: _KeyType, __sub_key: str | None) -> HKEYType: ... -def CreateKeyEx(key: _KeyType, sub_key: str | None, reserved: int = ..., access: int = ...) -> HKEYType: ... -def DeleteKey(__key: _KeyType, __sub_key: str) -> None: ... -def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = ..., reserved: int = ...) -> None: ... -def DeleteValue(__key: _KeyType, __value: str) -> None: ... -def EnumKey(__key: _KeyType, __index: int) -> str: ... -def EnumValue(__key: _KeyType, __index: int) -> tuple[str, Any, int]: ... -def ExpandEnvironmentStrings(__str: str) -> str: ... -def FlushKey(__key: _KeyType) -> None: ... -def LoadKey(__key: _KeyType, __sub_key: str, __file_name: str) -> None: ... -def OpenKey(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... -def OpenKeyEx(key: _KeyType, sub_key: str, reserved: int = ..., access: int = ...) -> HKEYType: ... -def QueryInfoKey(__key: _KeyType) -> tuple[int, int, int]: ... -def QueryValue(__key: _KeyType, __sub_key: str | None) -> str: ... -def QueryValueEx(__key: _KeyType, __name: str) -> tuple[Any, int]: ... -def SaveKey(__key: _KeyType, __file_name: str) -> None: ... -def SetValue(__key: _KeyType, __sub_key: str, __type: int, __value: str) -> None: ... -def SetValueEx( - __key: _KeyType, __value_name: str | None, __reserved: Any, __type: int, __value: str | int -) -> None: ... # reserved is ignored -def DisableReflectionKey(__key: _KeyType) -> None: ... -def EnableReflectionKey(__key: _KeyType) -> None: ... -def QueryReflectionKey(__key: _KeyType) -> bool: ... + KEY_ALL_ACCESS: Literal[983103] + KEY_WRITE: Literal[131078] + KEY_READ: Literal[131097] + KEY_EXECUTE: Literal[131097] + KEY_QUERY_VALUE: Literal[1] + KEY_SET_VALUE: Literal[2] + KEY_CREATE_SUB_KEY: Literal[4] + KEY_ENUMERATE_SUB_KEYS: Literal[8] + KEY_NOTIFY: Literal[16] + KEY_CREATE_LINK: Literal[32] -HKEY_CLASSES_ROOT: int -HKEY_CURRENT_USER: int -HKEY_LOCAL_MACHINE: int -HKEY_USERS: int -HKEY_PERFORMANCE_DATA: int -HKEY_CURRENT_CONFIG: int -HKEY_DYN_DATA: int + KEY_WOW64_64KEY: Literal[256] + KEY_WOW64_32KEY: Literal[512] -KEY_ALL_ACCESS: int -KEY_WRITE: int -KEY_READ: int -KEY_EXECUTE: int -KEY_QUERY_VALUE: int -KEY_SET_VALUE: int -KEY_CREATE_SUB_KEY: int -KEY_ENUMERATE_SUB_KEYS: int -KEY_NOTIFY: int -KEY_CREATE_LINK: int + REG_BINARY: Literal[3] + REG_DWORD: Literal[4] + REG_DWORD_LITTLE_ENDIAN: Literal[4] + REG_DWORD_BIG_ENDIAN: Literal[5] + REG_EXPAND_SZ: Literal[2] + REG_LINK: Literal[6] + REG_MULTI_SZ: Literal[7] + REG_NONE: Literal[0] + REG_QWORD: Literal[11] + REG_QWORD_LITTLE_ENDIAN: Literal[11] + REG_RESOURCE_LIST: Literal[8] + REG_FULL_RESOURCE_DESCRIPTOR: Literal[9] + REG_RESOURCE_REQUIREMENTS_LIST: Literal[10] + REG_SZ: Literal[1] -KEY_WOW64_64KEY: int -KEY_WOW64_32KEY: int + REG_CREATED_NEW_KEY: int # undocumented + REG_LEGAL_CHANGE_FILTER: int # undocumented + REG_LEGAL_OPTION: int # undocumented + REG_NOTIFY_CHANGE_ATTRIBUTES: int # undocumented + REG_NOTIFY_CHANGE_LAST_SET: int # undocumented + REG_NOTIFY_CHANGE_NAME: int # undocumented + REG_NOTIFY_CHANGE_SECURITY: int # undocumented + REG_NO_LAZY_FLUSH: int # undocumented + REG_OPENED_EXISTING_KEY: int # undocumented + REG_OPTION_BACKUP_RESTORE: int # undocumented + REG_OPTION_CREATE_LINK: int # undocumented + REG_OPTION_NON_VOLATILE: int # undocumented + REG_OPTION_OPEN_LINK: int # undocumented + REG_OPTION_RESERVED: int # undocumented + REG_OPTION_VOLATILE: int # undocumented + REG_REFRESH_HIVE: int # undocumented + REG_WHOLE_HIVE_VOLATILE: int # undocumented -REG_BINARY: int -REG_DWORD: int -REG_DWORD_LITTLE_ENDIAN: int -REG_DWORD_BIG_ENDIAN: int -REG_EXPAND_SZ: int -REG_LINK: int -REG_MULTI_SZ: int -REG_NONE: int -REG_QWORD: int -REG_QWORD_LITTLE_ENDIAN: int -REG_RESOURCE_LIST: int -REG_FULL_RESOURCE_DESCRIPTOR: int -REG_RESOURCE_REQUIREMENTS_LIST: int -REG_SZ: int + error = OSError -REG_CREATED_NEW_KEY: int # undocumented -REG_LEGAL_CHANGE_FILTER: int # undocumented -REG_LEGAL_OPTION: int # undocumented -REG_NOTIFY_CHANGE_ATTRIBUTES: int # undocumented -REG_NOTIFY_CHANGE_LAST_SET: int # undocumented -REG_NOTIFY_CHANGE_NAME: int # undocumented -REG_NOTIFY_CHANGE_SECURITY: int # undocumented -REG_NO_LAZY_FLUSH: int # undocumented -REG_OPENED_EXISTING_KEY: int # undocumented -REG_OPTION_BACKUP_RESTORE: int # undocumented -REG_OPTION_CREATE_LINK: int # undocumented -REG_OPTION_NON_VOLATILE: int # undocumented -REG_OPTION_OPEN_LINK: int # undocumented -REG_OPTION_RESERVED: int # undocumented -REG_OPTION_VOLATILE: int # undocumented -REG_REFRESH_HIVE: int # undocumented -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: ... - def __enter__(self: Self) -> Self: ... - def __exit__( - self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None - ) -> bool | None: ... - def Close(self) -> None: ... - def Detach(self) -> int: ... + # 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: ... + def __enter__(self: Self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> bool | None: ... + def Close(self) -> None: ... + def Detach(self) -> int: ... diff --git a/mypy/typeshed/stdlib/winsound.pyi b/mypy/typeshed/stdlib/winsound.pyi index 3d79f3b043f2..588bd5969e98 100644 --- a/mypy/typeshed/stdlib/winsound.pyi +++ b/mypy/typeshed/stdlib/winsound.pyi @@ -3,21 +3,21 @@ from typing import overload from typing_extensions import Literal if sys.platform == "win32": - SND_FILENAME: int - SND_ALIAS: int - SND_LOOP: int - SND_MEMORY: int - SND_PURGE: int - SND_ASYNC: int - SND_NODEFAULT: int - SND_NOSTOP: int - SND_NOWAIT: int + SND_FILENAME: Literal[131072] + SND_ALIAS: Literal[65536] + SND_LOOP: Literal[8] + SND_MEMORY: Literal[4] + SND_PURGE: Literal[64] + SND_ASYNC: Literal[1] + SND_NODEFAULT: Literal[2] + SND_NOSTOP: Literal[16] + SND_NOWAIT: Literal[8192] - MB_ICONASTERISK: int - MB_ICONEXCLAMATION: int - MB_ICONHAND: int - MB_ICONQUESTION: int - MB_OK: int + MB_ICONASTERISK: Literal[64] + MB_ICONEXCLAMATION: Literal[48] + MB_ICONHAND: Literal[16] + MB_ICONQUESTION: Literal[32] + MB_OK: Literal[0] def Beep(frequency: int, duration: int) -> None: ... # Can actually accept anything ORed with 4, and if not it's definitely str, but that's inexpressible @overload diff --git a/mypy/typeshed/stdlib/wsgiref/handlers.pyi b/mypy/typeshed/stdlib/wsgiref/handlers.pyi index ac1e56b7664e..11f474660b05 100644 --- a/mypy/typeshed/stdlib/wsgiref/handlers.pyi +++ b/mypy/typeshed/stdlib/wsgiref/handlers.pyi @@ -1,12 +1,12 @@ from abc import abstractmethod from types import TracebackType -from typing import IO, Callable, MutableMapping, Optional, Tuple, Type +from typing import IO, Callable, MutableMapping, Optional from .headers import Headers from .types import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment from .util import FileWrapper -_exc_info = Tuple[Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]] +_exc_info = tuple[Optional[type[BaseException]], Optional[BaseException], Optional[TracebackType]] def format_date_time(timestamp: float | None) -> str: ... # undocumented def read_environ() -> dict[str, str]: ... @@ -23,8 +23,8 @@ class BaseHandler: os_environ: MutableMapping[str, str] - wsgi_file_wrapper: Type[FileWrapper] | None - headers_class: Type[Headers] # undocumented + wsgi_file_wrapper: type[FileWrapper] | None + headers_class: type[Headers] # undocumented traceback_limit: int | None error_status: str diff --git a/mypy/typeshed/stdlib/wsgiref/headers.pyi b/mypy/typeshed/stdlib/wsgiref/headers.pyi index 531a521d3824..b62124a2a936 100644 --- a/mypy/typeshed/stdlib/wsgiref/headers.pyi +++ b/mypy/typeshed/stdlib/wsgiref/headers.pyi @@ -1,6 +1,6 @@ -from typing import List, Pattern, Tuple, overload +from typing import Pattern, overload -_HeaderList = List[Tuple[str, str]] +_HeaderList = list[tuple[str, str]] tspecials: Pattern[str] # undocumented diff --git a/mypy/typeshed/stdlib/wsgiref/simple_server.pyi b/mypy/typeshed/stdlib/wsgiref/simple_server.pyi index 76d0b269793d..7e746451d380 100644 --- a/mypy/typeshed/stdlib/wsgiref/simple_server.pyi +++ b/mypy/typeshed/stdlib/wsgiref/simple_server.pyi @@ -1,5 +1,5 @@ from http.server import BaseHTTPRequestHandler, HTTPServer -from typing import Type, TypeVar, overload +from typing import TypeVar, overload from .handlers import SimpleHandler from .types import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment @@ -30,8 +30,8 @@ def demo_app(environ: WSGIEnvironment, start_response: StartResponse) -> list[by _S = TypeVar("_S", bound=WSGIServer) @overload -def make_server(host: str, port: int, app: WSGIApplication, *, handler_class: Type[WSGIRequestHandler] = ...) -> WSGIServer: ... +def make_server(host: str, port: int, app: WSGIApplication, *, handler_class: type[WSGIRequestHandler] = ...) -> WSGIServer: ... @overload def make_server( - host: str, port: int, app: WSGIApplication, server_class: Type[_S], handler_class: Type[WSGIRequestHandler] = ... + host: str, port: int, app: WSGIApplication, server_class: type[_S], handler_class: type[WSGIRequestHandler] = ... ) -> _S: ... diff --git a/mypy/typeshed/stdlib/wsgiref/util.pyi b/mypy/typeshed/stdlib/wsgiref/util.pyi index a7f710e8012c..c769c77d36e9 100644 --- a/mypy/typeshed/stdlib/wsgiref/util.pyi +++ b/mypy/typeshed/stdlib/wsgiref/util.pyi @@ -1,3 +1,4 @@ +import sys from typing import IO, Any, Callable from .types import WSGIEnvironment @@ -7,7 +8,8 @@ class FileWrapper: blksize: int close: Callable[[], None] # only exists if filelike.close exists def __init__(self, filelike: IO[bytes], blksize: int = ...) -> None: ... - def __getitem__(self, key: Any) -> bytes: ... + if sys.version_info < (3, 11): + def __getitem__(self, key: Any) -> bytes: ... def __iter__(self) -> FileWrapper: ... def __next__(self) -> bytes: ... diff --git a/mypy/typeshed/stdlib/xml/dom/__init__.pyi b/mypy/typeshed/stdlib/xml/dom/__init__.pyi index c5766c326c3e..e5b91bf2a795 100644 --- a/mypy/typeshed/stdlib/xml/dom/__init__.pyi +++ b/mypy/typeshed/stdlib/xml/dom/__init__.pyi @@ -43,6 +43,7 @@ class IndexSizeErr(DOMException): ... class DomstringSizeErr(DOMException): ... class HierarchyRequestErr(DOMException): ... class WrongDocumentErr(DOMException): ... +class InvalidCharacterErr(DOMException): ... class NoDataAllowedErr(DOMException): ... class NoModificationAllowedErr(DOMException): ... class NotFoundErr(DOMException): ... diff --git a/mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi b/mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi index 964e6fa3f426..58914e8fabf1 100644 --- a/mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi +++ b/mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi @@ -1,3 +1,99 @@ -from typing import Any +from typing import Any, NoReturn +from xml.dom.minidom import Document, DOMImplementation, Node, TypeInfo +from xml.dom.xmlbuilder import DOMBuilderFilter, Options -def __getattr__(name: str) -> Any: ... # incomplete +TEXT_NODE = Node.TEXT_NODE +CDATA_SECTION_NODE = Node.CDATA_SECTION_NODE +DOCUMENT_NODE = Node.DOCUMENT_NODE +FILTER_ACCEPT = DOMBuilderFilter.FILTER_ACCEPT +FILTER_REJECT = DOMBuilderFilter.FILTER_REJECT +FILTER_SKIP = DOMBuilderFilter.FILTER_SKIP +FILTER_INTERRUPT = DOMBuilderFilter.FILTER_INTERRUPT +theDOMImplementation: DOMImplementation | None + +class ElementInfo: + tagName: Any + def __init__(self, tagName, model: Any | None = ...) -> None: ... + def getAttributeType(self, aname) -> TypeInfo: ... + def getAttributeTypeNS(self, namespaceURI, localName) -> TypeInfo: ... + def isElementContent(self) -> bool: ... + def isEmpty(self) -> bool: ... + def isId(self, aname) -> bool: ... + def isIdNS(self, euri, ename, auri, aname) -> bool: ... + +class ExpatBuilder: + document: Document # Created in self.reset() + curNode: Any # Created in self.reset() + def __init__(self, options: Options | None = ...) -> None: ... + def createParser(self): ... + def getParser(self): ... + def reset(self) -> None: ... + def install(self, parser) -> None: ... + def parseFile(self, file) -> Document: ... + def parseString(self, string: str) -> Document: ... + def start_doctype_decl_handler(self, doctypeName, systemId, publicId, has_internal_subset) -> None: ... + def end_doctype_decl_handler(self) -> None: ... + def pi_handler(self, target, data) -> None: ... + def character_data_handler_cdata(self, data) -> None: ... + def character_data_handler(self, data) -> None: ... + def start_cdata_section_handler(self) -> None: ... + def end_cdata_section_handler(self) -> None: ... + def entity_decl_handler(self, entityName, is_parameter_entity, value, base, systemId, publicId, notationName) -> None: ... + def notation_decl_handler(self, notationName, base, systemId, publicId) -> None: ... + def comment_handler(self, data) -> None: ... + def external_entity_ref_handler(self, context, base, systemId, publicId) -> int: ... + def first_element_handler(self, name, attributes) -> None: ... + def start_element_handler(self, name, attributes) -> None: ... + def end_element_handler(self, name) -> None: ... + def element_decl_handler(self, name, model) -> None: ... + def attlist_decl_handler(self, elem, name, type, default, required) -> None: ... + def xml_decl_handler(self, version, encoding, standalone) -> None: ... + +class FilterVisibilityController: + filter: DOMBuilderFilter + def __init__(self, filter: DOMBuilderFilter) -> None: ... + def startContainer(self, node: Node) -> int: ... + def acceptNode(self, node: Node) -> int: ... + +class FilterCrutch: + def __init__(self, builder) -> None: ... + +class Rejecter(FilterCrutch): + def start_element_handler(self, *args: Any) -> None: ... + def end_element_handler(self, *args: Any) -> None: ... + +class Skipper(FilterCrutch): + def start_element_handler(self, *args: Any) -> None: ... + def end_element_handler(self, *args: Any) -> None: ... + +class FragmentBuilder(ExpatBuilder): + fragment: Any | None + originalDocument: Any + context: Any + def __init__(self, context, options: Options | None = ...) -> None: ... + +class Namespaces: + def createParser(self): ... + def install(self, parser) -> None: ... + def start_namespace_decl_handler(self, prefix, uri) -> None: ... + def start_element_handler(self, name, attributes) -> None: ... + def end_element_handler(self, name) -> None: ... + +class ExpatBuilderNS(Namespaces, ExpatBuilder): ... +class FragmentBuilderNS(Namespaces, FragmentBuilder): ... +class ParseEscape(Exception): ... + +class InternalSubsetExtractor(ExpatBuilder): + subset: Any | None + def getSubset(self) -> Any | None: ... + def parseFile(self, file) -> None: ... # type: ignore[override] + def parseString(self, string: str) -> None: ... # type: ignore[override] + def start_doctype_decl_handler(self, name, publicId, systemId, has_internal_subset) -> None: ... # type: ignore[override] + def end_doctype_decl_handler(self) -> NoReturn: ... + def start_element_handler(self, name, attrs) -> NoReturn: ... + +def parse(file, namespaces: bool = ...): ... +def parseString(string: str, namespaces: bool = ...): ... +def parseFragment(file, context, namespaces: bool = ...): ... +def parseFragmentString(string: str, context, namespaces: bool = ...): ... +def makeBuilder(options: Options) -> ExpatBuilderNS | ExpatBuilder: ... diff --git a/mypy/typeshed/stdlib/xml/dom/minicompat.pyi b/mypy/typeshed/stdlib/xml/dom/minicompat.pyi index 4bc60f7ab965..e37b7cd89176 100644 --- a/mypy/typeshed/stdlib/xml/dom/minicompat.pyi +++ b/mypy/typeshed/stdlib/xml/dom/minicompat.pyi @@ -1,17 +1,17 @@ -from typing import Any, Iterable, List, Tuple, Type, TypeVar +from typing import Any, Iterable, TypeVar _T = TypeVar("_T") -StringTypes: tuple[Type[str]] +StringTypes: tuple[type[str]] -class NodeList(List[_T]): +class NodeList(list[_T]): length: int def item(self, index: int) -> _T | None: ... -class EmptyNodeList(Tuple[Any, ...]): +class EmptyNodeList(tuple[Any, ...]): length: int def item(self, index: int) -> None: ... - def __add__(self, other: Iterable[_T]) -> NodeList[_T]: ... # type: ignore + def __add__(self, other: Iterable[_T]) -> NodeList[_T]: ... # type: ignore[override] def __radd__(self, other: Iterable[_T]) -> NodeList[_T]: ... -def defproperty(klass: Type[Any], name: str, doc: str) -> None: ... +def defproperty(klass: type[Any], name: str, doc: str) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/dom/minidom.pyi b/mypy/typeshed/stdlib/xml/dom/minidom.pyi index 4d1d7a9d0faf..e9a26e30d721 100644 --- a/mypy/typeshed/stdlib/xml/dom/minidom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/minidom.pyi @@ -70,6 +70,10 @@ class Attr(Node): self, qName: str, namespaceURI: str | None = ..., localName: Any | None = ..., prefix: Any | None = ... ) -> None: ... def unlink(self) -> None: ... + @property + def isId(self) -> bool: ... + @property + def schemaType(self) -> Any: ... class NamedNodeMap: def __init__(self, attrs, attrsNS, ownerElement) -> None: ... @@ -96,6 +100,8 @@ class NamedNodeMap: def setNamedItem(self, node): ... def setNamedItemNS(self, node): ... def __delitem__(self, attname_or_tuple) -> None: ... + @property + def length(self) -> int: ... AttributeList = NamedNodeMap @@ -110,6 +116,7 @@ class Element(Node): schemaType: Any parentNode: Any tagName: str + nodeName: str prefix: Any namespaceURI: str | None childNodes: Any @@ -139,6 +146,8 @@ class Element(Node): def setIdAttribute(self, name) -> None: ... def setIdAttributeNS(self, namespaceURI: str, localName) -> None: ... def setIdAttributeNode(self, idAttr) -> None: ... + @property + def attributes(self) -> NamedNodeMap: ... class Childless: attributes: Any @@ -173,6 +182,8 @@ class CharacterData(Childless, Node): def insertData(self, offset: int, arg: str) -> None: ... def deleteData(self, offset: int, count: int) -> None: ... def replaceData(self, offset: int, count: int, arg: str) -> None: ... + @property + def length(self) -> int: ... class Text(CharacterData): nodeType: Any @@ -182,6 +193,10 @@ class Text(CharacterData): def splitText(self, offset): ... def writexml(self, writer, indent: str = ..., addindent: str = ..., newl: str = ...) -> None: ... def replaceWholeText(self, content): ... + @property + def isWhitespaceInElementContent(self) -> bool: ... + @property + def wholeText(self) -> str: ... class Comment(CharacterData): nodeType: Any @@ -205,15 +220,17 @@ class ReadOnlySequentialNamedNodeMap: def removeNamedItemNS(self, namespaceURI: str, localName) -> None: ... def setNamedItem(self, node) -> None: ... def setNamedItemNS(self, node) -> None: ... + @property + def length(self) -> int: ... -class Identified: ... +class Identified: + publicId: Any + systemId: Any class DocumentType(Identified, Childless, Node): nodeType: Any nodeValue: Any name: Any - publicId: Any - systemId: Any internalSubset: Any entities: Any notations: Any diff --git a/mypy/typeshed/stdlib/xml/dom/pulldom.pyi b/mypy/typeshed/stdlib/xml/dom/pulldom.pyi index ce8816b4a98a..c2b7aa0772fa 100644 --- a/mypy/typeshed/stdlib/xml/dom/pulldom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/pulldom.pyi @@ -1,4 +1,5 @@ -from typing import IO, Any, Sequence, Tuple, Union +import sys +from typing import IO, Any, Sequence, Union from typing_extensions import Literal from xml.dom.minidom import Document, DOMImplementation, Element, Text from xml.sax.handler import ContentHandler @@ -16,7 +17,7 @@ CHARACTERS: Literal["CHARACTERS"] _DocumentFactory = Union[DOMImplementation, None] _Node = Union[Document, Element, Text] -_Event = Tuple[ +_Event = tuple[ Literal[ Literal["START_ELEMENT"], Literal["END_ELEMENT"], @@ -66,7 +67,8 @@ class DOMEventStream: bufsize: int def __init__(self, stream: IO[bytes], parser: XMLReader, bufsize: int) -> None: ... pulldom: Any - def __getitem__(self, pos): ... + if sys.version_info < (3, 11): + def __getitem__(self, pos): ... def __next__(self): ... def __iter__(self): ... def getEvent(self) -> _Event: ... diff --git a/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi b/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi index d8936bdc2ab4..2738d735e73f 100644 --- a/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi +++ b/mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi @@ -1,6 +1,107 @@ -from typing import Any +from typing import Any, NoReturn, Optional +from typing_extensions import Literal +from urllib.request import OpenerDirector +from xml.dom.expatbuilder import ExpatBuilder, ExpatBuilderNS +from xml.dom.minidom import Node -def __getattr__(name: str) -> Any: ... # incomplete +# UNKNOWN TYPES: +# - `Options.errorHandler`. +# The same as `_DOMBuilderErrorHandlerType`? +# Maybe `xml.sax.handler.ErrorHandler`? +# - Return type of DOMBuilder.getFeature(). +# We could get rid of the `Any` if we knew more +# about `Options.errorHandler`. -class DocumentLS(Any): ... # type: ignore -class DOMImplementationLS(Any): ... # type: ignore +# ALIASES REPRESENTING MORE UNKNOWN TYPES: + +# probably the same as `Options.errorHandler`? +# Maybe `xml.sax.handler.ErrorHandler`? +_DOMBuilderErrorHandlerType = Optional[Any] +# probably some kind of IO... +_DOMInputSourceCharacterStreamType = Optional[Any] +# probably a string?? +_DOMInputSourceStringDataType = Optional[Any] +# probably a string?? +_DOMInputSourceEncodingType = Optional[Any] + +class Options: + namespaces: int + namespace_declarations: bool + validation: bool + external_parameter_entities: bool + external_general_entities: bool + external_dtd_subset: bool + validate_if_schema: bool + validate: bool + datatype_normalization: bool + create_entity_ref_nodes: bool + entities: bool + whitespace_in_element_content: bool + cdata_sections: bool + comments: bool + charset_overrides_xml_encoding: bool + infoset: bool + supported_mediatypes_only: bool + errorHandler: Any | None + filter: DOMBuilderFilter | None # a guess, but seems likely + +class DOMBuilder: + entityResolver: DOMEntityResolver | None # a guess, but seems likely + errorHandler: _DOMBuilderErrorHandlerType + filter: DOMBuilderFilter | None # a guess, but seems likely + ACTION_REPLACE: Literal[1] + ACTION_APPEND_AS_CHILDREN: Literal[2] + ACTION_INSERT_AFTER: Literal[3] + ACTION_INSERT_BEFORE: Literal[4] + def __init__(self) -> None: ... + def setFeature(self, name: str, state: int) -> None: ... + def supportsFeature(self, name: str) -> bool: ... + def canSetFeature(self, name: str, state: int) -> bool: ... + # getFeature could return any attribute from an instance of `Options` + def getFeature(self, name: str) -> Any: ... + def parseURI(self, uri: str) -> ExpatBuilder | ExpatBuilderNS: ... + def parse(self, input: DOMInputSource) -> ExpatBuilder | ExpatBuilderNS: ... + # `input` and `cnode` argtypes for `parseWithContext` are unknowable + # as the function does nothing with them, and always raises an exception. + # But `input` is *probably* `DOMInputSource`? + def parseWithContext(self, input: object, cnode: object, action: Literal[1, 2, 3, 4]) -> NoReturn: ... + +class DOMEntityResolver: + def resolveEntity(self, publicId: str | None, systemId: str) -> DOMInputSource: ... + +class DOMInputSource: + byteStream: OpenerDirector | None + characterStream: _DOMInputSourceCharacterStreamType + stringData: _DOMInputSourceStringDataType + encoding: _DOMInputSourceEncodingType + publicId: str | None + systemId: str | None + baseURI: str | None + +class DOMBuilderFilter: + FILTER_ACCEPT: Literal[1] + FILTER_REJECT: Literal[2] + FILTER_SKIP: Literal[3] + FILTER_INTERRUPT: Literal[4] + whatToShow: int + # The argtypes for acceptNode and startContainer appear to be irrelevant. + def acceptNode(self, element: object) -> Literal[1]: ... + def startContainer(self, element: object) -> Literal[1]: ... + +class DocumentLS: + async_: bool + def abort(self) -> NoReturn: ... + # `load()` and `loadXML()` always raise exceptions + # so the argtypes of `uri` and `source` are unknowable. + # `source` is *probably* `DOMInputSource`? + # `uri` is *probably* a str? (see DOMBuilder.parseURI()) + def load(self, uri: object) -> NoReturn: ... + def loadXML(self, source: object) -> NoReturn: ... + def saveXML(self, snode: Node | None) -> str: ... + +class DOMImplementationLS: + MODE_SYNCHRONOUS: Literal[1] + MODE_ASYNCHRONOUS: Literal[2] + def createDOMBuilder(self, mode: Literal[1], schemaType: None) -> DOMBuilder: ... + def createDOMWriter(self) -> NoReturn: ... + def createDOMInputSource(self) -> DOMInputSource: ... diff --git a/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi b/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi index 0ccccce4f3d0..b355bef1208c 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi @@ -6,6 +6,9 @@ XINCLUDE: str XINCLUDE_INCLUDE: str XINCLUDE_FALLBACK: str +if sys.version_info >= (3, 9): + DEFAULT_MAX_INCLUSION_DEPTH: int + class FatalIncludeError(SyntaxError): ... def default_loader(href: str | bytes | int, parse: str, encoding: str | None = ...) -> str | Element: ... @@ -17,6 +20,7 @@ if sys.version_info >= (3, 9): def include( elem: Element, loader: Callable[..., str | Element] | None = ..., base_url: str | None = ..., max_depth: int | None = ... ) -> None: ... + class LimitedRecursiveIncludeError(FatalIncludeError): ... else: def include(elem: Element, loader: Callable[..., str | Element] | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi b/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi index db4bd6a4e958..5a2dd69c1bee 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi @@ -1,11 +1,11 @@ -from typing import Callable, Generator, List, Pattern, Tuple, TypeVar +from typing import Callable, Generator, Pattern, TypeVar from xml.etree.ElementTree import Element xpath_tokenizer_re: Pattern[str] -_token = Tuple[str, str] +_token = tuple[str, str] _next = Callable[[], _token] -_callback = Callable[[_SelectorContext, List[Element]], Generator[Element, None, None]] +_callback = Callable[[_SelectorContext, list[Element]], Generator[Element, None, None]] def xpath_tokenizer(pattern: str, namespaces: dict[str, str] | None = ...) -> Generator[_token, None, None]: ... def get_parent_map(context: _SelectorContext) -> dict[Element, Element]: ... diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index 03a20dcad4cb..c4236cf292bb 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -4,19 +4,19 @@ from typing import ( IO, Any, Callable, - Dict, Generator, ItemsView, Iterable, Iterator, KeysView, + Mapping, MutableSequence, Sequence, TypeVar, Union, overload, ) -from typing_extensions import Literal +from typing_extensions import Literal, SupportsIndex _T = TypeVar("_T") _File = Union[StrOrBytesPath, FileDescriptor, IO[Any]] @@ -87,14 +87,14 @@ class Element(MutableSequence[Element]): def makeelement(self, __tag: str, __attrib: dict[str, str]) -> Element: ... def remove(self, __subelement: Element) -> None: ... def set(self, __key: str, __value: str) -> None: ... - def __delitem__(self, i: int | slice) -> None: ... + def __delitem__(self, i: SupportsIndex | slice) -> None: ... @overload - def __getitem__(self, i: int) -> Element: ... + def __getitem__(self, i: SupportsIndex) -> Element: ... @overload def __getitem__(self, s: slice) -> MutableSequence[Element]: ... def __len__(self) -> int: ... @overload - def __setitem__(self, i: int, o: Element) -> None: ... + def __setitem__(self, i: SupportsIndex, o: Element) -> None: ... @overload def __setitem__(self, s: slice, o: Iterable[Element]) -> None: ... if sys.version_info < (3, 9): @@ -256,14 +256,32 @@ def fromstringlist(sequence: Sequence[str | bytes], parser: XMLParser | None = . # TreeBuilder is called by client code (they could pass strs, bytes or whatever); # but we don't want to use a too-broad type, or it would be too hard to write # elementfactories. -_ElementFactory = Callable[[Any, Dict[Any, Any]], Element] +_ElementFactory = Callable[[Any, dict[Any, Any]], Element] class TreeBuilder: - def __init__(self, element_factory: _ElementFactory | None = ...) -> None: ... + if sys.version_info >= (3, 8): + # comment_factory can take None because passing None to Comment is not an error + def __init__( + self, + element_factory: _ElementFactory | None = ..., + *, + comment_factory: Callable[[str | None], Element] | None = ..., + pi_factory: Callable[[str, str | None], Element] | None = ..., + insert_comments: bool = ..., + insert_pis: bool = ..., + ) -> None: ... + insert_comments: bool + insert_pis: bool + else: + def __init__(self, element_factory: _ElementFactory | None = ...) -> None: ... def close(self) -> Element: ... def data(self, __data: str | bytes) -> None: ... def start(self, __tag: str | bytes, __attrs: dict[str | bytes, str | bytes]) -> Element: ... def end(self, __tag: str | bytes) -> Element: ... + if sys.version_info >= (3, 8): + # These two methods have pos-only parameters in the C implementation + def comment(self, __text: str | None) -> Element: ... + def pi(self, __target: str, __text: str | None = ...) -> Element: ... if sys.version_info >= (3, 8): class C14NWriterTarget: @@ -279,6 +297,12 @@ if sys.version_info >= (3, 8): exclude_attrs: Iterable[str] | None = ..., exclude_tags: Iterable[str] | None = ..., ) -> None: ... + def data(self, data: str) -> None: ... + def start_ns(self, prefix: str, uri: str) -> None: ... + def start(self, tag: str, attrs: Mapping[str, str]) -> None: ... + def end(self, tag: str) -> None: ... + def comment(self, text: str) -> None: ... + def pi(self, target: str, data: str) -> None: ... class XMLParser: parser: Any diff --git a/mypy/typeshed/stdlib/xmlrpc/client.pyi b/mypy/typeshed/stdlib/xmlrpc/client.pyi index 061df849eff2..03a6ac69f5b7 100644 --- a/mypy/typeshed/stdlib/xmlrpc/client.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/client.pyi @@ -6,16 +6,16 @@ from _typeshed import Self, SupportsRead, SupportsWrite from datetime import datetime from io import BytesIO from types import TracebackType -from typing import Any, Callable, Dict, Iterable, List, Mapping, Protocol, Tuple, Type, Union, overload +from typing import Any, Callable, Iterable, Mapping, Protocol, Union, overload from typing_extensions import Literal class _SupportsTimeTuple(Protocol): def timetuple(self) -> time.struct_time: ... _DateTimeComparable = Union[DateTime, datetime, str, _SupportsTimeTuple] -_Marshallable = Union[None, bool, int, float, str, bytes, Tuple[Any, ...], List[Any], Dict[Any, Any], datetime, DateTime, Binary] -_XMLDate = Union[int, datetime, Tuple[int, ...], time.struct_time] -_HostType = Union[Tuple[str, Dict[str, str]], str] +_Marshallable = Union[None, bool, int, float, str, bytes, tuple[Any, ...], list[Any], dict[Any, Any], datetime, DateTime, Binary] +_XMLDate = Union[int, datetime, tuple[int, ...], time.struct_time] +_HostType = Union[tuple[str, dict[str, str]], str] def escape(s: str) -> str: ... # undocumented @@ -63,12 +63,12 @@ def _strftime(value: _XMLDate) -> str: ... # undocumented class DateTime: value: str # undocumented - def __init__(self, value: int | str | datetime | time.struct_time | Tuple[int, ...] = ...) -> None: ... + def __init__(self, value: int | str | datetime | time.struct_time | tuple[int, ...] = ...) -> None: ... def __lt__(self, other: _DateTimeComparable) -> bool: ... def __le__(self, other: _DateTimeComparable) -> bool: ... def __gt__(self, other: _DateTimeComparable) -> bool: ... def __ge__(self, other: _DateTimeComparable) -> bool: ... - def __eq__(self, other: _DateTimeComparable) -> bool: ... # type: ignore + def __eq__(self, other: _DateTimeComparable) -> bool: ... # type: ignore[override] def make_comparable(self, other: _DateTimeComparable) -> tuple[str, str]: ... # undocumented def timetuple(self) -> time.struct_time: ... # undocumented def decode(self, data: Any) -> None: ... @@ -86,7 +86,7 @@ class Binary: def _binary(data: bytes) -> Binary: ... # undocumented -WRAPPERS: tuple[Type[DateTime], Type[Binary]] # undocumented +WRAPPERS: tuple[type[DateTime], type[Binary]] # undocumented class ExpatParser: # undocumented def __init__(self, target: Unmarshaller) -> None: ... @@ -96,7 +96,7 @@ class ExpatParser: # undocumented class Marshaller: dispatch: dict[ - Type[Any], Callable[[Marshaller, Any, Callable[[str], Any]], None] + type[Any], Callable[[Marshaller, Any, Callable[[str], Any]], None] ] # TODO: Replace 'Any' with some kind of binding memo: dict[Any, None] @@ -135,7 +135,7 @@ class Unmarshaller: _use_datetime: bool _use_builtin_types: bool def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ...) -> None: ... - def close(self) -> Tuple[_Marshallable, ...]: ... + def close(self) -> tuple[_Marshallable, ...]: ... def getmethodname(self) -> str | None: ... def xml(self, encoding: str, standalone: Any) -> None: ... # Standalone is ignored def start(self, tag: str, attrs: dict[str, str]) -> None: ... @@ -159,7 +159,7 @@ class Unmarshaller: class _MultiCallMethod: # undocumented - __call_list: list[tuple[str, Tuple[_Marshallable, ...]]] + __call_list: list[tuple[str, tuple[_Marshallable, ...]]] __name: str def __init__(self, call_list: list[tuple[str, _Marshallable]], name: str) -> None: ... def __getattr__(self, name: str) -> _MultiCallMethod: ... @@ -174,7 +174,7 @@ class MultiCallIterator: # undocumented class MultiCall: __server: ServerProxy - __call_list: list[tuple[str, Tuple[_Marshallable, ...]]] + __call_list: list[tuple[str, tuple[_Marshallable, ...]]] def __init__(self, server: ServerProxy) -> None: ... def __getattr__(self, item: str) -> _MultiCallMethod: ... def __call__(self) -> MultiCallIterator: ... @@ -186,13 +186,13 @@ FastUnmarshaller: Unmarshaller | None def getparser(use_datetime: bool = ..., use_builtin_types: bool = ...) -> tuple[ExpatParser, Unmarshaller]: ... def dumps( - params: Fault | Tuple[_Marshallable, ...], + params: Fault | tuple[_Marshallable, ...], methodname: str | None = ..., methodresponse: bool | None = ..., encoding: str | None = ..., allow_none: bool = ..., ) -> str: ... -def loads(data: str, use_datetime: bool = ..., use_builtin_types: bool = ...) -> tuple[Tuple[_Marshallable, ...], str | None]: ... +def loads(data: str, use_datetime: bool = ..., use_builtin_types: bool = ...) -> tuple[tuple[_Marshallable, ...], str | None]: ... def gzip_encode(data: bytes) -> bytes: ... # undocumented def gzip_decode(data: bytes, max_decode: int = ...) -> bytes: ... # undocumented @@ -204,9 +204,9 @@ class GzipDecodedResponse(gzip.GzipFile): # undocumented class _Method: # undocumented - __send: Callable[[str, Tuple[_Marshallable, ...]], _Marshallable] + __send: Callable[[str, tuple[_Marshallable, ...]], _Marshallable] __name: str - def __init__(self, send: Callable[[str, Tuple[_Marshallable, ...]], _Marshallable], name: str) -> None: ... + def __init__(self, send: Callable[[str, tuple[_Marshallable, ...]], _Marshallable], name: str) -> None: ... def __getattr__(self, name: str) -> _Method: ... def __call__(self, *args: _Marshallable) -> _Marshallable: ... @@ -228,10 +228,10 @@ class Transport: ) -> None: ... else: def __init__(self, use_datetime: bool = ..., use_builtin_types: bool = ...) -> None: ... - def request(self, host: _HostType, handler: str, request_body: bytes, verbose: bool = ...) -> Tuple[_Marshallable, ...]: ... + def request(self, host: _HostType, handler: str, request_body: bytes, verbose: bool = ...) -> tuple[_Marshallable, ...]: ... def single_request( self, host: _HostType, handler: str, request_body: bytes, verbose: bool = ... - ) -> Tuple[_Marshallable, ...]: ... + ) -> tuple[_Marshallable, ...]: ... def getparser(self) -> tuple[ExpatParser, Unmarshaller]: ... def get_host_info(self, host: _HostType) -> tuple[str, list[tuple[str, str]], dict[str, str]]: ... def make_connection(self, host: _HostType) -> http.client.HTTPConnection: ... @@ -239,7 +239,7 @@ class Transport: def send_request(self, host: _HostType, handler: str, request_body: bytes, debug: bool) -> http.client.HTTPConnection: ... def send_headers(self, connection: http.client.HTTPConnection, headers: list[tuple[str, str]]) -> None: ... def send_content(self, connection: http.client.HTTPConnection, request_body: bytes) -> None: ... - def parse_response(self, response: http.client.HTTPResponse) -> Tuple[_Marshallable, ...]: ... + def parse_response(self, response: http.client.HTTPResponse) -> tuple[_Marshallable, ...]: ... class SafeTransport(Transport): @@ -301,9 +301,9 @@ class ServerProxy: def __call__(self, attr: str) -> Callable[[], None] | Transport: ... 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 __close(self) -> None: ... # undocumented - def __request(self, methodname: str, params: Tuple[_Marshallable, ...]) -> Tuple[_Marshallable, ...]: ... # undocumented + def __request(self, methodname: str, params: tuple[_Marshallable, ...]) -> tuple[_Marshallable, ...]: ... # undocumented Server = ServerProxy diff --git a/mypy/typeshed/stdlib/xmlrpc/server.pyi b/mypy/typeshed/stdlib/xmlrpc/server.pyi index bf5611fbaa96..650a659452e0 100644 --- a/mypy/typeshed/stdlib/xmlrpc/server.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/server.pyi @@ -3,11 +3,11 @@ import pydoc import socketserver import sys from datetime import datetime -from typing import Any, Callable, Dict, Iterable, List, Mapping, Pattern, Protocol, Tuple, Type, Union +from typing import Any, Callable, Iterable, Mapping, Pattern, Protocol, Union from xmlrpc.client import Fault # TODO: Recursive type on tuple, list, dict -_Marshallable = Union[None, bool, int, float, str, bytes, Tuple[Any, ...], List[Any], Dict[Any, Any], datetime] +_Marshallable = Union[None, bool, int, float, str, bytes, tuple[Any, ...], list[Any], dict[Any, Any], datetime] # The dispatch accepts anywhere from 0 to N arguments, no easy way to allow this in mypy class _DispatchArity0(Protocol): @@ -53,7 +53,7 @@ class SimpleXMLRPCDispatcher: # undocumented def _marshaled_dispatch( self, data: str, - dispatch_method: Callable[[str | None, Tuple[_Marshallable, ...]], Fault | Tuple[_Marshallable, ...]] | None = ..., + dispatch_method: Callable[[str | None, tuple[_Marshallable, ...]], Fault | tuple[_Marshallable, ...]] | None = ..., path: Any | None = ..., ) -> str: ... # undocumented def system_listMethods(self) -> list[str]: ... # undocumented @@ -81,7 +81,7 @@ class SimpleXMLRPCServer(socketserver.TCPServer, SimpleXMLRPCDispatcher): def __init__( self, addr: tuple[str, int], - requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., + requestHandler: type[SimpleXMLRPCRequestHandler] = ..., logRequests: bool = ..., allow_none: bool = ..., encoding: str | None = ..., @@ -97,7 +97,7 @@ class MultiPathXMLRPCServer(SimpleXMLRPCServer): # undocumented def __init__( self, addr: tuple[str, int], - requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., + requestHandler: type[SimpleXMLRPCRequestHandler] = ..., logRequests: bool = ..., allow_none: bool = ..., encoding: str | None = ..., @@ -109,7 +109,7 @@ class MultiPathXMLRPCServer(SimpleXMLRPCServer): # undocumented def _marshaled_dispatch( self, data: str, - dispatch_method: Callable[[str | None, Tuple[_Marshallable, ...]], Fault | Tuple[_Marshallable, ...]] | None = ..., + dispatch_method: Callable[[str | None, tuple[_Marshallable, ...]], Fault | tuple[_Marshallable, ...]] | None = ..., path: Any | None = ..., ) -> str: ... @@ -120,7 +120,16 @@ class CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher): def handle_request(self, request_text: str | None = ...) -> None: ... class ServerHTMLDoc(pydoc.HTMLDoc): # undocumented - def docroutine(self, object: object, name: str, mod: str | None = ..., funcs: Mapping[str, str] = ..., classes: Mapping[str, str] = ..., methods: Mapping[str, str] = ..., cl: type | None = ...) -> str: ... # type: ignore + def docroutine( # type: ignore[override] + self, + object: object, + name: str, + mod: str | None = ..., + funcs: Mapping[str, str] = ..., + classes: Mapping[str, str] = ..., + methods: Mapping[str, str] = ..., + cl: type | None = ..., + ) -> str: ... def docserver(self, server_name: str, package_documentation: str, methods: dict[str, str]) -> str: ... class XMLRPCDocGenerator: # undocumented @@ -141,7 +150,7 @@ class DocXMLRPCServer(SimpleXMLRPCServer, XMLRPCDocGenerator): def __init__( self, addr: tuple[str, int], - requestHandler: Type[SimpleXMLRPCRequestHandler] = ..., + requestHandler: type[SimpleXMLRPCRequestHandler] = ..., logRequests: bool = ..., allow_none: bool = ..., encoding: str | None = ..., diff --git a/mypy/typeshed/stdlib/zipfile.pyi b/mypy/typeshed/stdlib/zipfile.pyi index 2335428549dc..a0a968ac94b0 100644 --- a/mypy/typeshed/stdlib/zipfile.pyi +++ b/mypy/typeshed/stdlib/zipfile.pyi @@ -3,10 +3,10 @@ import sys from _typeshed import Self, StrPath from os import PathLike from types import TracebackType -from typing import IO, Any, Callable, Iterable, Iterator, Protocol, Sequence, Tuple, Type, overload +from typing import IO, Any, Callable, Iterable, Iterator, Protocol, Sequence, overload from typing_extensions import Literal -_DateTuple = Tuple[int, int, int, int, int, int] +_DateTuple = tuple[int, int, int, int, int, int] _ReadWriteMode = Literal["r", "w"] _ReadWriteBinaryMode = Literal["r", "w", "rb", "wb"] _ZipFileMode = Literal["r", "w", "x", "a"] @@ -97,10 +97,9 @@ class ZipExtFile(io.BufferedIOBase): close_fileobj: Literal[False] = ..., ) -> None: ... def read(self, n: int | None = ...) -> bytes: ... - def readline(self, limit: int = ...) -> bytes: ... # type: ignore - def __repr__(self) -> str: ... + def readline(self, limit: int = ...) -> bytes: ... # type: ignore[override] def peek(self, n: int = ...) -> bytes: ... - def read1(self, n: int | None) -> bytes: ... # type: ignore + def read1(self, n: int | None) -> bytes: ... # type: ignore[override] if sys.version_info >= (3, 7): def seek(self, offset: int, whence: int = ...) -> int: ... @@ -145,7 +144,7 @@ class ZipFile: ) -> 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 close(self) -> None: ... def getinfo(self, name: str) -> ZipInfo: ... diff --git a/mypy/typeshed/stdlib/zipimport.pyi b/mypy/typeshed/stdlib/zipimport.pyi index 155b9742aa57..3435092a4722 100644 --- a/mypy/typeshed/stdlib/zipimport.pyi +++ b/mypy/typeshed/stdlib/zipimport.pyi @@ -1,5 +1,6 @@ import os import sys +from importlib.machinery import ModuleSpec from types import CodeType, ModuleType from typing import Any @@ -8,7 +9,7 @@ if sys.version_info >= (3, 7): class ZipImportError(ImportError): ... -class zipimporter(object): +class zipimporter: archive: str prefix: str def __init__(self, path: str | bytes | os.PathLike[Any]) -> None: ... @@ -22,3 +23,6 @@ class zipimporter(object): def get_source(self, fullname: str) -> str | None: ... def is_package(self, fullname: str) -> bool: ... def load_module(self, fullname: str) -> ModuleType: ... + if sys.version_info >= (3, 10): + def find_spec(self, fullname: str, target: ModuleType | None = ...) -> ModuleSpec | None: ... + def invalidate_caches(self) -> None: ... diff --git a/mypy/typeshed/stdlib/zlib.pyi b/mypy/typeshed/stdlib/zlib.pyi index 5acc4190f1fe..646c96bd2bef 100644 --- a/mypy/typeshed/stdlib/zlib.pyi +++ b/mypy/typeshed/stdlib/zlib.pyi @@ -1,12 +1,16 @@ from array import array from typing import Any +from typing_extensions import Literal DEFLATED: int DEF_MEM_LEVEL: int MAX_WBITS: int ZLIB_VERSION: str +Z_NO_COMPRESSION: Literal[0] +Z_PARTIAL_FLUSH: Literal[1] Z_BEST_COMPRESSION: int Z_BEST_SPEED: int +Z_BLOCK: Literal[5] Z_DEFAULT_COMPRESSION: int Z_DEFAULT_STRATEGY: int Z_FILTERED: int @@ -17,6 +21,7 @@ Z_HUFFMAN_ONLY: int Z_NO_FLUSH: int Z_RLE: int Z_SYNC_FLUSH: int +Z_TREES: Literal[6] DEF_BUF_SIZE: int ZLIB_RUNTIME_VERSION: str diff --git a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi index 4f924e0cc4bf..86439251083b 100644 --- a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi +++ b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi @@ -1,9 +1,9 @@ import typing -from _typeshed import StrPath +from _typeshed import Self, StrPath from datetime import tzinfo -from typing import Any, Iterable, Protocol, Sequence, Type +from typing import Any, Iterable, Protocol, Sequence -_T = typing.TypeVar("_T", bound="ZoneInfo") +_T = typing.TypeVar("_T", bound=ZoneInfo) class _IOBytes(Protocol): def read(self, __size: int) -> bytes: ... @@ -14,9 +14,9 @@ class ZoneInfo(tzinfo): def key(self) -> str: ... def __init__(self, key: str) -> None: ... @classmethod - def no_cache(cls: Type[_T], key: str) -> _T: ... + def no_cache(cls: type[Self], key: str) -> Self: ... @classmethod - def from_file(cls: Type[_T], __fobj: _IOBytes, key: str | None = ...) -> _T: ... + def from_file(cls: type[Self], __fobj: _IOBytes, key: str | None = ...) -> Self: ... @classmethod def clear_cache(cls, *, only_keys: Iterable[str] = ...) -> None: ... diff --git a/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi b/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi index fc6de37d07d1..89f312336b58 100644 --- a/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi +++ b/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi @@ -1,19 +1,20 @@ import abc import sys -from typing import Any, Callable, Generic, ItemsView, KeysView, Mapping, Type, TypeVar, Union, ValuesView +from _typeshed import Self +from typing import Any, Callable, Generic, ItemsView, KeysView, Mapping, TypeVar, ValuesView _T = TypeVar("_T") _U = TypeVar("_U") # Internal mypy fallback type for all typed dicts (does not exist at runtime) class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): - def copy(self: _T) -> _T: ... + def copy(self: Self) -> Self: ... # Using NoReturn so that only calls using mypy plugin hook that specialize the signature # can go through. def setdefault(self, k: NoReturn, default: object) -> object: ... # Mypy plugin hook for 'pop' expects that 'default' has a type variable type. def pop(self, k: NoReturn, default: _T = ...) -> object: ... # type: ignore - def update(self: _T, __m: _T) -> None: ... + def update(self: Self, __m: Self) -> None: ... if sys.version_info >= (3, 0): def items(self) -> ItemsView[str, object]: ... def keys(self) -> KeysView[str]: ... @@ -25,7 +26,7 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): def viewvalues(self) -> ValuesView[object]: ... def __delitem__(self, k: NoReturn) -> None: ... -def TypedDict(typename: str, fields: dict[str, Type[Any]], total: bool = ...) -> Type[dict[str, Any]]: ... +def TypedDict(typename: str, fields: dict[str, type[Any]], total: bool = ...) -> type[dict[str, Any]]: ... def Arg(type: _T = ..., name: str | None = ...) -> _T: ... def DefaultArg(type: _T = ..., name: str | None = ...) -> _T: ... def NamedArg(type: _T = ..., name: str | None = ...) -> _T: ... @@ -34,9 +35,8 @@ def VarArg(type: _T = ...) -> _T: ... def KwArg(type: _T = ...) -> _T: ... # 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] # Deprecated: Use typing.NoReturn instead. +# Deprecated: Use typing.NoReturn instead. +class NoReturn: ... # This is intended as a class decorator, but mypy rejects abstract classes # when a Type[_T] is expected, so we can't give it the type we want