From 43fa5c660f5a2d64a809d1dfa9b28d932e33aded Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Tue, 20 Apr 2021 21:57:53 -0700 Subject: [PATCH 1/2] Sync typeshed Source commit: https://github.com/python/typeshed/commit/fc660d6d4170ce1bcb0a17151f7fa5b21db8fecc --- mypy/typeshed/stdlib/@python2/UserString.pyi | 4 +- mypy/typeshed/stdlib/@python2/__builtin__.pyi | 20 +- mypy/typeshed/stdlib/@python2/builtins.pyi | 20 +- mypy/typeshed/stdlib/@python2/cgi.pyi | 109 +++++ .../stdlib/@python2/logging/__init__.pyi | 292 +++++++++++ .../stdlib/@python2/logging/config.pyi | 14 + .../stdlib/@python2/logging/handlers.pyi | 133 +++++ mypy/typeshed/stdlib/@python2/platform.pyi | 10 +- mypy/typeshed/stdlib/VERSIONS | 6 +- mypy/typeshed/stdlib/__future__.pyi | 1 + mypy/typeshed/stdlib/_codecs.pyi | 8 +- mypy/typeshed/stdlib/_collections_abc.pyi | 56 +++ mypy/typeshed/stdlib/_compression.pyi | 9 +- mypy/typeshed/stdlib/_curses.pyi | 54 ++- mypy/typeshed/stdlib/_dummy_threading.pyi | 9 +- mypy/typeshed/stdlib/_heapq.pyi | 2 +- mypy/typeshed/stdlib/_tkinter.pyi | 24 +- mypy/typeshed/stdlib/_typeshed/__init__.pyi | 50 +- mypy/typeshed/stdlib/_typeshed/tkinter.pyi | 7 + mypy/typeshed/stdlib/_weakref.pyi | 10 +- mypy/typeshed/stdlib/_weakrefset.pyi | 4 +- mypy/typeshed/stdlib/asyncio/base_events.pyi | 20 +- mypy/typeshed/stdlib/asyncio/events.pyi | 2 +- .../stdlib/asyncio/format_helpers.pyi | 2 +- .../stdlib/asyncio/proactor_events.pyi | 16 +- mypy/typeshed/stdlib/asyncio/sslproto.pyi | 2 +- mypy/typeshed/stdlib/asyncio/streams.pyi | 3 +- mypy/typeshed/stdlib/asyncio/tasks.pyi | 39 +- mypy/typeshed/stdlib/asyncio/trsock.pyi | 2 +- mypy/typeshed/stdlib/asyncio/unix_events.pyi | 15 +- mypy/typeshed/stdlib/base64.pyi | 8 +- mypy/typeshed/stdlib/binascii.pyi | 10 +- mypy/typeshed/stdlib/builtins.pyi | 320 +++++++----- mypy/typeshed/stdlib/bz2.pyi | 16 +- mypy/typeshed/stdlib/calendar.pyi | 6 +- mypy/typeshed/stdlib/cgi.pyi | 136 ++---- mypy/typeshed/stdlib/cmath.pyi | 2 +- mypy/typeshed/stdlib/codecs.pyi | 20 +- mypy/typeshed/stdlib/collections/__init__.pyi | 66 +-- mypy/typeshed/stdlib/collections/abc.pyi | 29 +- mypy/typeshed/stdlib/compileall.pyi | 56 +-- mypy/typeshed/stdlib/configparser.pyi | 8 +- mypy/typeshed/stdlib/ctypes/__init__.pyi | 34 +- mypy/typeshed/stdlib/dataclasses.pyi | 20 +- mypy/typeshed/stdlib/dbm/__init__.pyi | 6 +- .../stdlib/distutils/archive_util.pyi | 12 +- mypy/typeshed/stdlib/distutils/debug.pyi | 4 +- mypy/typeshed/stdlib/distutils/extension.pyi | 26 +- .../stdlib/distutils/fancy_getopt.pyi | 5 +- mypy/typeshed/stdlib/distutils/filelist.pyi | 69 ++- mypy/typeshed/stdlib/distutils/sysconfig.pyi | 1 - mypy/typeshed/stdlib/distutils/text_file.pyi | 2 +- .../stdlib/email/_header_value_parser.pyi | 411 ++++++++++++++++ mypy/typeshed/stdlib/email/errors.pyi | 7 +- mypy/typeshed/stdlib/email/generator.pyi | 28 +- mypy/typeshed/stdlib/email/headerregistry.pyi | 109 +++-- mypy/typeshed/stdlib/email/message.pyi | 7 +- mypy/typeshed/stdlib/email/parser.pyi | 6 +- mypy/typeshed/stdlib/email/utils.pyi | 20 +- mypy/typeshed/stdlib/encodings/__init__.pyi | 10 +- mypy/typeshed/stdlib/encodings/utf_8.pyi | 18 +- mypy/typeshed/stdlib/enum.pyi | 5 +- mypy/typeshed/stdlib/fcntl.pyi | 2 +- mypy/typeshed/stdlib/functools.pyi | 10 +- mypy/typeshed/stdlib/getopt.pyi | 7 +- mypy/typeshed/stdlib/gettext.pyi | 2 +- mypy/typeshed/stdlib/gzip.pyi | 92 +++- mypy/typeshed/stdlib/hashlib.pyi | 5 +- mypy/typeshed/stdlib/heapq.pyi | 4 +- mypy/typeshed/stdlib/html/parser.pyi | 2 +- mypy/typeshed/stdlib/http/client.pyi | 23 +- mypy/typeshed/stdlib/http/cookiejar.pyi | 10 +- mypy/typeshed/stdlib/http/cookies.pyi | 9 +- mypy/typeshed/stdlib/http/server.pyi | 3 +- mypy/typeshed/stdlib/importlib/abc.pyi | 7 +- mypy/typeshed/stdlib/importlib/machinery.pyi | 27 +- mypy/typeshed/stdlib/importlib/metadata.pyi | 6 +- mypy/typeshed/stdlib/importlib/resources.pyi | 5 +- mypy/typeshed/stdlib/importlib/util.pyi | 7 +- mypy/typeshed/stdlib/itertools.pyi | 255 ++++++---- mypy/typeshed/stdlib/json/__init__.pyi | 1 + mypy/typeshed/stdlib/locale.pyi | 6 +- mypy/typeshed/stdlib/logging/__init__.pyi | 459 ++++++------------ mypy/typeshed/stdlib/logging/config.pyi | 32 +- mypy/typeshed/stdlib/logging/handlers.pyi | 234 ++++----- mypy/typeshed/stdlib/netrc.pyi | 4 +- mypy/typeshed/stdlib/ntpath.pyi | 4 +- mypy/typeshed/stdlib/operator.pyi | 54 ++- mypy/typeshed/stdlib/optparse.pyi | 8 +- mypy/typeshed/stdlib/os/__init__.pyi | 31 ++ mypy/typeshed/stdlib/pipes.pyi | 2 +- mypy/typeshed/stdlib/pkgutil.pyi | 9 +- mypy/typeshed/stdlib/pyexpat/__init__.pyi | 2 +- mypy/typeshed/stdlib/random.pyi | 21 +- mypy/typeshed/stdlib/re.pyi | 8 +- mypy/typeshed/stdlib/resource.pyi | 9 +- mypy/typeshed/stdlib/runpy.pyi | 4 +- mypy/typeshed/stdlib/shelve.pyi | 4 +- mypy/typeshed/stdlib/shlex.pyi | 6 +- mypy/typeshed/stdlib/shutil.pyi | 6 +- mypy/typeshed/stdlib/smtpd.pyi | 26 +- mypy/typeshed/stdlib/smtplib.pyi | 2 +- mypy/typeshed/stdlib/socket.pyi | 2 +- mypy/typeshed/stdlib/sqlite3/dbapi2.pyi | 4 +- mypy/typeshed/stdlib/sre_constants.pyi | 2 +- mypy/typeshed/stdlib/ssl.pyi | 65 ++- mypy/typeshed/stdlib/struct.pyi | 2 +- mypy/typeshed/stdlib/subprocess.pyi | 36 +- mypy/typeshed/stdlib/sunau.pyi | 12 +- mypy/typeshed/stdlib/symtable.pyi | 9 +- mypy/typeshed/stdlib/sysconfig.pyi | 4 +- mypy/typeshed/stdlib/tarfile.pyi | 97 ++++ mypy/typeshed/stdlib/tempfile.pyi | 47 +- mypy/typeshed/stdlib/threading.pyi | 9 +- mypy/typeshed/stdlib/timeit.pyi | 4 +- mypy/typeshed/stdlib/tkinter/__init__.pyi | 27 +- mypy/typeshed/stdlib/tkinter/colorchooser.pyi | 9 + mypy/typeshed/stdlib/tkinter/commondialog.pyi | 4 +- mypy/typeshed/stdlib/tkinter/dnd.pyi | 13 + mypy/typeshed/stdlib/tkinter/filedialog.pyi | 8 +- mypy/typeshed/stdlib/tkinter/font.pyi | 5 +- mypy/typeshed/stdlib/tkinter/messagebox.pyi | 4 +- mypy/typeshed/stdlib/tkinter/scrolledtext.pyi | 8 + mypy/typeshed/stdlib/tkinter/simpledialog.pyi | 27 ++ mypy/typeshed/stdlib/tkinter/tix.pyi | 305 ++++++++++++ mypy/typeshed/stdlib/tkinter/ttk.pyi | 16 +- mypy/typeshed/stdlib/trace.pyi | 13 +- mypy/typeshed/stdlib/traceback.pyi | 56 ++- mypy/typeshed/stdlib/turtle.pyi | 10 +- mypy/typeshed/stdlib/types.pyi | 52 +- mypy/typeshed/stdlib/typing.pyi | 10 +- mypy/typeshed/stdlib/typing_extensions.pyi | 117 +++++ mypy/typeshed/stdlib/unittest/case.pyi | 10 +- mypy/typeshed/stdlib/unittest/mock.pyi | 75 +-- mypy/typeshed/stdlib/urllib/error.pyi | 8 +- mypy/typeshed/stdlib/urllib/parse.pyi | 44 +- mypy/typeshed/stdlib/wave.pyi | 7 +- mypy/typeshed/stdlib/weakref.pyi | 35 +- .../typeshed/stdlib/wsgiref/simple_server.pyi | 6 +- mypy/typeshed/stdlib/wsgiref/util.pyi | 6 +- mypy/typeshed/stdlib/wsgiref/validate.pyi | 14 +- mypy/typeshed/stdlib/xml/dom/domreg.pyi | 2 +- mypy/typeshed/stdlib/xml/dom/minidom.pyi | 4 +- .../typeshed/stdlib/xml/etree/ElementPath.pyi | 4 +- .../typeshed/stdlib/xml/etree/ElementTree.pyi | 8 +- mypy/typeshed/stdlib/xml/sax/xmlreader.pyi | 1 - mypy/typeshed/stdlib/xmlrpc/client.pyi | 9 +- mypy/typeshed/stdlib/xmlrpc/server.pyi | 2 +- mypy/typeshed/stdlib/zipfile.pyi | 2 + mypy/typeshed/stdlib/zlib.pyi | 11 +- 150 files changed, 3548 insertions(+), 1505 deletions(-) create mode 100644 mypy/typeshed/stdlib/@python2/cgi.pyi create mode 100644 mypy/typeshed/stdlib/@python2/logging/__init__.pyi create mode 100644 mypy/typeshed/stdlib/@python2/logging/config.pyi create mode 100644 mypy/typeshed/stdlib/@python2/logging/handlers.pyi create mode 100644 mypy/typeshed/stdlib/_collections_abc.pyi create mode 100644 mypy/typeshed/stdlib/_typeshed/tkinter.pyi create mode 100644 mypy/typeshed/stdlib/email/_header_value_parser.pyi create mode 100644 mypy/typeshed/stdlib/tkinter/colorchooser.pyi create mode 100644 mypy/typeshed/stdlib/tkinter/dnd.pyi create mode 100644 mypy/typeshed/stdlib/tkinter/scrolledtext.pyi create mode 100644 mypy/typeshed/stdlib/tkinter/simpledialog.pyi create mode 100644 mypy/typeshed/stdlib/tkinter/tix.pyi create mode 100644 mypy/typeshed/stdlib/typing_extensions.pyi diff --git a/mypy/typeshed/stdlib/@python2/UserString.pyi b/mypy/typeshed/stdlib/@python2/UserString.pyi index df7bbc363b9f..33de4873992b 100644 --- a/mypy/typeshed/stdlib/@python2/UserString.pyi +++ b/mypy/typeshed/stdlib/@python2/UserString.pyi @@ -27,7 +27,7 @@ class UserString(Sequence[UserString]): def count(self, sub: int, start: int = ..., end: int = ...) -> int: ... def decode(self: _UST, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UST: ... def encode(self: _UST, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UST: ... - def endswith(self, suffix: Text, start: int = ..., end: int = ...) -> bool: ... + def endswith(self, suffix: Union[Text, Tuple[Text, ...]], start: Optional[int] = ..., end: Optional[int] = ...) -> bool: ... def expandtabs(self: _UST, tabsize: int = ...) -> _UST: ... def find(self, sub: Text, start: int = ..., end: int = ...) -> int: ... def index(self, sub: Text, start: int = ..., end: int = ...) -> int: ... @@ -54,7 +54,7 @@ class UserString(Sequence[UserString]): def split(self, sep: Optional[Text] = ..., maxsplit: int = ...) -> List[Text]: ... def rsplit(self, sep: Optional[Text] = ..., maxsplit: int = ...) -> List[Text]: ... def splitlines(self, keepends: int = ...) -> List[Text]: ... - def startswith(self, suffix: Text, start: int = ..., end: int = ...) -> bool: ... + def startswith(self, prefix: Union[Text, Tuple[Text, ...]], start: Optional[int] = ..., end: Optional[int] = ...) -> bool: ... def strip(self: _UST, chars: Optional[Text] = ...) -> _UST: ... def swapcase(self: _UST) -> _UST: ... def title(self: _UST) -> _UST: ... diff --git a/mypy/typeshed/stdlib/@python2/__builtin__.pyi b/mypy/typeshed/stdlib/@python2/__builtin__.pyi index 0e01b635cf26..8f42584aaa2a 100644 --- a/mypy/typeshed/stdlib/@python2/__builtin__.pyi +++ b/mypy/typeshed/stdlib/@python2/__builtin__.pyi @@ -296,7 +296,9 @@ 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: Union[unicode, Tuple[unicode, ...]], start: int = ..., end: int = ...) -> bool: ... + def endswith( + self, __suffix: Union[unicode, Tuple[unicode, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... + ) -> 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: ... @@ -326,7 +328,9 @@ class unicode(basestring, Sequence[unicode]): def rstrip(self, chars: unicode = ...) -> unicode: ... def split(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... def splitlines(self, keepends: bool = ...) -> List[unicode]: ... - def startswith(self, prefix: Union[unicode, Tuple[unicode, ...]], start: int = ..., end: int = ...) -> bool: ... + def startswith( + self, __prefix: Union[unicode, Tuple[unicode, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... + ) -> bool: ... def strip(self, chars: unicode = ...) -> unicode: ... def swapcase(self) -> unicode: ... def title(self) -> unicode: ... @@ -369,7 +373,9 @@ class str(Sequence[str], basestring): def count(self, x: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... - def endswith(self, suffix: Union[Text, Tuple[Text, ...]]) -> bool: ... + def endswith( + self, __suffix: Union[Text, Tuple[Text, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... + ) -> bool: ... def expandtabs(self, tabsize: int = ...) -> str: ... def find(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... def format(self, *args: object, **kwargs: object) -> str: ... @@ -418,7 +424,9 @@ class str(Sequence[str], basestring): @overload def split(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... def splitlines(self, keepends: bool = ...) -> List[str]: ... - def startswith(self, prefix: Union[Text, Tuple[Text, ...]]) -> bool: ... + def startswith( + self, __prefix: Union[Text, Tuple[Text, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... + ) -> bool: ... @overload def strip(self, __chars: str = ...) -> str: ... @overload @@ -468,7 +476,9 @@ 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: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def endswith( + self, __suffix: Union[bytes, Tuple[bytes, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... + ) -> bool: ... def expandtabs(self, tabsize: int = ...) -> bytearray: ... def extend(self, iterable: Union[str, Iterable[int]]) -> None: ... def find(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/builtins.pyi b/mypy/typeshed/stdlib/@python2/builtins.pyi index 0e01b635cf26..8f42584aaa2a 100644 --- a/mypy/typeshed/stdlib/@python2/builtins.pyi +++ b/mypy/typeshed/stdlib/@python2/builtins.pyi @@ -296,7 +296,9 @@ 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: Union[unicode, Tuple[unicode, ...]], start: int = ..., end: int = ...) -> bool: ... + def endswith( + self, __suffix: Union[unicode, Tuple[unicode, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... + ) -> 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: ... @@ -326,7 +328,9 @@ class unicode(basestring, Sequence[unicode]): def rstrip(self, chars: unicode = ...) -> unicode: ... def split(self, sep: Optional[unicode] = ..., maxsplit: int = ...) -> List[unicode]: ... def splitlines(self, keepends: bool = ...) -> List[unicode]: ... - def startswith(self, prefix: Union[unicode, Tuple[unicode, ...]], start: int = ..., end: int = ...) -> bool: ... + def startswith( + self, __prefix: Union[unicode, Tuple[unicode, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... + ) -> bool: ... def strip(self, chars: unicode = ...) -> unicode: ... def swapcase(self) -> unicode: ... def title(self) -> unicode: ... @@ -369,7 +373,9 @@ class str(Sequence[str], basestring): def count(self, x: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... def decode(self, encoding: Text = ..., errors: Text = ...) -> unicode: ... def encode(self, encoding: Text = ..., errors: Text = ...) -> bytes: ... - def endswith(self, suffix: Union[Text, Tuple[Text, ...]]) -> bool: ... + def endswith( + self, __suffix: Union[Text, Tuple[Text, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... + ) -> bool: ... def expandtabs(self, tabsize: int = ...) -> str: ... def find(self, sub: Text, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... def format(self, *args: object, **kwargs: object) -> str: ... @@ -418,7 +424,9 @@ class str(Sequence[str], basestring): @overload def split(self, sep: unicode, maxsplit: int = ...) -> List[unicode]: ... def splitlines(self, keepends: bool = ...) -> List[str]: ... - def startswith(self, prefix: Union[Text, Tuple[Text, ...]]) -> bool: ... + def startswith( + self, __prefix: Union[Text, Tuple[Text, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... + ) -> bool: ... @overload def strip(self, __chars: str = ...) -> str: ... @overload @@ -468,7 +476,9 @@ 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: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def endswith( + self, __suffix: Union[bytes, Tuple[bytes, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... + ) -> bool: ... def expandtabs(self, tabsize: int = ...) -> bytearray: ... def extend(self, iterable: Union[str, Iterable[int]]) -> None: ... def find(self, __sub: str, __start: int = ..., __end: int = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/@python2/cgi.pyi b/mypy/typeshed/stdlib/@python2/cgi.pyi new file mode 100644 index 000000000000..c3519bba9b20 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/cgi.pyi @@ -0,0 +1,109 @@ +from _typeshed import SupportsGetItem, SupportsItemAccess +from builtins import type as _type +from typing import IO, Any, AnyStr, Iterable, Iterator, List, Mapping, Optional, Protocol, TypeVar, Union +from UserDict import UserDict + +_T = TypeVar("_T", bound=FieldStorage) + +def parse( + fp: Optional[IO[Any]] = ..., + 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]]: ... + +class _Environ(Protocol): + def __getitem__(self, __k: str) -> str: ... + def keys(self) -> Iterable[str]: ... + +def parse_header(line: str) -> tuple[str, dict[str, str]]: ... +def test(environ: _Environ = ...) -> None: ... +def print_environ(environ: _Environ = ...) -> None: ... +def print_form(form: dict[str, Any]) -> None: ... +def print_directory() -> None: ... +def print_environ_usage() -> None: ... +def escape(s: AnyStr, quote: bool = ...) -> AnyStr: ... + +class MiniFieldStorage: + # The first five "Any" attributes here are always None, but mypy doesn't support that + filename: Any + list: Any + type: Any + file: Optional[IO[bytes]] + type_options: dict[Any, Any] + disposition: Any + disposition_options: dict[Any, Any] + headers: dict[Any, Any] + name: Any + value: Any + def __init__(self, name: Any, value: Any) -> None: ... + def __repr__(self) -> str: ... + +class FieldStorage(object): + FieldStorageClass: Optional[_type] + keep_blank_values: int + strict_parsing: int + qs_on_post: Optional[str] + headers: Mapping[str, str] + fp: IO[bytes] + encoding: str + errors: str + outerboundary: bytes + bytes_read: int + limit: Optional[int] + disposition: str + disposition_options: dict[str, str] + filename: Optional[str] + file: Optional[IO[bytes]] + type: str + type_options: dict[str, str] + innerboundary: bytes + length: int + done: int + list: Optional[List[Any]] + value: Union[None, bytes, List[Any]] + def __init__( + self, + fp: IO[Any] = ..., + headers: Mapping[str, str] = ..., + outerboundary: bytes = ..., + environ: SupportsGetItem[str, str] = ..., + 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: ... + def getfirst(self, key: str, default: Any = ...) -> Any: ... + def getlist(self, key: str) -> List[Any]: ... + def keys(self) -> List[str]: ... + def has_key(self, key: str) -> bool: ... + def __contains__(self, key: str) -> bool: ... + def __len__(self) -> int: ... + def __nonzero__(self) -> bool: ... + # 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]]): + query_string: str + def __init__(self, environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ...) -> None: ... + +class SvFormContentDict(FormContentDict): + def getlist(self, key: Any) -> Any: ... + +class InterpFormContentDict(SvFormContentDict): ... + +class FormContent(FormContentDict): + # TODO this should have + # def values(self, key: Any) -> Any: ... + # but this is incompatible with the supertype, and adding '# type: ignore' triggers + # a parse error in pytype (https://github.com/google/pytype/issues/53) + def indexed_value(self, key: Any, location: int) -> Any: ... + def value(self, key: Any) -> Any: ... + def length(self, key: Any) -> int: ... + def stripped(self, key: Any) -> Any: ... + def pars(self) -> dict[Any, Any]: ... diff --git a/mypy/typeshed/stdlib/@python2/logging/__init__.pyi b/mypy/typeshed/stdlib/@python2/logging/__init__.pyi new file mode 100644 index 000000000000..a683113285a1 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/logging/__init__.pyi @@ -0,0 +1,292 @@ +import threading +from _typeshed import StrPath +from string import Template +from time import struct_time +from types import FrameType, TracebackType +from typing import ( + IO, + Any, + Callable, + Dict, + Iterable, + List, + Mapping, + MutableMapping, + Optional, + Sequence, + Text, + Tuple, + Union, + overload, +) + +_SysExcInfoType = Union[Tuple[type, BaseException, Optional[TracebackType]], Tuple[None, None, None]] +_ExcInfoType = Union[None, bool, _SysExcInfoType] +_ArgsType = Union[Tuple[Any, ...], Mapping[str, Any]] +_FilterType = Union[Filter, Callable[[LogRecord], int]] +_Level = Union[int, Text] + +raiseExceptions: bool +logThreads: bool +logMultiprocessing: bool +logProcesses: bool +_srcfile: Optional[str] + +def currentframe() -> FrameType: ... + +_levelNames: Dict[Union[int, str], Union[str, int]] # Union[int:str, str:int] + +class Filterer(object): + 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 Logger(Filterer): + name: str + level: int + parent: Union[Logger, PlaceHolder] + propagate: bool + handlers: List[Handler] + disabled: int + def __init__(self, name: str, level: _Level = ...) -> None: ... + def setLevel(self, level: _Level) -> None: ... + def isEnabledFor(self, level: int) -> bool: ... + def getEffectiveLevel(self) -> int: ... + def getChild(self, suffix: str) -> Logger: ... + def debug( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def info( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def warning( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + warn = warning + def error( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def critical( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + fatal = critical + def log( + self, + level: int, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def exception( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def _log( + self, + level: int, + msg: Any, + args: _ArgsType, + exc_info: Optional[_ExcInfoType] = ..., + extra: Optional[Dict[str, Any]] = ..., + ) -> 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 handle(self, record: LogRecord) -> None: ... + def makeRecord( + self, + name: str, + level: int, + fn: str, + lno: int, + msg: Any, + args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ..., + extra: Optional[Mapping[str, Any]] = ..., + ) -> LogRecord: ... + +CRITICAL: int +FATAL: int +ERROR: int +WARNING: int +WARN: int +INFO: int +DEBUG: int +NOTSET: int + +class Handler(Filterer): + level: int # undocumented + formatter: Optional[Formatter] # undocumented + lock: Optional[threading.Lock] # undocumented + name: Optional[str] # undocumented + def __init__(self, level: _Level = ...) -> None: ... + def createLock(self) -> None: ... + def acquire(self) -> None: ... + def release(self) -> None: ... + def setLevel(self, level: _Level) -> None: ... + def setFormatter(self, fmt: Formatter) -> None: ... + def filter(self, record: LogRecord) -> bool: ... + def flush(self) -> None: ... + def close(self) -> None: ... + def handle(self, record: LogRecord) -> None: ... + def handleError(self, record: LogRecord) -> None: ... + def format(self, record: LogRecord) -> str: ... + def emit(self, record: LogRecord) -> None: ... + +class Formatter: + converter: Callable[[Optional[float]], struct_time] + _fmt: Optional[str] + datefmt: Optional[str] + def __init__(self, fmt: Optional[str] = ..., datefmt: Optional[str] = ...) -> None: ... + def format(self, record: LogRecord) -> str: ... + def formatTime(self, record: LogRecord, datefmt: Optional[str] = ...) -> str: ... + def formatException(self, ei: _SysExcInfoType) -> str: ... + +class Filter: + def __init__(self, name: str = ...) -> None: ... + def filter(self, record: LogRecord) -> bool: ... + +class LogRecord: + args: _ArgsType + asctime: str + created: int + exc_info: Optional[_SysExcInfoType] + exc_text: Optional[str] + filename: str + funcName: str + levelname: str + levelno: int + lineno: int + module: str + msecs: int + message: str + msg: str + name: str + pathname: str + process: int + processName: str + relativeCreated: int + thread: int + threadName: str + def __init__( + self, + name: str, + level: int, + pathname: str, + lineno: int, + msg: Any, + args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ..., + ) -> None: ... + def getMessage(self) -> str: ... + +class LoggerAdapter: + logger: Logger + extra: Mapping[str, Any] + def __init__(self, logger: Logger, extra: Mapping[str, Any]) -> None: ... + def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> Tuple[Any, MutableMapping[str, Any]]: ... + def debug( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def info( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def warning( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def error( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def exception( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def critical( + self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any + ) -> None: ... + def log( + self, + level: int, + msg: Any, + *args: Any, + exc_info: _ExcInfoType = ..., + extra: Optional[Dict[str, Any]] = ..., + **kwargs: Any, + ) -> None: ... + def isEnabledFor(self, level: int) -> bool: ... + +@overload +def getLogger() -> Logger: ... +@overload +def getLogger(name: Union[Text, str]) -> Logger: ... +def getLoggerClass() -> type: ... +def debug(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... +def info(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... +def warning(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... + +warn = warning + +def error(msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any) -> None: ... +def critical( + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any +) -> None: ... +def exception( + msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any +) -> None: ... +def log( + level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any +) -> None: ... + +fatal = critical + +def disable(level: int) -> None: ... +def addLevelName(level: int, levelName: str) -> None: ... +def getLevelName(level: Union[int, str]) -> Any: ... +def makeLogRecord(dict: Mapping[str, Any]) -> LogRecord: ... +@overload +def basicConfig() -> None: ... +@overload +def basicConfig( + *, + filename: Optional[str] = ..., + filemode: str = ..., + format: str = ..., + datefmt: Optional[str] = ..., + level: Optional[_Level] = ..., + stream: IO[str] = ..., +) -> None: ... +def shutdown(handlerList: Sequence[Any] = ...) -> None: ... # handlerList is undocumented +def setLoggerClass(klass: type) -> None: ... +def captureWarnings(capture: bool) -> None: ... + +class StreamHandler(Handler): + stream: IO[str] # undocumented + def __init__(self, stream: Optional[IO[str]] = ...) -> None: ... + +class FileHandler(StreamHandler): + baseFilename: str # undocumented + mode: str # undocumented + encoding: Optional[str] # undocumented + delay: bool # undocumented + def __init__(self, filename: StrPath, mode: str = ..., encoding: Optional[str] = ..., delay: bool = ...) -> None: ... + def _open(self) -> IO[Any]: ... + +class NullHandler(Handler): ... + +class PlaceHolder: + def __init__(self, alogger: Logger) -> None: ... + def append(self, alogger: Logger) -> None: ... + +# Below aren't in module docs but still visible + +class RootLogger(Logger): + def __init__(self, level: int) -> None: ... + +root: RootLogger + +BASIC_FORMAT: str diff --git a/mypy/typeshed/stdlib/@python2/logging/config.pyi b/mypy/typeshed/stdlib/@python2/logging/config.pyi new file mode 100644 index 000000000000..695001221d79 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/logging/config.pyi @@ -0,0 +1,14 @@ +from _typeshed import AnyPath, StrPath +from threading import Thread +from typing import IO, Any, Callable, Dict, Optional, Union + +from ConfigParser import RawConfigParser + +_Path = StrPath + +def dictConfig(config: Dict[str, Any]) -> None: ... +def fileConfig( + fname: Union[str, IO[str]], defaults: Optional[Dict[str, str]] = ..., 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 new file mode 100644 index 000000000000..9403409fce87 --- /dev/null +++ b/mypy/typeshed/stdlib/@python2/logging/handlers.pyi @@ -0,0 +1,133 @@ +import datetime +import ssl +from _typeshed import StrPath +from logging import FileHandler, Handler, LogRecord +from Queue import Queue +from socket import SocketKind, SocketType +from typing import Any, Callable, ClassVar, Dict, List, Optional, Tuple, Union + +DEFAULT_TCP_LOGGING_PORT: int +DEFAULT_UDP_LOGGING_PORT: int +DEFAULT_HTTP_LOGGING_PORT: int +DEFAULT_SOAP_LOGGING_PORT: int +SYSLOG_UDP_PORT: int +SYSLOG_TCP_PORT: int + +class WatchedFileHandler(FileHandler): + dev: int + ino: int + def __init__(self, filename: StrPath, mode: str = ..., encoding: Optional[str] = ..., delay: bool = ...) -> None: ... + def _statstream(self) -> None: ... + +class RotatingFileHandler(Handler): + def __init__( + self, + filename: str, + mode: str = ..., + maxBytes: int = ..., + backupCount: int = ..., + encoding: Optional[str] = ..., + delay: bool = ..., + ) -> None: ... + def doRollover(self) -> None: ... + +class TimedRotatingFileHandler(Handler): + def __init__( + self, + filename: str, + when: str = ..., + interval: int = ..., + backupCount: int = ..., + encoding: Optional[str] = ..., + delay: bool = ..., + utc: bool = ..., + ) -> None: ... + def doRollover(self) -> None: ... + +class SocketHandler(Handler): + retryStart: float + retryFactor: float + retryMax: float + def __init__(self, host: str, port: int) -> None: ... + def makeSocket(self, timeout: float = ...) -> SocketType: ... # timeout is undocumented + def makePickle(self, record: LogRecord) -> bytes: ... + def send(self, s: bytes) -> None: ... + def createSocket(self) -> None: ... + +class DatagramHandler(SocketHandler): + def makeSocket(self) -> SocketType: ... # type: ignore + +class SysLogHandler(Handler): + LOG_EMERG: int + LOG_ALERT: int + LOG_CRIT: int + LOG_ERR: int + LOG_WARNING: int + LOG_NOTICE: int + LOG_INFO: int + LOG_DEBUG: int + + LOG_KERN: int + LOG_USER: int + LOG_MAIL: int + LOG_DAEMON: int + LOG_AUTH: int + LOG_SYSLOG: int + LOG_LPR: int + LOG_NEWS: int + LOG_UUCP: int + LOG_CRON: int + LOG_AUTHPRIV: int + LOG_FTP: 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 + 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: Union[Tuple[str, int], str] = ..., facility: int = ..., socktype: Optional[SocketKind] = ... + ) -> None: ... + def encodePriority(self, facility: Union[int, str], priority: Union[int, str]) -> int: ... + def mapPriority(self, levelName: str) -> str: ... + +class NTEventLogHandler(Handler): + def __init__(self, appname: str, dllname: Optional[str] = ..., logtype: str = ...) -> None: ... + def getEventCategory(self, record: LogRecord) -> int: ... + # TODO correct return value? + def getEventType(self, record: LogRecord) -> int: ... + def getMessageID(self, record: LogRecord) -> int: ... + +class SMTPHandler(Handler): + # TODO `secure` can also be an empty tuple + def __init__( + self, + mailhost: Union[str, Tuple[str, int]], + fromaddr: str, + toaddrs: List[str], + subject: str, + credentials: Optional[Tuple[str, str]] = ..., + secure: Union[Tuple[str], Tuple[str, str], None] = ..., + ) -> None: ... + def getSubject(self, record: LogRecord) -> str: ... + +class BufferingHandler(Handler): + buffer: List[LogRecord] + def __init__(self, capacity: int) -> None: ... + def shouldFlush(self, record: LogRecord) -> bool: ... + +class MemoryHandler(BufferingHandler): + def __init__(self, capacity: int, flushLevel: int = ..., target: Optional[Handler] = ...) -> None: ... + def setTarget(self, target: Handler) -> None: ... + +class HTTPHandler(Handler): + def __init__(self, host: str, url: str, method: str = ...) -> None: ... + def mapLogRecord(self, record: LogRecord) -> Dict[str, Any]: ... diff --git a/mypy/typeshed/stdlib/@python2/platform.pyi b/mypy/typeshed/stdlib/@python2/platform.pyi index cccb024d4278..44bbe4d62aa9 100644 --- a/mypy/typeshed/stdlib/@python2/platform.pyi +++ b/mypy/typeshed/stdlib/@python2/platform.pyi @@ -19,9 +19,13 @@ class _popen: __del__: Any def popen(cmd, mode=..., bufsize: Optional[Any] = ...): ... -def win32_ver(release=..., version=..., csd=..., ptype=...): ... -def mac_ver(release=..., versioninfo=..., machine=...): ... -def java_ver(release=..., vendor=..., vminfo=..., osinfo=...): ... +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]: ... +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]]: ... def system_alias(system, release, version): ... def architecture(executable=..., bits=..., linkage=...) -> Tuple[str, str]: ... def uname() -> Tuple[str, str, str, str, str, str]: ... diff --git a/mypy/typeshed/stdlib/VERSIONS b/mypy/typeshed/stdlib/VERSIONS index c3a08455b5f6..872219720ffc 100644 --- a/mypy/typeshed/stdlib/VERSIONS +++ b/mypy/typeshed/stdlib/VERSIONS @@ -3,6 +3,7 @@ _ast: 3.6 _bisect: 2.7 _bootlocale: 3.6 _codecs: 2.7 +_collections_abc: 3.6 _compat_pickle: 3.6 _compression: 3.6 _csv: 2.7 @@ -53,7 +54,7 @@ builtins: 3.6 bz2: 2.7 cProfile: 2.7 calendar: 2.7 -cgi: 2.7 +cgi: 3.6 cgitb: 2.7 chunk: 2.7 cmath: 2.7 @@ -124,7 +125,7 @@ keyword: 2.7 lib2to3: 2.7 linecache: 2.7 locale: 2.7 -logging: 2.7 +logging: 3.6 lzma: 3.6 macpath: 2.7 macurl2path: 3.6 @@ -232,6 +233,7 @@ tty: 2.7 turtle: 2.7 types: 3.6 typing: 3.6 +typing_extensions: 2.7 unicodedata: 2.7 unittest: 3.6 urllib: 3.6 diff --git a/mypy/typeshed/stdlib/__future__.pyi b/mypy/typeshed/stdlib/__future__.pyi index 0483e736f06b..8a5035271eec 100644 --- a/mypy/typeshed/stdlib/__future__.pyi +++ b/mypy/typeshed/stdlib/__future__.pyi @@ -2,6 +2,7 @@ import sys from typing import List class _Feature: + def __init__(self, optionalRelease: sys._version_info, mandatoryRelease: sys._version_info, compiler_flag: int) -> None: ... def getOptionalRelease(self) -> sys._version_info: ... def getMandatoryRelease(self) -> sys._version_info: ... compiler_flag: int diff --git a/mypy/typeshed/stdlib/_codecs.pyi b/mypy/typeshed/stdlib/_codecs.pyi index 2316cdbbc756..fbb014aadbfb 100644 --- a/mypy/typeshed/stdlib/_codecs.pyi +++ b/mypy/typeshed/stdlib/_codecs.pyi @@ -6,12 +6,12 @@ from typing import Any, Callable, Dict, Optional, Text, Tuple, Union _Handler = Callable[[Exception], Tuple[Text, int]] _String = Union[bytes, str] _Errors = Union[str, Text, None] -if sys.version_info < (3, 0): - _Decodable = Union[bytes, Text] - _Encodable = Union[bytes, Text] -else: +if sys.version_info >= (3, 0): _Decodable = bytes _Encodable = str +else: + _Decodable = Union[bytes, Text] + _Encodable = Union[bytes, Text] # This type is not exposed; it is defined in unicodeobject.c class _EncodingMap(object): diff --git a/mypy/typeshed/stdlib/_collections_abc.pyi b/mypy/typeshed/stdlib/_collections_abc.pyi new file mode 100644 index 000000000000..357c1f91a735 --- /dev/null +++ b/mypy/typeshed/stdlib/_collections_abc.pyi @@ -0,0 +1,56 @@ +from typing import ( + AbstractSet as Set, + AsyncGenerator as AsyncGenerator, + AsyncIterable as AsyncIterable, + AsyncIterator as AsyncIterator, + Awaitable as Awaitable, + ByteString as ByteString, + Callable as Callable, + Collection as Collection, + Container as Container, + Coroutine as Coroutine, + Generator as Generator, + Hashable as Hashable, + ItemsView as ItemsView, + Iterable as Iterable, + Iterator as Iterator, + KeysView as KeysView, + Mapping as Mapping, + MappingView as MappingView, + MutableMapping as MutableMapping, + MutableSequence as MutableSequence, + MutableSet as MutableSet, + Reversible as Reversible, + Sequence as Sequence, + Sized as Sized, + ValuesView as ValuesView, +) + +# Without the real definition, mypy and pytest both think that __all__ is empty, so re-exports nothing +__all__ = [ + "Awaitable", + "Coroutine", + "AsyncIterable", + "AsyncIterator", + "AsyncGenerator", + "Hashable", + "Iterable", + "Iterator", + "Generator", + "Reversible", + "Sized", + "Container", + "Callable", + "Collection", + "Set", + "MutableSet", + "Mapping", + "MutableMapping", + "MappingView", + "KeysView", + "ItemsView", + "ValuesView", + "Sequence", + "MutableSequence", + "ByteString", +] diff --git a/mypy/typeshed/stdlib/_compression.pyi b/mypy/typeshed/stdlib/_compression.pyi index ac44d6d6505d..6cbf5e9ffdff 100644 --- a/mypy/typeshed/stdlib/_compression.pyi +++ b/mypy/typeshed/stdlib/_compression.pyi @@ -1,15 +1,20 @@ from _typeshed import WriteableBuffer from io import BufferedIOBase, RawIOBase -from typing import Any, Callable, Tuple, Type, Union +from typing import Any, Callable, Protocol, Tuple, Type, Union BUFFER_SIZE: Any +class _Reader(Protocol): + def read(self, __n: int) -> bytes: ... + def seekable(self) -> bool: ... + def seek(self, __n: int) -> Any: ... + class BaseStream(BufferedIOBase): ... class DecompressReader(RawIOBase): def __init__( self, - fp: RawIOBase, + fp: _Reader, decomp_factory: Callable[..., object], trailing_error: Union[Type[Exception], Tuple[Type[Exception], ...]] = ..., **decomp_args: Any, diff --git a/mypy/typeshed/stdlib/_curses.pyi b/mypy/typeshed/stdlib/_curses.pyi index 5e447a249bf8..cf11bb40d2ee 100644 --- a/mypy/typeshed/stdlib/_curses.pyi +++ b/mypy/typeshed/stdlib/_curses.pyi @@ -3,6 +3,50 @@ from typing import IO, Any, BinaryIO, NamedTuple, Optional, Tuple, Union, overlo _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 @@ -223,7 +267,14 @@ 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_pair(__color_number: 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: ... @@ -488,3 +539,4 @@ if sys.version_info >= (3, 8): minor: int patch: int ncurses_version: _ncurses_version + window = _CursesWindow # undocumented diff --git a/mypy/typeshed/stdlib/_dummy_threading.pyi b/mypy/typeshed/stdlib/_dummy_threading.pyi index 625ec7b5c4f6..af0b0af89d9b 100644 --- a/mypy/typeshed/stdlib/_dummy_threading.pyi +++ b/mypy/typeshed/stdlib/_dummy_threading.pyi @@ -54,7 +54,7 @@ class Thread: target: Optional[Callable[..., Any]] = ..., name: Optional[str] = ..., args: Iterable[Any] = ..., - kwargs: Mapping[str, Any] = ..., + kwargs: Optional[Mapping[str, Any]] = ..., *, daemon: Optional[bool] = ..., ) -> None: ... @@ -65,7 +65,7 @@ class Thread: target: Optional[Callable[..., Any]] = ..., name: Optional[Text] = ..., args: Iterable[Any] = ..., - kwargs: Mapping[Text, Any] = ..., + kwargs: Optional[Mapping[Text, Any]] = ..., ) -> None: ... def start(self) -> None: ... def run(self) -> None: ... @@ -130,14 +130,15 @@ class Condition: class Semaphore: def __init__(self, value: int = ...) -> None: ... - def __enter__(self) -> bool: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... if sys.version_info >= (3,): - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + def acquire(self, blocking: bool = ..., timeout: Optional[float] = ...) -> bool: ... + def __enter__(self, blocking: bool = ..., timeout: Optional[float] = ...) -> bool: ... else: def acquire(self, blocking: bool = ...) -> bool: ... + def __enter__(self, blocking: bool = ...) -> bool: ... if sys.version_info >= (3, 9): def release(self, n: int = ...) -> None: ... else: diff --git a/mypy/typeshed/stdlib/_heapq.pyi b/mypy/typeshed/stdlib/_heapq.pyi index 673c03e80047..5b14a9de773d 100644 --- a/mypy/typeshed/stdlib/_heapq.pyi +++ b/mypy/typeshed/stdlib/_heapq.pyi @@ -3,7 +3,7 @@ from typing import Any, Callable, Iterable, List, Optional, TypeVar _T = TypeVar("_T") -def heapify(__heap: List[_T]) -> None: ... +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: ... diff --git a/mypy/typeshed/stdlib/_tkinter.pyi b/mypy/typeshed/stdlib/_tkinter.pyi index bc42dbf86937..378b04202c4f 100644 --- a/mypy/typeshed/stdlib/_tkinter.pyi +++ b/mypy/typeshed/stdlib/_tkinter.pyi @@ -1,4 +1,5 @@ -from typing import Any, Tuple, Union +from typing import Any +from typing_extensions import Literal # _tkinter is meant to be only used internally by tkinter, but some tkinter # functions e.g. return _tkinter.Tcl_Obj objects. Tcl_Obj represents a Tcl @@ -38,7 +39,7 @@ class TclError(Exception): ... # Tkapp_UnicodeResult, and it returns a string when it succeeds. class TkappType: # Please keep in sync with tkinter.Tk - def call(self, __command: Union[str, Tuple[Any, ...]], *args: Any) -> Any: ... + def call(self, __command: Any, *args: Any) -> Any: ... def eval(self, __script: str) -> str: ... adderrorinfo: Any createcommand: Any @@ -71,16 +72,17 @@ class TkappType: wantobjects: Any willdispatch: Any -ALL_EVENTS: int -FILE_EVENTS: int -IDLE_EVENTS: int -TIMER_EVENTS: int -WINDOW_EVENTS: int +# These should be kept in sync with tkinter.tix constants, except ALL_EVENTS which doesn't match TCL_ALL_EVENTS +ALL_EVENTS: Literal[-3] +FILE_EVENTS: Literal[8] +IDLE_EVENTS: Literal[32] +TIMER_EVENTS: Literal[16] +WINDOW_EVENTS: Literal[4] -DONT_WAIT: int -EXCEPTION: int -READABLE: int -WRITABLE: int +DONT_WAIT: Literal[2] +EXCEPTION: Literal[8] +READABLE: Literal[2] +WRITABLE: Literal[4] TCL_VERSION: str TK_VERSION: str diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index 8160286c7ab2..039c948fb055 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -31,6 +31,12 @@ class SupportsLessThan(Protocol): SupportsLessThanT = TypeVar("SupportsLessThanT", bound=SupportsLessThan) # noqa: Y001 +class SupportsDivMod(Protocol[_T_contra, _T_co]): + def __divmod__(self, __other: _T_contra) -> _T_co: ... + +class SupportsRDivMod(Protocol[_T_contra, _T_co]): + def __rdivmod__(self, __other: _T_contra) -> _T_co: ... + # Mapping-like protocols class SupportsItems(Protocol[_KT_co, _VT_co]): @@ -64,61 +70,53 @@ else: BytesPath = bytes AnyPath = Union[Text, bytes] -OpenTextMode = Literal[ - "r", +OpenTextModeUpdating = Literal[ "r+", "+r", - "rt", - "tr", "rt+", "r+t", "+rt", "tr+", "t+r", "+tr", - "w", "w+", "+w", - "wt", - "tw", "wt+", "w+t", "+wt", "tw+", "t+w", "+tw", - "a", "a+", "+a", - "at", - "ta", "at+", "a+t", "+at", "ta+", "t+a", "+ta", - "x", "x+", "+x", - "xt", - "tx", "xt+", "x+t", "+xt", "tx+", "t+x", "+tx", - "U", - "rU", - "Ur", - "rtU", - "rUt", - "Urt", - "trU", - "tUr", - "Utr", ] +OpenTextModeWriting = Literal[ + "w", + "wt", + "tw", + "a", + "at", + "ta", + "x", + "xt", + "tx", +] +OpenTextModeReading = Literal["r", "rt", "tr", "U", "rU", "Ur", "rtU", "rUt", "Urt", "trU", "tUr", "Utr"] +OpenTextMode = Union[OpenTextModeUpdating, OpenTextModeWriting, OpenTextModeReading] OpenBinaryModeUpdating = Literal[ "rb+", "r+b", @@ -168,11 +166,11 @@ class SupportsWrite(Protocol[_T_contra]): def write(self, __s: _T_contra) -> Any: ... if sys.version_info >= (3,): - ReadableBuffer = Union[bytes, bytearray, memoryview, array.array, mmap.mmap] - WriteableBuffer = Union[bytearray, memoryview, array.array, mmap.mmap] + ReadableBuffer = Union[bytes, bytearray, memoryview, array.array[Any], mmap.mmap] + WriteableBuffer = Union[bytearray, memoryview, array.array[Any], mmap.mmap] else: - ReadableBuffer = Union[bytes, bytearray, memoryview, array.array, mmap.mmap, buffer] - WriteableBuffer = Union[bytearray, memoryview, array.array, mmap.mmap, buffer] + ReadableBuffer = Union[bytes, bytearray, memoryview, array.array[Any], mmap.mmap, buffer] + WriteableBuffer = Union[bytearray, memoryview, array.array[Any], mmap.mmap, buffer] if sys.version_info >= (3, 10): from types import NoneType as NoneType diff --git a/mypy/typeshed/stdlib/_typeshed/tkinter.pyi b/mypy/typeshed/stdlib/_typeshed/tkinter.pyi new file mode 100644 index 000000000000..565635adbb74 --- /dev/null +++ b/mypy/typeshed/stdlib/_typeshed/tkinter.pyi @@ -0,0 +1,7 @@ +import sys +from typing import Optional, Protocol + +if sys.version_info >= (3,): + from tkinter import Event, Misc, Widget + class DndSource(Protocol): + def dnd_end(self, target: Optional[Widget], event: Optional[Event[Misc]]) -> None: ... diff --git a/mypy/typeshed/stdlib/_weakref.pyi b/mypy/typeshed/stdlib/_weakref.pyi index 5b4870229e66..115a591ce4c8 100644 --- a/mypy/typeshed/stdlib/_weakref.pyi +++ b/mypy/typeshed/stdlib/_weakref.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, Callable, Generic, Optional, TypeVar, overload +from typing import Any, Callable, Generic, List, Optional, TypeVar, overload if sys.version_info >= (3, 9): from types import GenericAlias @@ -7,10 +7,10 @@ if sys.version_info >= (3, 9): _C = TypeVar("_C", bound=Callable[..., Any]) _T = TypeVar("_T") -class CallableProxyType(object): # "weakcallableproxy" +class CallableProxyType(Generic[_C]): # "weakcallableproxy" def __getattr__(self, attr: str) -> Any: ... -class ProxyType(object): # "weakproxy" +class ProxyType(Generic[_T]): # "weakproxy" def __getattr__(self, attr: str) -> Any: ... class ReferenceType(Generic[_T]): @@ -25,9 +25,9 @@ class ReferenceType(Generic[_T]): ref = ReferenceType def getweakrefcount(__object: Any) -> int: ... -def getweakrefs(object: Any) -> int: ... +def getweakrefs(object: Any) -> List[Any]: ... @overload -def proxy(object: _C, callback: Optional[Callable[[_C], Any]] = ...) -> CallableProxyType: ... +def proxy(object: _C, callback: Optional[Callable[[_C], Any]] = ...) -> CallableProxyType[_C]: ... # Return CallableProxyType if object is callable, ProxyType otherwise @overload diff --git a/mypy/typeshed/stdlib/_weakrefset.pyi b/mypy/typeshed/stdlib/_weakrefset.pyi index 6f84124643af..c369584aa243 100644 --- a/mypy/typeshed/stdlib/_weakrefset.pyi +++ b/mypy/typeshed/stdlib/_weakrefset.pyi @@ -23,7 +23,7 @@ class WeakSet(MutableSet[_T], Generic[_T]): def __ior__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... def difference(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... def __sub__(self: _SelfT, other: Iterable[_T]) -> _SelfT: ... - def difference_update(self: _SelfT, other: Iterable[_T]) -> None: ... + 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: ... @@ -38,7 +38,7 @@ class WeakSet(MutableSet[_T], Generic[_T]): def __eq__(self, other: object) -> bool: ... def symmetric_difference(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... def __xor__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... - def symmetric_difference_update(self, other: Iterable[_S]) -> None: ... + def symmetric_difference_update(self, other: Iterable[Any]) -> None: ... def __ixor__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... def union(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... def __or__(self, other: Iterable[_S]) -> WeakSet[Union[_S, _T]]: ... diff --git a/mypy/typeshed/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi index 33c0f87d8da2..cdc98e69195d 100644 --- a/mypy/typeshed/stdlib/asyncio/base_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_events.pyi @@ -21,7 +21,23 @@ _ProtocolFactory = Callable[[], BaseProtocol] _SSLContext = Union[bool, None, ssl.SSLContext] _TransProtPair = Tuple[BaseTransport, BaseProtocol] -class Server(AbstractServer): ... +class Server(AbstractServer): + if sys.version_info >= (3, 7): + def __init__( + self, + loop: AbstractEventLoop, + sockets: List[socket], + protocol_factory: _ProtocolFactory, + ssl_context: _SSLContext, + backlog: int, + ssl_handshake_timeout: Optional[float], + ) -> None: ... + else: + def __init__( + self, + loop: AbstractEventLoop, + sockets: List[socket], + ) -> None: ... class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): def run_forever(self) -> None: ... @@ -184,7 +200,7 @@ class BaseEventLoop(AbstractEventLoop, metaclass=ABCMeta): ) -> _TransProtPair: ... if sys.version_info >= (3, 7): async def sock_sendfile( - self, sock: socket, file: IO[bytes], offset: int = ..., count: Optional[int] = ..., *, fallback: bool = ... + self, sock: socket, file: IO[bytes], offset: int = ..., count: Optional[int] = ..., *, fallback: Optional[bool] = ... ) -> int: ... @overload async def create_server( diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index 8cda63a5caec..521c69f32e12 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -242,7 +242,7 @@ class AbstractEventLoop(metaclass=ABCMeta): if sys.version_info >= (3, 7): @abstractmethod async def sock_sendfile( - self, sock: socket, file: IO[bytes], offset: int = ..., count: Optional[int] = ..., *, fallback: bool = ... + self, sock: socket, file: IO[bytes], offset: int = ..., count: Optional[int] = ..., *, fallback: Optional[bool] = ... ) -> int: ... @overload @abstractmethod diff --git a/mypy/typeshed/stdlib/asyncio/format_helpers.pyi b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi index 5f2baf7b6c59..5c075a910931 100644 --- a/mypy/typeshed/stdlib/asyncio/format_helpers.pyi +++ b/mypy/typeshed/stdlib/asyncio/format_helpers.pyi @@ -7,7 +7,7 @@ from typing import Any, Dict, Iterable, Optional, Tuple, Union, overload class _HasWrapper: __wrapper__: Union[_HasWrapper, FunctionType] -_FuncType = Union[FunctionType, _HasWrapper, functools.partial, functools.partialmethod] +_FuncType = Union[FunctionType, _HasWrapper, functools.partial[Any], functools.partialmethod[Any]] if sys.version_info >= (3, 7): @overload diff --git a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi index e3ebeb502f3c..b4598cec8ef8 100644 --- a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi @@ -1,9 +1,16 @@ +import sys from socket import socket -from typing import Any, Mapping, Optional -from typing_extensions import Literal +from typing import Any, Mapping, Optional, Type +from typing_extensions import Literal, Protocol from . import base_events, constants, events, futures, streams, transports +if sys.version_info >= (3, 8): + class _WarnCallbackProtocol(Protocol): + def __call__( + self, message: str, category: Optional[Type[Warning]] = ..., stacklevel: int = ..., source: Optional[Any] = ... + ) -> None: ... + class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTransport): def __init__( self, @@ -15,7 +22,10 @@ class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTr server: Optional[events.AbstractServer] = ..., ) -> None: ... def __repr__(self) -> str: ... - def __del__(self) -> None: ... + if sys.version_info >= (3, 8): + def __del__(self, _warn: _WarnCallbackProtocol = ...) -> None: ... + else: + def __del__(self) -> None: ... def get_write_buffer_size(self) -> int: ... class _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTransport): diff --git a/mypy/typeshed/stdlib/asyncio/sslproto.pyi b/mypy/typeshed/stdlib/asyncio/sslproto.pyi index 8d1c44aee7e8..a267736ec997 100644 --- a/mypy/typeshed/stdlib/asyncio/sslproto.pyi +++ b/mypy/typeshed/stdlib/asyncio/sslproto.pyi @@ -106,7 +106,7 @@ class SSLProtocol(protocols.Protocol): loop: events.AbstractEventLoop, app_protocol: protocols.BaseProtocol, sslcontext: ssl.SSLContext, - waiter: futures.Future, + waiter: futures.Future[Any], server_side: bool = ..., server_hostname: Optional[str] = ..., call_connection_made: bool = ..., diff --git a/mypy/typeshed/stdlib/asyncio/streams.pyi b/mypy/typeshed/stdlib/asyncio/streams.pyi index 36aafedd7aa3..a6367201052b 100644 --- a/mypy/typeshed/stdlib/asyncio/streams.pyi +++ b/mypy/typeshed/stdlib/asyncio/streams.pyi @@ -53,7 +53,8 @@ if sys.platform != "win32": **kwds: Any, ) -> events.AbstractServer: ... -class FlowControlMixin(protocols.Protocol): ... +class FlowControlMixin(protocols.Protocol): + def __init__(self, loop: Optional[events.AbstractEventLoop] = ...) -> None: ... class StreamReaderProtocol(FlowControlMixin, protocols.Protocol): def __init__( diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index 0c148fa1ad6d..65f61b887734 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -1,22 +1,8 @@ import concurrent.futures import sys +from collections.abc import Awaitable, Generator, Iterable, Iterator from types import FrameType -from typing import ( - Any, - Awaitable, - Generator, - Generic, - Iterable, - Iterator, - List, - Optional, - Set, - TextIO, - Tuple, - TypeVar, - Union, - overload, -) +from typing import Any, Generic, List, Optional, Set, TextIO, Tuple, TypeVar, Union, overload from typing_extensions import Literal from .events import AbstractEventLoop @@ -31,6 +17,7 @@ _T2 = TypeVar("_T2") _T3 = TypeVar("_T3") _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") +_FT = TypeVar("_FT", bound=Future[Any]) _FutureT = Union[Future[_T], Generator[Any, None, _T], Awaitable[_T]] _TaskYieldType = Optional[Future[object]] @@ -41,7 +28,10 @@ ALL_COMPLETED: str def as_completed( fs: Iterable[_FutureT[_T]], *, loop: Optional[AbstractEventLoop] = ..., timeout: Optional[float] = ... ) -> Iterator[Future[_T]]: ... -def ensure_future(coro_or_future: _FutureT[_T], *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... +@overload +def ensure_future(coro_or_future: _FT, *, loop: Optional[AbstractEventLoop] = ...) -> _FT: ... # type: ignore +@overload +def ensure_future(coro_or_future: Awaitable[_T], *, loop: Optional[AbstractEventLoop] = ...) -> Task[_T]: ... # Prior to Python 3.7 'async' was an alias for 'ensure_future'. # It became a keyword in 3.7. @@ -159,9 +149,16 @@ def gather( def run_coroutine_threadsafe(coro: _FutureT[_T], loop: AbstractEventLoop) -> concurrent.futures.Future[_T]: ... def shield(arg: _FutureT[_T], *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... def sleep(delay: float, result: _T = ..., *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... +@overload +def wait(fs: Iterable[_FT], *, loop: Optional[AbstractEventLoop] = ..., timeout: Optional[float] = ..., return_when: str = ...) -> Future[Tuple[Set[_FT], Set[_FT]]]: ... # type: ignore +@overload def wait( - fs: Iterable[_FutureT[_T]], *, loop: Optional[AbstractEventLoop] = ..., timeout: Optional[float] = ..., return_when: str = ... -) -> Future[Tuple[Set[Future[_T]], Set[Future[_T]]]]: ... + fs: Iterable[Awaitable[_T]], + *, + loop: Optional[AbstractEventLoop] = ..., + timeout: Optional[float] = ..., + return_when: str = ..., +) -> Future[Tuple[Set[Task[_T]], Set[Task[_T]]]]: ... def wait_for(fut: _FutureT[_T], timeout: Optional[float], *, loop: Optional[AbstractEventLoop] = ...) -> Future[_T]: ... class Task(Future[_T], Generic[_T]): @@ -182,8 +179,8 @@ class Task(Future[_T], Generic[_T]): def get_coro(self) -> Any: ... def get_name(self) -> str: ... def set_name(self, __value: object) -> None: ... - def get_stack(self, *, limit: int = ...) -> List[FrameType]: ... - def print_stack(self, *, limit: int = ..., file: TextIO = ...) -> None: ... + def get_stack(self, *, limit: Optional[int] = ...) -> List[FrameType]: ... + def print_stack(self, *, limit: Optional[int] = ..., file: Optional[TextIO] = ...) -> None: ... if sys.version_info >= (3, 9): def cancel(self, msg: Optional[str] = ...) -> bool: ... else: diff --git a/mypy/typeshed/stdlib/asyncio/trsock.pyi b/mypy/typeshed/stdlib/asyncio/trsock.pyi index db9efb08b585..0bd3f0adb142 100644 --- a/mypy/typeshed/stdlib/asyncio/trsock.pyi +++ b/mypy/typeshed/stdlib/asyncio/trsock.pyi @@ -5,7 +5,7 @@ from typing import Any, BinaryIO, Iterable, List, NoReturn, Optional, Tuple, Typ if sys.version_info >= (3, 8): # These are based in socket, maybe move them out into _typeshed.pyi or such - _Address = Union[tuple, str] + _Address = Union[Tuple[Any, ...], str] _RetAddress = Any _WriteBuffer = Union[bytearray, memoryview] _CMSG = Tuple[int, int, bytes] diff --git a/mypy/typeshed/stdlib/asyncio/unix_events.pyi b/mypy/typeshed/stdlib/asyncio/unix_events.pyi index 7d3c1b208a35..855fca43469b 100644 --- a/mypy/typeshed/stdlib/asyncio/unix_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/unix_events.pyi @@ -1,8 +1,9 @@ import sys import types +from socket import socket from typing import Any, Callable, Optional, Type, TypeVar -from .events import AbstractEventLoop, BaseDefaultEventLoopPolicy +from .events import AbstractEventLoop, AbstractServer, BaseDefaultEventLoopPolicy, _ProtocolFactory, _SSLContext from .selector_events import BaseSelectorEventLoop _T1 = TypeVar("_T1", bound=AbstractChildWatcher) @@ -30,7 +31,17 @@ class SafeChildWatcher(BaseChildWatcher): class FastChildWatcher(BaseChildWatcher): def __enter__(self: _T3) -> _T3: ... -class _UnixSelectorEventLoop(BaseSelectorEventLoop): ... +class _UnixSelectorEventLoop(BaseSelectorEventLoop): + if sys.version_info < (3, 7): + async def create_unix_server( + self, + protocol_factory: _ProtocolFactory, + path: Optional[str] = ..., + *, + sock: Optional[socket] = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + ) -> AbstractServer: ... class _UnixDefaultEventLoopPolicy(BaseDefaultEventLoopPolicy): def get_child_watcher(self) -> AbstractChildWatcher: ... diff --git a/mypy/typeshed/stdlib/base64.pyi b/mypy/typeshed/stdlib/base64.pyi index 01be704aa71c..01d304dc7678 100644 --- a/mypy/typeshed/stdlib/base64.pyi +++ b/mypy/typeshed/stdlib/base64.pyi @@ -1,12 +1,12 @@ import sys from typing import IO, Optional, Union -if sys.version_info < (3,): - _encodable = Union[bytes, unicode] - _decodable = Union[bytes, unicode] -else: +if sys.version_info >= (3, 0): _encodable = bytes _decodable = Union[bytes, str] +else: + _encodable = Union[bytes, unicode] + _decodable = Union[bytes, unicode] def b64encode(s: _encodable, altchars: Optional[bytes] = ...) -> bytes: ... def b64decode(s: _decodable, altchars: Optional[bytes] = ..., validate: bool = ...) -> bytes: ... diff --git a/mypy/typeshed/stdlib/binascii.pyi b/mypy/typeshed/stdlib/binascii.pyi index d4141b9c4656..db843ad6ca31 100644 --- a/mypy/typeshed/stdlib/binascii.pyi +++ b/mypy/typeshed/stdlib/binascii.pyi @@ -1,15 +1,15 @@ import sys from typing import Text, Union -if sys.version_info < (3,): - # Python 2 accepts unicode ascii pretty much everywhere. - _Bytes = Text - _Ascii = Text -else: +if sys.version_info >= (3, 0): # But since Python 3.3 ASCII-only unicode strings are accepted by the # a2b_* functions. _Bytes = bytes _Ascii = Union[bytes, str] +else: + # Python 2 accepts unicode ascii pretty much everywhere. + _Bytes = Text + _Ascii = Text def a2b_uu(__data: _Ascii) -> bytes: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 939effa782a4..e88d9d8d27ae 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -1,4 +1,5 @@ import sys +import types from _typeshed import ( AnyPath, OpenBinaryMode, @@ -7,9 +8,11 @@ from _typeshed import ( OpenBinaryModeWriting, OpenTextMode, ReadableBuffer, + SupportsDivMod, SupportsKeysAndGetItem, SupportsLessThan, SupportsLessThanT, + SupportsRDivMod, SupportsWrite, ) from ast import AST, mod @@ -69,6 +72,7 @@ class _SupportsTrunc(Protocol): _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) +_T_contra = TypeVar("_T_contra", contravariant=True) _KT = TypeVar("_KT") _VT = TypeVar("_VT") _S = TypeVar("_S") @@ -88,8 +92,9 @@ class object: __annotations__: Dict[str, Any] @property def __class__(self: _T) -> Type[_T]: ... + # Ignore errors about type mismatch between property getter and setter @__class__.setter - def __class__(self, __type: Type[object]) -> None: ... # noqa: F811 + def __class__(self, __type: Type[object]) -> None: ... # type: ignore # noqa: F811 def __init__(self) -> None: ... def __new__(cls) -> Any: ... def __setattr__(self, name: str, value: Any) -> None: ... @@ -152,6 +157,8 @@ class type(object): def __subclasscheck__(self, subclass: type) -> bool: ... @classmethod def __prepare__(metacls, __name: str, __bases: Tuple[type, ...], **kwds: Any) -> Mapping[str, Any]: ... + if sys.version_info >= (3, 10): + def __or__(self, t: Any) -> types.Union: ... class super(object): @overload @@ -328,14 +335,19 @@ class str(Sequence[str]): def capitalize(self) -> str: ... def casefold(self) -> str: ... def center(self, __width: int, __fillchar: str = ...) -> str: ... - def count(self, x: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def count(self, x: str, __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ...) -> int: ... def encode(self, encoding: str = ..., errors: str = ...) -> bytes: ... - def endswith(self, suffix: Union[str, Tuple[str, ...]], start: Optional[int] = ..., end: Optional[int] = ...) -> bool: ... + def endswith( + self, + __suffix: Union[str, Tuple[str, ...]], + __start: Optional[_SupportsIndex] = ..., + __end: Optional[_SupportsIndex] = ..., + ) -> bool: ... def expandtabs(self, tabsize: int = ...) -> str: ... - def find(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def find(self, __sub: str, __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ...) -> int: ... def format(self, *args: object, **kwargs: object) -> str: ... def format_map(self, map: _FormatMapMapping) -> str: ... - def index(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def index(self, __sub: str, __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ...) -> int: ... def isalnum(self) -> bool: ... def isalpha(self) -> bool: ... if sys.version_info >= (3, 7): @@ -358,15 +370,20 @@ class str(Sequence[str]): if sys.version_info >= (3, 9): def removeprefix(self, __prefix: str) -> str: ... def removesuffix(self, __suffix: str) -> str: ... - def rfind(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - def rindex(self, sub: str, __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rfind(self, __sub: str, __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ...) -> int: ... + def rindex(self, __sub: str, __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ...) -> int: ... def rjust(self, __width: int, __fillchar: str = ...) -> str: ... def rpartition(self, __sep: str) -> Tuple[str, str, str]: ... def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... def rstrip(self, __chars: Optional[str] = ...) -> str: ... def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... def splitlines(self, keepends: bool = ...) -> List[str]: ... - def startswith(self, prefix: Union[str, Tuple[str, ...]], start: Optional[int] = ..., end: Optional[int] = ...) -> bool: ... + def startswith( + self, + __prefix: Union[str, Tuple[str, ...]], + __start: Optional[_SupportsIndex] = ..., + __end: Optional[_SupportsIndex] = ..., + ) -> bool: ... def strip(self, __chars: Optional[str] = ...) -> str: ... def swapcase(self) -> str: ... def title(self) -> str: ... @@ -412,16 +429,27 @@ class bytes(ByteString): def __new__(cls: Type[_T], o: SupportsBytes) -> _T: ... def capitalize(self) -> bytes: ... def center(self, __width: int, __fillchar: bytes = ...) -> bytes: ... - def count(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def count( + self, __sub: Union[bytes, int], __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ... + ) -> int: ... def decode(self, encoding: str = ..., errors: str = ...) -> str: ... - def endswith(self, suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def endswith( + self, + __suffix: Union[bytes, Tuple[bytes, ...]], + __start: Optional[_SupportsIndex] = ..., + __end: Optional[_SupportsIndex] = ..., + ) -> bool: ... def expandtabs(self, tabsize: int = ...) -> bytes: ... - def find(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def find( + self, __sub: Union[bytes, int], __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ... + ) -> int: ... if sys.version_info >= (3, 8): def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: int = ...) -> str: ... else: def hex(self) -> str: ... - def index(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def index( + self, __sub: Union[bytes, int], __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ... + ) -> int: ... def isalnum(self) -> bool: ... def isalpha(self) -> bool: ... if sys.version_info >= (3, 7): @@ -440,8 +468,12 @@ class bytes(ByteString): if sys.version_info >= (3, 9): def removeprefix(self, __prefix: bytes) -> bytes: ... def removesuffix(self, __suffix: bytes) -> bytes: ... - def rfind(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... - def rindex(self, sub: Union[bytes, int], start: Optional[int] = ..., end: Optional[int] = ...) -> int: ... + def rfind( + self, __sub: Union[bytes, int], __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ... + ) -> int: ... + def rindex( + self, __sub: Union[bytes, int], __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ... + ) -> int: ... def rjust(self, __width: int, __fillchar: bytes = ...) -> bytes: ... def rpartition(self, __sep: bytes) -> Tuple[bytes, bytes, bytes]: ... def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... @@ -449,7 +481,10 @@ class bytes(ByteString): def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytes]: ... def splitlines(self, keepends: bool = ...) -> List[bytes]: ... def startswith( - self, prefix: Union[bytes, Tuple[bytes, ...]], start: Optional[int] = ..., end: Optional[int] = ... + self, + __prefix: Union[bytes, Tuple[bytes, ...]], + __start: Optional[_SupportsIndex] = ..., + __end: Optional[_SupportsIndex] = ..., ) -> bool: ... def strip(self, __bytes: Optional[bytes] = ...) -> bytes: ... def swapcase(self) -> bytes: ... @@ -459,14 +494,12 @@ class bytes(ByteString): def zfill(self, __width: int) -> bytes: ... @classmethod def fromhex(cls, __s: str) -> bytes: ... - @classmethod - def maketrans(cls, frm: bytes, to: bytes) -> bytes: ... + @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 __int__(self) -> int: ... - def __float__(self) -> float: ... def __hash__(self) -> int: ... @overload def __getitem__(self, i: int) -> int: ... @@ -495,19 +528,32 @@ class bytearray(MutableSequence[int], ByteString): def __init__(self, string: str, encoding: str, errors: str = ...) -> None: ... @overload def __init__(self, length: int) -> None: ... + def append(self, __item: int) -> None: ... def capitalize(self) -> bytearray: ... def center(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... - def count(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def count( + self, __sub: Union[bytes, int], __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ... + ) -> int: ... def copy(self) -> bytearray: ... def decode(self, encoding: str = ..., errors: str = ...) -> str: ... - def endswith(self, __suffix: Union[bytes, Tuple[bytes, ...]]) -> bool: ... + def endswith( + self, + __suffix: Union[bytes, Tuple[bytes, ...]], + __start: Optional[_SupportsIndex] = ..., + __end: Optional[_SupportsIndex] = ..., + ) -> bool: ... def expandtabs(self, tabsize: int = ...) -> bytearray: ... - def find(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def extend(self, __iterable_of_ints: Iterable[int]) -> None: ... + def find( + self, __sub: Union[bytes, int], __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ... + ) -> int: ... if sys.version_info >= (3, 8): def hex(self, sep: Union[str, bytes] = ..., bytes_per_sep: int = ...) -> str: ... else: def hex(self) -> str: ... - def index(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def index( + self, __sub: Union[bytes, int], __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ... + ) -> int: ... def insert(self, __index: int, __item: int) -> None: ... def isalnum(self) -> bool: ... def isalpha(self) -> bool: ... @@ -527,8 +573,12 @@ class bytearray(MutableSequence[int], ByteString): def removeprefix(self, __prefix: bytes) -> bytearray: ... def removesuffix(self, __suffix: bytes) -> bytearray: ... def replace(self, __old: bytes, __new: bytes, __count: int = ...) -> bytearray: ... - def rfind(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... - def rindex(self, __sub: Union[bytes, int], __start: Optional[int] = ..., __end: Optional[int] = ...) -> int: ... + def rfind( + self, __sub: Union[bytes, int], __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ... + ) -> int: ... + def rindex( + self, __sub: Union[bytes, int], __start: Optional[_SupportsIndex] = ..., __end: Optional[_SupportsIndex] = ... + ) -> int: ... def rjust(self, __width: int, __fillchar: bytes = ...) -> bytearray: ... def rpartition(self, __sep: bytes) -> Tuple[bytearray, bytearray, bytearray]: ... def rsplit(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... @@ -536,7 +586,10 @@ class bytearray(MutableSequence[int], ByteString): def split(self, sep: Optional[bytes] = ..., maxsplit: int = ...) -> List[bytearray]: ... def splitlines(self, keepends: bool = ...) -> List[bytearray]: ... def startswith( - self, __prefix: Union[bytes, Tuple[bytes, ...]], __start: Optional[int] = ..., __end: Optional[int] = ... + self, + __prefix: Union[bytes, Tuple[bytes, ...]], + __start: Optional[_SupportsIndex] = ..., + __end: Optional[_SupportsIndex] = ..., ) -> bool: ... def strip(self, __bytes: Optional[bytes] = ...) -> bytearray: ... def swapcase(self) -> bytearray: ... @@ -546,14 +599,12 @@ class bytearray(MutableSequence[int], ByteString): def zfill(self, __width: int) -> bytearray: ... @classmethod def fromhex(cls, __string: str) -> bytearray: ... - @classmethod - def maketrans(cls, __frm: bytes, __to: bytes) -> bytes: ... + @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 __int__(self) -> int: ... - def __float__(self) -> float: ... __hash__: None # type: ignore @overload def __getitem__(self, i: int) -> int: ... @@ -718,14 +769,14 @@ class list(MutableSequence[_T], Generic[_T]): def __str__(self) -> str: ... __hash__: None # type: ignore @overload - def __getitem__(self, i: int) -> _T: ... + def __getitem__(self, i: _SupportsIndex) -> _T: ... @overload def __getitem__(self, s: slice) -> List[_T]: ... @overload - def __setitem__(self, i: int, o: _T) -> None: ... + def __setitem__(self, i: _SupportsIndex, o: _T) -> None: ... @overload def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... - def __delitem__(self, i: Union[int, slice]) -> None: ... + def __delitem__(self, i: Union[_SupportsIndex, slice]) -> None: ... def __add__(self, x: List[_T]) -> List[_T]: ... def __iadd__(self: _S, x: Iterable[_T]) -> _S: ... def __mul__(self, n: int) -> List[_T]: ... @@ -741,10 +792,10 @@ class list(MutableSequence[_T], Generic[_T]): def __class_getitem__(cls, item: Any) -> GenericAlias: ... class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): - # NOTE: Keyword arguments are special. If they are used, _KT must include - # str, but we have no way of enforcing it here. @overload - def __init__(self, **kwargs: _VT) -> None: ... + def __init__(self: Dict[_KT, _VT]) -> None: ... + @overload + def __init__(self: Dict[str, _VT], **kwargs: _VT) -> None: ... @overload def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... @overload @@ -875,6 +926,9 @@ class range(Sequence[int]): def __reversed__(self) -> Iterator[int]: ... class property(object): + fget: Optional[Callable[[Any], Any]] + fset: Optional[Callable[[Any, Any], None]] + fdel: Optional[Callable[[Any], None]] def __init__( self, fget: Optional[Callable[[Any], Any]] = ..., @@ -888,9 +942,6 @@ class property(object): def __get__(self, obj: Any, type: Optional[type] = ...) -> Any: ... def __set__(self, obj: Any, value: Any) -> None: ... def __delete__(self, obj: Any) -> None: ... - def fget(self) -> Any: ... - def fset(self, value: Any) -> None: ... - def fdel(self) -> None: ... class _NotImplementedType(Any): # type: ignore # A little weird, but typing the __call__ as NotImplemented makes the error message @@ -945,10 +996,10 @@ def copyright() -> None: ... def credits() -> None: ... def delattr(__obj: Any, __name: str) -> None: ... def dir(__o: object = ...) -> List[str]: ... - -_N2 = TypeVar("_N2", int, float) - -def divmod(__x: _N2, __y: _N2) -> Tuple[_N2, _N2]: ... +@overload +def divmod(__x: SupportsDivMod[_T_contra, _T_co], __y: _T_contra) -> _T_co: ... +@overload +def divmod(__x: _T_contra, __y: SupportsRDivMod[_T_contra, _T_co]) -> _T_co: ... def eval( __source: Union[str, bytes, CodeType], __globals: Optional[Dict[str, Any]] = ..., __locals: Optional[Mapping[str, Any]] = ... ) -> Any: ... @@ -958,10 +1009,15 @@ def exec( __locals: Optional[Mapping[str, Any]] = ..., ) -> Any: ... def exit(code: object = ...) -> NoReturn: ... -@overload -def filter(__function: None, __iterable: Iterable[Optional[_T]]) -> Iterator[_T]: ... -@overload -def filter(__function: Callable[[_T], Any], __iterable: Iterable[_T]) -> Iterator[_T]: ... + +class filter(Iterator[_T], Generic[_T]): + @overload + def __init__(self, __function: None, __iterable: Iterable[Optional[_T]]) -> None: ... + @overload + def __init__(self, __function: Callable[[_T], Any], __iterable: Iterable[_T]) -> None: ... + def __iter__(self) -> Iterator[_T]: ... + def __next__(self) -> _T: ... + def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode def getattr(__o: Any, name: str, __default: Any = ...) -> Any: ... def globals() -> Dict[str, Any]: ... @@ -982,42 +1038,50 @@ def issubclass(__cls: type, __class_or_tuple: Union[type, Tuple[Union[type, Tupl def len(__obj: Sized) -> int: ... def license() -> None: ... def locals() -> Dict[str, Any]: ... -@overload -def map(__func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> Iterator[_S]: ... -@overload -def map(__func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> Iterator[_S]: ... -@overload -def map( - __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] -) -> Iterator[_S]: ... -@overload -def map( - __func: Callable[[_T1, _T2, _T3, _T4], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], -) -> Iterator[_S]: ... -@overload -def map( - __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], -) -> Iterator[_S]: ... -@overload -def map( - __func: Callable[..., _S], - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any], -) -> Iterator[_S]: ... + +class map(Iterator[_S], Generic[_S]): + @overload + def __init__(self, __func: Callable[[_T1], _S], __iter1: Iterable[_T1]) -> None: ... + @overload + def __init__(self, __func: Callable[[_T1, _T2], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> None: ... + @overload + def __init__( + self, __func: Callable[[_T1, _T2, _T3], _S], __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3] + ) -> None: ... + @overload + def __init__( + self, + __func: Callable[[_T1, _T2, _T3, _T4], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + ) -> None: ... + @overload + def __init__( + self, + __func: Callable[[_T1, _T2, _T3, _T4, _T5], _S], + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5], + ) -> None: ... + @overload + def __init__( + self, + __func: Callable[..., _S], + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any], + ) -> None: ... + def __iter__(self) -> Iterator[_S]: ... + def __next__(self) -> _S: ... + @overload def max( __arg1: SupportsLessThanT, __arg2: SupportsLessThanT, *_args: SupportsLessThanT, key: None = ... @@ -1186,21 +1250,20 @@ else: def pow(__base: _SupportsPow3[_E, _M, _T_co], __exp: _E, __mod: _M) -> _T_co: ... def quit(code: object = ...) -> NoReturn: ... -@overload -def reversed(__sequence: Sequence[_T]) -> Iterator[_T]: ... -@overload -def reversed(__sequence: Reversible[_T]) -> Iterator[_T]: ... + +class reversed(Iterator[_T], Generic[_T]): + @overload + def __init__(self, __sequence: Sequence[_T]) -> None: ... + @overload + def __init__(self, __sequence: Reversible[_T]) -> None: ... + def __iter__(self) -> Iterator[_T]: ... + def __next__(self) -> _T: ... + def repr(__obj: object) -> str: ... @overload -def round(number: float) -> int: ... -@overload -def round(number: float, ndigits: None) -> int: ... -@overload -def round(number: float, ndigits: int) -> float: ... +def round(number: SupportsRound[Any]) -> int: ... @overload -def round(number: SupportsRound[_T]) -> int: ... -@overload -def round(number: SupportsRound[_T], ndigits: None) -> int: ... +def round(number: SupportsRound[Any], ndigits: None) -> int: ... @overload def round(number: SupportsRound[_T], ndigits: int) -> _T: ... def setattr(__obj: Any, __name: str, __value: Any) -> None: ... @@ -1222,30 +1285,41 @@ else: def sum(__iterable: Iterable[_T], __start: _S) -> Union[_T, _S]: ... def vars(__object: Any = ...) -> Dict[str, Any]: ... -@overload -def zip(__iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... -@overload -def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> Iterator[Tuple[_T1, _T2]]: ... -@overload -def zip(__iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> Iterator[Tuple[_T1, _T2, _T3]]: ... -@overload -def zip( - __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] -) -> Iterator[Tuple[_T1, _T2, _T3, _T4]]: ... -@overload -def zip( - __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4], __iter5: Iterable[_T5] -) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... -@overload -def zip( - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - *iterables: Iterable[Any], -) -> Iterator[Tuple[Any, ...]]: ... + +class zip(Iterator[_T_co], Generic[_T_co]): + @overload + def __new__(cls, __iter1: Iterable[_T1]) -> zip[Tuple[_T1]]: ... + @overload + def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> zip[Tuple[_T1, _T2]]: ... + @overload + def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> zip[Tuple[_T1, _T2, _T3]]: ... + @overload + def __new__( + cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] + ) -> zip[Tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def __new__( + cls, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5], + ) -> zip[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def __new__( + cls, + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + *iterables: Iterable[Any], + ) -> zip[Tuple[Any, ...]]: ... + def __iter__(self) -> Iterator[_T_co]: ... + def __next__(self) -> _T_co: ... + def __import__( name: str, globals: Optional[Mapping[str, Any]] = ..., @@ -1290,9 +1364,13 @@ class OSError(Exception): # filename, filename2 are actually Union[str, bytes, None] filename: Any filename2: Any + if sys.platform == "win32": + winerror: int EnvironmentError = OSError IOError = OSError +if sys.platform == "win32": + WindowsError = OSError class ArithmeticError(_StandardError): ... class AssertionError(_StandardError): ... @@ -1304,6 +1382,7 @@ class ImportError(_StandardError): def __init__(self, *args: object, name: Optional[str] = ..., path: Optional[str] = ...) -> None: ... name: Optional[str] path: Optional[str] + msg: str # undocumented class LookupError(_StandardError): ... class MemoryError(_StandardError): ... @@ -1332,9 +1411,6 @@ class IndexError(LookupError): ... class KeyError(LookupError): ... class UnboundLocalError(NameError): ... -class WindowsError(OSError): - winerror: int - class BlockingIOError(OSError): characters_written: int diff --git a/mypy/typeshed/stdlib/bz2.pyi b/mypy/typeshed/stdlib/bz2.pyi index b67d00cc7be1..dfc1876bf43e 100644 --- a/mypy/typeshed/stdlib/bz2.pyi +++ b/mypy/typeshed/stdlib/bz2.pyi @@ -1,8 +1,8 @@ import io import sys -from _typeshed import AnyPath -from typing import IO, Any, Optional, TextIO, TypeVar, Union, overload -from typing_extensions import Literal +from _typeshed import AnyPath, ReadableBuffer, WriteableBuffer +from typing import IO, Any, Iterable, List, Optional, TextIO, TypeVar, Union, overload +from typing_extensions import Literal, SupportsIndex _PathOrFile = Union[AnyPath, IO[bytes]] _T = TypeVar("_T") @@ -49,10 +49,18 @@ class BZ2File(io.BufferedIOBase, IO[bytes]): def __init__( self, filename: _PathOrFile, mode: str = ..., buffering: Optional[Any] = ..., compresslevel: int = ... ) -> None: ... + def read(self, size: Optional[int] = ...) -> 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 seek(self, offset: int, whence: int = ...) -> int: ... + def write(self, data: ReadableBuffer) -> int: ... + def writelines(self, seq: Iterable[ReadableBuffer]) -> None: ... class BZ2Compressor(object): def __init__(self, compresslevel: int = ...) -> None: ... - def compress(self, data: bytes) -> bytes: ... + def compress(self, __data: bytes) -> bytes: ... def flush(self) -> bytes: ... class BZ2Decompressor(object): diff --git a/mypy/typeshed/stdlib/calendar.pyi b/mypy/typeshed/stdlib/calendar.pyi index af2aa83edbdb..0737062de405 100644 --- a/mypy/typeshed/stdlib/calendar.pyi +++ b/mypy/typeshed/stdlib/calendar.pyi @@ -76,14 +76,14 @@ class HTMLCalendar(Calendar): cssclass_year: str cssclass_year_head: str -if sys.version_info < (3, 0): - class TimeEncoding: +if sys.version_info >= (3, 0): + class different_locale: def __init__(self, locale: _LocaleType) -> None: ... def __enter__(self) -> _LocaleType: ... def __exit__(self, *args: Any) -> None: ... else: - class different_locale: + class TimeEncoding: def __init__(self, locale: _LocaleType) -> None: ... def __enter__(self) -> _LocaleType: ... def __exit__(self, *args: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/cgi.pyi b/mypy/typeshed/stdlib/cgi.pyi index c868d6521f3d..da3a4d43c563 100644 --- a/mypy/typeshed/stdlib/cgi.pyi +++ b/mypy/typeshed/stdlib/cgi.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import SupportsGetItem, SupportsItemAccess from builtins import type as _type -from typing import IO, Any, AnyStr, Dict, Iterable, Iterator, List, Mapping, Optional, Protocol, Tuple, TypeVar, Union +from collections.abc import Iterable, Iterator, Mapping +from typing import IO, Any, Optional, Protocol, TypeVar, Union _T = TypeVar("_T", bound=FieldStorage) @@ -10,35 +11,33 @@ def parse( environ: SupportsItemAccess[str, str] = ..., keep_blank_values: bool = ..., strict_parsing: bool = ..., -) -> Dict[str, List[str]]: ... + separator: str = ..., +) -> dict[str, list[str]]: ... if sys.version_info < (3, 8): - 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_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]]: ... if sys.version_info >= (3, 7): def parse_multipart( - fp: IO[Any], pdict: SupportsGetItem[str, bytes], encoding: str = ..., errors: str = ... - ) -> Dict[str, List[Any]]: ... + fp: IO[Any], pdict: SupportsGetItem[str, bytes], encoding: str = ..., errors: str = ..., separator: str = ... + ) -> dict[str, list[Any]]: ... else: - def parse_multipart(fp: IO[Any], pdict: SupportsGetItem[str, bytes]) -> Dict[str, List[bytes]]: ... + def parse_multipart(fp: IO[Any], pdict: SupportsGetItem[str, bytes]) -> dict[str, list[bytes]]: ... class _Environ(Protocol): def __getitem__(self, __k: str) -> str: ... def keys(self) -> Iterable[str]: ... -def parse_header(line: str) -> Tuple[str, Dict[str, str]]: ... +def parse_header(line: str) -> tuple[str, dict[str, str]]: ... def test(environ: _Environ = ...) -> None: ... def print_environ(environ: _Environ = ...) -> None: ... -def print_form(form: Dict[str, Any]) -> None: ... +def print_form(form: dict[str, Any]) -> None: ... def print_directory() -> None: ... def print_environ_usage() -> None: ... -if sys.version_info < (3,): - def escape(s: AnyStr, quote: bool = ...) -> AnyStr: ... - -elif sys.version_info < (3, 8): +if sys.version_info < (3, 8): def escape(s: str, quote: Optional[bool] = ...) -> str: ... class MiniFieldStorage: @@ -47,15 +46,17 @@ class MiniFieldStorage: list: Any type: Any file: Optional[IO[bytes]] - type_options: Dict[Any, Any] + type_options: dict[Any, Any] disposition: Any - disposition_options: Dict[Any, Any] - headers: Dict[Any, Any] + disposition_options: dict[Any, Any] + headers: dict[Any, Any] name: Any value: Any def __init__(self, name: Any, value: Any) -> None: ... def __repr__(self) -> str: ... +_list = list + class FieldStorage(object): FieldStorageClass: Optional[_type] keep_blank_values: int @@ -69,94 +70,41 @@ class FieldStorage(object): bytes_read: int limit: Optional[int] disposition: str - disposition_options: Dict[str, str] + disposition_options: dict[str, str] filename: Optional[str] file: Optional[IO[bytes]] type: str - type_options: Dict[str, str] + type_options: dict[str, str] innerboundary: bytes length: int done: int - list: Optional[List[Any]] - value: Union[None, bytes, List[Any]] - - if sys.version_info >= (3, 6): - def __init__( - self, - fp: Optional[IO[Any]] = ..., - headers: Optional[Mapping[str, str]] = ..., - outerboundary: bytes = ..., - environ: SupportsGetItem[str, str] = ..., - keep_blank_values: int = ..., - strict_parsing: int = ..., - limit: Optional[int] = ..., - encoding: str = ..., - errors: str = ..., - max_num_fields: Optional[int] = ..., - ) -> None: ... - elif sys.version_info >= (3, 0): - def __init__( - self, - fp: Optional[IO[Any]] = ..., - headers: Optional[Mapping[str, str]] = ..., - outerboundary: bytes = ..., - environ: SupportsGetItem[str, str] = ..., - keep_blank_values: int = ..., - strict_parsing: int = ..., - limit: Optional[int] = ..., - encoding: str = ..., - errors: str = ..., - ) -> None: ... - else: - def __init__( - self, - fp: IO[Any] = ..., - headers: Mapping[str, str] = ..., - outerboundary: bytes = ..., - environ: SupportsGetItem[str, str] = ..., - keep_blank_values: int = ..., - strict_parsing: int = ..., - ) -> None: ... - if sys.version_info >= (3, 0): - def __enter__(self: _T) -> _T: ... - def __exit__(self, *args: Any) -> None: ... + list: Optional[_list[Any]] + value: Union[None, bytes, _list[Any]] + def __init__( + self, + fp: Optional[IO[Any]] = ..., + headers: Optional[Mapping[str, str]] = ..., + outerboundary: bytes = ..., + environ: SupportsGetItem[str, str] = ..., + keep_blank_values: int = ..., + strict_parsing: int = ..., + limit: Optional[int] = ..., + encoding: str = ..., + errors: str = ..., + max_num_fields: Optional[int] = ..., + separator: str = ..., + ) -> None: ... + def __enter__(self: _T) -> _T: ... + 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: ... def getfirst(self, key: str, default: Any = ...) -> Any: ... - def getlist(self, key: str) -> List[Any]: ... - def keys(self) -> List[str]: ... - if sys.version_info < (3, 0): - def has_key(self, key: str) -> bool: ... + def getlist(self, key: str) -> _list[Any]: ... + def keys(self) -> _list[str]: ... def __contains__(self, key: str) -> bool: ... def __len__(self) -> int: ... - if sys.version_info >= (3, 0): - def __bool__(self) -> bool: ... - else: - def __nonzero__(self) -> bool: ... - if sys.version_info >= (3, 0): - # In Python 3 it returns bytes or str IO depending on an internal flag - def make_file(self) -> IO[Any]: ... - else: - # In Python 2 it always returns bytes and ignores the "binary" flag - def make_file(self, binary: Any = ...) -> IO[bytes]: ... - -if sys.version_info < (3, 0): - from UserDict import UserDict - class FormContentDict(UserDict[str, List[str]]): - query_string: str - def __init__(self, environ: Mapping[str, str] = ..., keep_blank_values: int = ..., strict_parsing: int = ...) -> None: ... - class SvFormContentDict(FormContentDict): - def getlist(self, key: Any) -> Any: ... - class InterpFormContentDict(SvFormContentDict): ... - class FormContent(FormContentDict): - # TODO this should have - # def values(self, key: Any) -> Any: ... - # but this is incompatible with the supertype, and adding '# type: ignore' triggers - # a parse error in pytype (https://github.com/google/pytype/issues/53) - def indexed_value(self, key: Any, location: int) -> Any: ... - def value(self, key: Any) -> Any: ... - def length(self, key: Any) -> int: ... - def stripped(self, key: Any) -> Any: ... - def pars(self) -> Dict[Any, Any]: ... + def __bool__(self) -> bool: ... + # In Python 3 it returns bytes or str IO depending on an internal flag + def make_file(self) -> IO[Any]: ... diff --git a/mypy/typeshed/stdlib/cmath.pyi b/mypy/typeshed/stdlib/cmath.pyi index bb9e302ed414..eaa62eafcb33 100644 --- a/mypy/typeshed/stdlib/cmath.pyi +++ b/mypy/typeshed/stdlib/cmath.pyi @@ -10,7 +10,7 @@ if sys.version_info >= (3, 6): nanj: complex tau: float -_C = Union[SupportsFloat, SupportsComplex] +_C = Union[SupportsFloat, SupportsComplex, complex] def acos(__z: _C) -> complex: ... def acosh(__z: _C) -> complex: ... diff --git a/mypy/typeshed/stdlib/codecs.pyi b/mypy/typeshed/stdlib/codecs.pyi index 1a596b95a4bb..ad4f74357558 100644 --- a/mypy/typeshed/stdlib/codecs.pyi +++ b/mypy/typeshed/stdlib/codecs.pyi @@ -82,8 +82,10 @@ def decode(obj: str, encoding: Literal["rot13", "rot_13"] = ..., errors: str = . @overload def decode(obj: _Encoded, encoding: str = ..., errors: str = ...) -> _Decoded: ... def lookup(__encoding: str) -> CodecInfo: ... -def utf_16_be_decode(__obj: _Encoded, __errors: str = ..., __final: bool = ...) -> Tuple[_Decoded, int]: ... # undocumented -def utf_16_be_encode(__obj: _Decoded, __errors: str = ...) -> Tuple[_Encoded, int]: ... # undocumented +def utf_16_be_decode( + __data: _Encoded, __errors: Optional[str] = ..., __final: bool = ... +) -> Tuple[_Decoded, int]: ... # undocumented +def utf_16_be_encode(__str: _Decoded, __errors: Optional[str] = ...) -> Tuple[_Encoded, int]: ... # undocumented class CodecInfo(Tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): @property @@ -160,7 +162,7 @@ class IncrementalEncoder: errors: str def __init__(self, errors: str = ...) -> None: ... @abstractmethod - def encode(self, object: _Decoded, final: bool = ...) -> _Encoded: ... + def encode(self, input: _Decoded, final: bool = ...) -> _Encoded: ... def reset(self) -> None: ... # documentation says int but str is needed for the subclass. def getstate(self) -> Union[int, _Decoded]: ... @@ -188,7 +190,7 @@ class BufferedIncrementalDecoder(IncrementalDecoder): def __init__(self, errors: str = ...) -> None: ... @abstractmethod def _buffer_decode(self, input: _Encoded, errors: str, final: bool) -> Tuple[_Decoded, int]: ... - def decode(self, object: _Encoded, final: bool = ...) -> _Decoded: ... + def decode(self, input: _Encoded, final: bool = ...) -> _Decoded: ... _SW = TypeVar("_SW", bound=StreamWriter) @@ -197,14 +199,14 @@ _SW = TypeVar("_SW", bound=StreamWriter) class StreamWriter(Codec): errors: str def __init__(self, stream: IO[_Encoded], errors: str = ...) -> None: ... - def write(self, obj: _Decoded) -> None: ... + 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: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[types.TracebackType] ) -> None: ... - def __getattr__(self, name: str) -> Any: ... + def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... _SR = TypeVar("_SR", bound=StreamReader) @@ -212,15 +214,15 @@ 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 = ..., keepends: bool = ...) -> _Decoded: ... - def readlines(self, sizehint: int = ..., keepends: bool = ...) -> List[_Decoded]: ... + def readline(self, size: Optional[int] = ..., keepends: bool = ...) -> _Decoded: ... + def readlines(self, sizehint: Optional[int] = ..., keepends: bool = ...) -> List[_Decoded]: ... def reset(self) -> None: ... def __enter__(self: _SR) -> _SR: ... def __exit__( self, typ: Optional[Type[BaseException]], exc: Optional[BaseException], tb: Optional[types.TracebackType] ) -> None: ... def __iter__(self) -> Iterator[_Decoded]: ... - def __getattr__(self, name: str) -> Any: ... + def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... _T = TypeVar("_T", bound=StreamReaderWriter) diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index 65f1e0e95b73..76ec87661dc9 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -1,44 +1,22 @@ import sys -import typing -from typing import ( - AbstractSet, - Any, - AsyncGenerator as AsyncGenerator, - AsyncIterable as AsyncIterable, - AsyncIterator as AsyncIterator, - Awaitable as Awaitable, - ByteString as ByteString, - Callable as Callable, - Collection as Collection, - Container as Container, - Coroutine as Coroutine, - Dict, - Generator as Generator, - 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, - MutableSequence as MutableSequence, - MutableSet as MutableSet, - Optional, - Reversible as Reversible, - Sequence as Sequence, - Sized as Sized, - Tuple, - Type, - TypeVar, - Union, - ValuesView as ValuesView, - overload, -) +from typing import Any, Dict, Generic, List, Optional, Tuple, Type, TypeVar, Union, overload -Set = AbstractSet +if sys.version_info >= (3, 10): + from typing import ( + Callable, + ItemsView, + Iterable, + Iterator, + KeysView, + Mapping, + MutableMapping, + MutableSequence, + Reversible, + Sequence, + ValuesView, + ) +else: + from _collections_abc import * _S = TypeVar("_S") _T = TypeVar("_T") @@ -138,10 +116,10 @@ class UserString(Sequence[str]): def center(self: _UserStringT, width: int, *args: Any) -> _UserStringT: ... def count(self, sub: Union[str, UserString], start: int = ..., end: int = ...) -> int: ... if sys.version_info >= (3, 8): - def encode(self: _UserStringT, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> bytes: ... + def encode(self: UserString, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> bytes: ... else: def encode(self: _UserStringT, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> _UserStringT: ... - def endswith(self, suffix: Union[str, Tuple[str, ...]], start: int = ..., end: int = ...) -> bool: ... + def endswith(self, suffix: Union[str, Tuple[str, ...]], start: Optional[int] = ..., end: Optional[int] = ...) -> bool: ... def expandtabs(self: _UserStringT, tabsize: int = ...) -> _UserStringT: ... def find(self, sub: Union[str, UserString], start: int = ..., end: int = ...) -> int: ... def format(self, *args: Any, **kwds: Any) -> str: ... @@ -183,7 +161,7 @@ class UserString(Sequence[str]): def split(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... def rsplit(self, sep: Optional[str] = ..., maxsplit: int = ...) -> List[str]: ... def splitlines(self, keepends: bool = ...) -> List[str]: ... - def startswith(self, prefix: Union[str, Tuple[str, ...]], start: int = ..., end: int = ...) -> bool: ... + def startswith(self, prefix: Union[str, Tuple[str, ...]], start: Optional[int] = ..., end: Optional[int] = ...) -> bool: ... def strip(self: _UserStringT, chars: Optional[str] = ...) -> _UserStringT: ... def swapcase(self: _UserStringT) -> _UserStringT: ... def title(self: _UserStringT) -> _UserStringT: ... @@ -316,9 +294,9 @@ class ChainMap(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def __init__(self, *maps: Mapping[_KT, _VT]) -> None: ... @property def maps(self) -> List[Mapping[_KT, _VT]]: ... - def new_child(self, m: Mapping[_KT, _VT] = ...) -> typing.ChainMap[_KT, _VT]: ... + def new_child(self, m: Mapping[_KT, _VT] = ...) -> ChainMap[_KT, _VT]: ... @property - def parents(self) -> typing.ChainMap[_KT, _VT]: ... + def parents(self) -> ChainMap[_KT, _VT]: ... def __setitem__(self, k: _KT, v: _VT) -> None: ... def __delitem__(self, v: _KT) -> None: ... def __getitem__(self, k: _KT) -> _VT: ... diff --git a/mypy/typeshed/stdlib/collections/abc.pyi b/mypy/typeshed/stdlib/collections/abc.pyi index c9d69978afd2..3df2a1d9eb9b 100644 --- a/mypy/typeshed/stdlib/collections/abc.pyi +++ b/mypy/typeshed/stdlib/collections/abc.pyi @@ -1,27 +1,2 @@ -from . import ( - AsyncGenerator as AsyncGenerator, - AsyncIterable as AsyncIterable, - AsyncIterator as AsyncIterator, - Awaitable as Awaitable, - ByteString as ByteString, - Callable as Callable, - Collection as Collection, - Container as Container, - Coroutine as Coroutine, - Generator as Generator, - Hashable as Hashable, - ItemsView as ItemsView, - Iterable as Iterable, - Iterator as Iterator, - KeysView as KeysView, - Mapping as Mapping, - MappingView as MappingView, - MutableMapping as MutableMapping, - MutableSequence as MutableSequence, - MutableSet as MutableSet, - Reversible as Reversible, - Sequence as Sequence, - Set as Set, - Sized as Sized, - ValuesView as ValuesView, -) +from _collections_abc import * +from _collections_abc import __all__ as __all__ diff --git a/mypy/typeshed/stdlib/compileall.pyi b/mypy/typeshed/stdlib/compileall.pyi index bcc2a8e8275d..529568275c8c 100644 --- a/mypy/typeshed/stdlib/compileall.pyi +++ b/mypy/typeshed/stdlib/compileall.pyi @@ -1,51 +1,54 @@ import sys -from _typeshed import AnyPath -from typing import Any, Optional, Pattern +from _typeshed import StrPath +from typing import Any, Optional, Protocol if sys.version_info >= (3, 7): from py_compile import PycInvalidationMode +class _SupportsSearch(Protocol): + def search(self, string: str) -> Any: ... + if sys.version_info >= (3, 9): def compile_dir( - dir: AnyPath, + dir: StrPath, maxlevels: Optional[int] = ..., - ddir: Optional[AnyPath] = ..., + ddir: Optional[StrPath] = ..., force: bool = ..., - rx: Optional[Pattern[Any]] = ..., + rx: Optional[_SupportsSearch] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ..., workers: int = ..., invalidation_mode: Optional[PycInvalidationMode] = ..., *, - stripdir: Optional[str] = ..., # TODO: change to Optional[AnyPath] once https://bugs.python.org/issue40447 is resolved - prependdir: Optional[AnyPath] = ..., - limit_sl_dest: Optional[AnyPath] = ..., + stripdir: Optional[str] = ..., # TODO: change to Optional[StrPath] once https://bugs.python.org/issue40447 is resolved + prependdir: Optional[StrPath] = ..., + limit_sl_dest: Optional[StrPath] = ..., hardlink_dupes: bool = ..., ) -> int: ... def compile_file( - fullname: AnyPath, - ddir: Optional[AnyPath] = ..., + fullname: StrPath, + ddir: Optional[StrPath] = ..., force: bool = ..., - rx: Optional[Pattern[Any]] = ..., + rx: Optional[_SupportsSearch] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ..., invalidation_mode: Optional[PycInvalidationMode] = ..., *, - stripdir: Optional[str] = ..., # TODO: change to Optional[AnyPath] once https://bugs.python.org/issue40447 is resolved - prependdir: Optional[AnyPath] = ..., - limit_sl_dest: Optional[AnyPath] = ..., + stripdir: Optional[str] = ..., # TODO: change to Optional[StrPath] once https://bugs.python.org/issue40447 is resolved + prependdir: Optional[StrPath] = ..., + limit_sl_dest: Optional[StrPath] = ..., hardlink_dupes: bool = ..., ) -> int: ... elif sys.version_info >= (3, 7): def compile_dir( - dir: AnyPath, + dir: StrPath, maxlevels: int = ..., - ddir: Optional[AnyPath] = ..., + ddir: Optional[StrPath] = ..., force: bool = ..., - rx: Optional[Pattern[Any]] = ..., + rx: Optional[_SupportsSearch] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ..., @@ -53,10 +56,10 @@ elif sys.version_info >= (3, 7): invalidation_mode: Optional[PycInvalidationMode] = ..., ) -> int: ... def compile_file( - fullname: AnyPath, - ddir: Optional[AnyPath] = ..., + fullname: StrPath, + ddir: Optional[StrPath] = ..., force: bool = ..., - rx: Optional[Pattern[Any]] = ..., + rx: Optional[_SupportsSearch] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ..., @@ -64,23 +67,22 @@ elif sys.version_info >= (3, 7): ) -> int: ... else: - # rx can be any object with a 'search' method; once we have Protocols we can change the type def compile_dir( - dir: AnyPath, + dir: StrPath, maxlevels: int = ..., - ddir: Optional[AnyPath] = ..., + ddir: Optional[StrPath] = ..., force: bool = ..., - rx: Optional[Pattern[Any]] = ..., + rx: Optional[_SupportsSearch] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ..., workers: int = ..., ) -> int: ... def compile_file( - fullname: AnyPath, - ddir: Optional[AnyPath] = ..., + fullname: StrPath, + ddir: Optional[StrPath] = ..., force: bool = ..., - rx: Optional[Pattern[Any]] = ..., + rx: Optional[_SupportsSearch] = ..., quiet: int = ..., legacy: bool = ..., optimize: int = ..., diff --git a/mypy/typeshed/stdlib/configparser.pyi b/mypy/typeshed/stdlib/configparser.pyi index e842e5e6e829..f4a4e889c646 100644 --- a/mypy/typeshed/stdlib/configparser.pyi +++ b/mypy/typeshed/stdlib/configparser.pyi @@ -45,7 +45,9 @@ class Interpolation: class BasicInterpolation(Interpolation): ... class ExtendedInterpolation(Interpolation): ... -class LegacyInterpolation(Interpolation): ... + +class LegacyInterpolation(Interpolation): + def before_get(self, parser: _parser, section: str, option: str, value: str, vars: _section) -> str: ... class RawConfigParser(_parser): _SECT_TMPL: ClassVar[str] = ... # Undocumented @@ -188,7 +190,7 @@ class SectionProxy(MutableMapping[str, str]): def getboolean( self, option: str, fallback: _T = ..., *, raw: bool = ..., vars: Optional[_section] = ... ) -> Union[bool, _T]: ... - # SectionProxy can have arbitrary attributes when custon converters are used + # SectionProxy can have arbitrary attributes when custom converters are used def __getattr__(self, key: str) -> Callable[..., Any]: ... class ConverterMapping(MutableMapping[str, Optional[_converter]]): @@ -219,7 +221,7 @@ class DuplicateOptionError(Error): option: str source: Optional[str] lineno: Optional[int] - def __init__(self, section: str, option: str, source: Optional[str] = ..., lineno: Optional[str] = ...) -> None: ... + def __init__(self, section: str, option: str, source: Optional[str] = ..., lineno: Optional[int] = ...) -> None: ... class NoOptionError(Error): section: str diff --git a/mypy/typeshed/stdlib/ctypes/__init__.pyi b/mypy/typeshed/stdlib/ctypes/__init__.pyi index f06fa7396edf..299672ad0629 100644 --- a/mypy/typeshed/stdlib/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/ctypes/__init__.pyi @@ -36,15 +36,25 @@ class CDLL(object): _name: str = ... _handle: int = ... _FuncPtr: Type[_FuncPointer] = ... - def __init__( - self, - name: Optional[str], - mode: int = ..., - handle: Optional[int] = ..., - use_errno: bool = ..., - use_last_error: bool = ..., - winmode: Optional[int] = ..., - ) -> None: ... + if sys.version_info >= (3, 8): + def __init__( + self, + name: Optional[str], + mode: int = ..., + handle: Optional[int] = ..., + use_errno: bool = ..., + use_last_error: bool = ..., + winmode: Optional[int] = ..., + ) -> None: ... + else: + def __init__( + self, + name: Optional[str], + mode: int = ..., + handle: Optional[int] = ..., + use_errno: bool = ..., + use_last_error: bool = ..., + ) -> None: ... def __getattr__(self, name: str) -> _NamedFuncPointer: ... def __getitem__(self, name: str) -> _NamedFuncPointer: ... @@ -72,7 +82,7 @@ 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 # for it. Instead we have to list the most common stdlib buffer classes in a Union. -_WritableBuffer = _UnionT[bytearray, memoryview, array, _CData] +_WritableBuffer = _UnionT[bytearray, memoryview, array[Any], _CData] # Same as _WritableBuffer, but also includes read-only buffer types (like bytes). _ReadOnlyBuffer = _UnionT[_WritableBuffer, bytes] @@ -105,7 +115,7 @@ _ECT = Callable[[Optional[Type[_CData]], _FuncPointer, Tuple[_CData, ...]], _CDa _PF = _UnionT[Tuple[int], Tuple[int, str], Tuple[int, str, Any]] class _FuncPointer(_PointerLike, _CData): - restype: _UnionT[Type[_CData], Callable[[int], None], None] = ... + restype: _UnionT[Type[_CData], Callable[[int], Any], None] = ... argtypes: Sequence[Type[_CData]] = ... errcheck: _ECT = ... @overload @@ -151,7 +161,7 @@ def byref(obj: _CData, offset: int = ...) -> _CArgObject: ... _CastT = TypeVar("_CastT", bound=_CanCastTo) -def cast(obj: _UnionT[_CData, _CArgObject, int], type: Type[_CastT]) -> _CastT: ... +def cast(obj: _UnionT[_CData, _CArgObject, int], typ: Type[_CastT]) -> _CastT: ... def create_string_buffer(init: _UnionT[int, bytes], size: Optional[int] = ...) -> Array[c_char]: ... c_buffer = create_string_buffer diff --git a/mypy/typeshed/stdlib/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index 678e6bcb85a1..3fa15d9bd388 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -18,7 +18,25 @@ def astuple(obj: Any) -> Tuple[Any, ...]: ... @overload def astuple(obj: Any, *, tuple_factory: Callable[[List[Any]], _T]) -> _T: ... -if sys.version_info >= (3, 8): +if sys.version_info >= (3, 10): + # Added match_args + @overload + def dataclass(__cls: Type[_T]) -> Type[_T]: ... + @overload + 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 = ..., + match_args: bool = ..., + ) -> 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]: ... diff --git a/mypy/typeshed/stdlib/dbm/__init__.pyi b/mypy/typeshed/stdlib/dbm/__init__.pyi index 2b870b38e3c5..edce1ea02861 100644 --- a/mypy/typeshed/stdlib/dbm/__init__.pyi +++ b/mypy/typeshed/stdlib/dbm/__init__.pyi @@ -1,5 +1,5 @@ from types import TracebackType -from typing import Iterator, MutableMapping, Optional, Type, Union +from typing import Iterator, MutableMapping, Optional, Tuple, Type, Union from typing_extensions import Literal _KeyType = Union[str, bytes] @@ -18,7 +18,9 @@ class _Database(MutableMapping[_KeyType, bytes]): self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> None: ... -class error(Exception): ... +class _error(Exception): ... + +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/distutils/archive_util.pyi b/mypy/typeshed/stdlib/distutils/archive_util.pyi index 0e94d3818ae4..76ae158de3e6 100644 --- a/mypy/typeshed/stdlib/distutils/archive_util.pyi +++ b/mypy/typeshed/stdlib/distutils/archive_util.pyi @@ -7,6 +7,16 @@ def make_archive( base_dir: Optional[str] = ..., verbose: int = ..., dry_run: int = ..., + owner: Optional[str] = ..., + group: Optional[str] = ..., +) -> str: ... +def make_tarball( + base_name: str, + base_dir: str, + compress: Optional[str] = ..., + verbose: int = ..., + dry_run: int = ..., + owner: Optional[str] = ..., + group: Optional[str] = ..., ) -> str: ... -def make_tarball(base_name: str, base_dir: str, compress: Optional[str] = ..., verbose: int = ..., dry_run: int = ...) -> str: ... def make_zipfile(base_name: str, base_dir: str, verbose: int = ..., dry_run: int = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/distutils/debug.pyi b/mypy/typeshed/stdlib/distutils/debug.pyi index 098dc3dee246..89a7f3854ab4 100644 --- a/mypy/typeshed/stdlib/distutils/debug.pyi +++ b/mypy/typeshed/stdlib/distutils/debug.pyi @@ -1 +1,3 @@ -DEBUG: bool +from typing import Optional + +DEBUG: Optional[bool] diff --git a/mypy/typeshed/stdlib/distutils/extension.pyi b/mypy/typeshed/stdlib/distutils/extension.pyi index c85128ab1a16..47aa8ad4f040 100644 --- a/mypy/typeshed/stdlib/distutils/extension.pyi +++ b/mypy/typeshed/stdlib/distutils/extension.pyi @@ -5,18 +5,18 @@ class Extension: self, name: str, sources: List[str], - include_dirs: List[str] = ..., - define_macros: List[Tuple[str, Optional[str]]] = ..., - 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] = ..., + include_dirs: Optional[List[str]] = ..., + define_macros: Optional[List[Tuple[str, Optional[str]]]] = ..., + undef_macros: Optional[List[str]] = ..., + library_dirs: Optional[List[str]] = ..., + libraries: Optional[List[str]] = ..., + runtime_library_dirs: Optional[List[str]] = ..., + extra_objects: Optional[List[str]] = ..., + extra_compile_args: Optional[List[str]] = ..., + extra_link_args: Optional[List[str]] = ..., + export_symbols: Optional[List[str]] = ..., swig_opts: Optional[str] = ..., # undocumented - depends: List[str] = ..., - language: str = ..., - optional: bool = ..., + depends: Optional[List[str]] = ..., + language: Optional[str] = ..., + optional: Optional[bool] = ..., ) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi index 8eb4c416fa28..00f2cd648aeb 100644 --- a/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi +++ b/mypy/typeshed/stdlib/distutils/fancy_getopt.pyi @@ -1,4 +1,4 @@ -from typing import Any, List, Mapping, Optional, Tuple, Union, overload +from typing import Any, Iterable, List, Mapping, Optional, Tuple, Union, overload _Option = Tuple[str, Optional[str], str] _GR = Tuple[List[str], OptionDummy] @@ -18,4 +18,5 @@ class FancyGetopt: def get_option_order(self) -> List[Tuple[str, str]]: ... def generate_help(self, header: Optional[str] = ...) -> List[str]: ... -class OptionDummy: ... +class OptionDummy: + def __init__(self, options: Iterable[str] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/filelist.pyi b/mypy/typeshed/stdlib/distutils/filelist.pyi index 8fa55d09d265..ac7cdf8a15ce 100644 --- a/mypy/typeshed/stdlib/distutils/filelist.pyi +++ b/mypy/typeshed/stdlib/distutils/filelist.pyi @@ -1 +1,68 @@ -class FileList: ... +from typing import Iterable, List, Optional, Pattern, Union, overload +from typing_extensions import Literal + +# class is entirely undocumented +class FileList: + allfiles: Optional[Iterable[str]] = ... + files: List[str] = ... + def __init__(self, warn: None = ..., debug_print: None = ...) -> None: ... + def set_allfiles(self, allfiles: Iterable[str]) -> None: ... + def findall(self, dir: str = ...) -> None: ... + def debug_print(self, msg: str) -> None: ... + def append(self, item: str) -> None: ... + def extend(self, items: Iterable[str]) -> None: ... + def sort(self) -> None: ... + def remove_duplicates(self) -> None: ... + def process_template_line(self, line: str) -> None: ... + @overload + def include_pattern( + self, + pattern: str, + anchor: Union[int, bool] = ..., + prefix: Optional[str] = ..., + is_regex: Literal[0, False] = ..., + ) -> bool: ... + @overload + def include_pattern(self, pattern: Union[str, Pattern[str]], *, is_regex: Literal[True, 1] = ...) -> bool: ... + @overload + def include_pattern( + self, + pattern: Union[str, Pattern[str]], + anchor: Union[int, bool] = ..., + prefix: Optional[str] = ..., + is_regex: Union[int, bool] = ..., + ) -> bool: ... + @overload + def exclude_pattern( + self, + pattern: str, + anchor: Union[int, bool] = ..., + prefix: Optional[str] = ..., + is_regex: Literal[0, False] = ..., + ) -> bool: ... + @overload + def exclude_pattern(self, pattern: Union[str, Pattern[str]], *, is_regex: Literal[True, 1] = ...) -> bool: ... + @overload + def exclude_pattern( + self, + pattern: Union[str, Pattern[str]], + anchor: Union[int, bool] = ..., + prefix: Optional[str] = ..., + is_regex: Union[int, bool] = ..., + ) -> bool: ... + +def findall(dir: str = ...) -> List[str]: ... +def glob_to_re(pattern: str) -> str: ... +@overload +def translate_pattern( + pattern: str, anchor: Union[int, bool] = ..., prefix: Optional[str] = ..., is_regex: Literal[False, 0] = ... +) -> Pattern[str]: ... +@overload +def translate_pattern(pattern: Union[str, Pattern[str]], *, is_regex: Literal[True, 1] = ...) -> Pattern[str]: ... +@overload +def translate_pattern( + pattern: Union[str, Pattern[str]], + anchor: Union[int, bool] = ..., + prefix: Optional[str] = ..., + is_regex: Union[int, bool] = ..., +) -> Pattern[str]: ... diff --git a/mypy/typeshed/stdlib/distutils/sysconfig.pyi b/mypy/typeshed/stdlib/distutils/sysconfig.pyi index 9061db75ccf1..4b4baf416ffa 100644 --- a/mypy/typeshed/stdlib/distutils/sysconfig.pyi +++ b/mypy/typeshed/stdlib/distutils/sysconfig.pyi @@ -11,4 +11,3 @@ def get_makefile_filename() -> str: ... def get_python_inc(plat_specific: bool = ..., prefix: Optional[str] = ...) -> str: ... def get_python_lib(plat_specific: bool = ..., standard_lib: bool = ..., prefix: Optional[str] = ...) -> str: ... def customize_compiler(compiler: CCompiler) -> None: ... -def set_python_build() -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/text_file.pyi b/mypy/typeshed/stdlib/distutils/text_file.pyi index 9872a1f25751..a65f37305d94 100644 --- a/mypy/typeshed/stdlib/distutils/text_file.pyi +++ b/mypy/typeshed/stdlib/distutils/text_file.pyi @@ -15,7 +15,7 @@ class TextFile: ) -> None: ... def open(self, filename: str) -> None: ... def close(self) -> None: ... - def warn(self, msg: str, line: Union[List[int], Tuple[int, int], int] = ...) -> None: ... + def warn(self, msg: str, line: Optional[Union[List[int], Tuple[int, int], int]] = ...) -> None: ... def readline(self) -> Optional[str]: ... def readlines(self) -> List[str]: ... def unreadline(self, line: str) -> str: ... diff --git a/mypy/typeshed/stdlib/email/_header_value_parser.pyi b/mypy/typeshed/stdlib/email/_header_value_parser.pyi new file mode 100644 index 000000000000..22a2a643ed1b --- /dev/null +++ b/mypy/typeshed/stdlib/email/_header_value_parser.pyi @@ -0,0 +1,411 @@ +import sys +from email.errors import HeaderParseError, MessageDefect +from email.policy import Policy +from typing import Any, Iterable, Iterator, List, Optional, Pattern, Set, Tuple, Type, TypeVar, Union +from typing_extensions import Final + +_T = TypeVar("_T") + +WSP: Final[Set[str]] = ... +CFWS_LEADER: Final[Set[str]] = ... +SPECIALS: Final[Set[str]] = ... +ATOM_ENDS: Final[Set[str]] = ... +DOT_ATOM_ENDS: Final[Set[str]] = ... +PHRASE_ENDS: Final[Set[str]] = ... +TSPECIALS: Final[Set[str]] = ... +TOKEN_ENDS: Final[Set[str]] = ... +ASPECIALS: Final[Set[str]] = ... +ATTRIBUTE_ENDS: Final[Set[str]] = ... +EXTENDED_ATTRIBUTE_ENDS: Final[Set[str]] = ... + +def quote_string(value: Any) -> str: ... + +if sys.version_info >= (3, 7): + rfc2047_matcher: Pattern[str] + +class TokenList(List[Union[TokenList, Terminal]]): + token_type: Optional[str] = ... + syntactic_break: bool = ... + ew_combine_allowed: bool = ... + defects: List[MessageDefect] = ... + def __init__(self, *args: Any, **kw: Any) -> None: ... + @property + def value(self) -> str: ... + @property + def all_defects(self) -> List[MessageDefect]: ... + def startswith_fws(self) -> bool: ... + @property + def as_ew_allowed(self) -> bool: ... + @property + def comments(self) -> List[str]: ... + def fold(self, *, policy: Policy) -> str: ... + def pprint(self, indent: str = ...) -> None: ... + def ppstr(self, indent: str = ...) -> str: ... + +class WhiteSpaceTokenList(TokenList): + @property + def value(self) -> str: ... + @property + def comments(self) -> List[str]: ... + +class UnstructuredTokenList(TokenList): + token_type: str = ... + +class Phrase(TokenList): + token_type: str = ... + +class Word(TokenList): + token_type: str = ... + +class CFWSList(WhiteSpaceTokenList): + token_type: str = ... + +class Atom(TokenList): + token_type: str = ... + +class Token(TokenList): + token_type: str = ... + encode_as_ew: bool = ... + +class EncodedWord(TokenList): + token_type: str = ... + cte: Optional[str] = ... + charset: Optional[str] = ... + lang: Optional[str] = ... + +class QuotedString(TokenList): + token_type: str = ... + @property + def content(self) -> str: ... + @property + def quoted_value(self) -> str: ... + @property + def stripped_value(self) -> str: ... + +class BareQuotedString(QuotedString): + token_type: str = ... + @property + def value(self) -> str: ... + +class Comment(WhiteSpaceTokenList): + token_type: str = ... + def quote(self, value: Any) -> str: ... + @property + def content(self) -> str: ... + @property + def comments(self) -> List[str]: ... + +class AddressList(TokenList): + token_type: str = ... + @property + def addresses(self) -> List[Address]: ... + @property + def mailboxes(self) -> List[Mailbox]: ... + @property + def all_mailboxes(self) -> List[Mailbox]: ... + +class Address(TokenList): + token_type: str = ... + @property + def display_name(self) -> str: ... + @property + def mailboxes(self) -> List[Mailbox]: ... + @property + def all_mailboxes(self) -> List[Mailbox]: ... + +class MailboxList(TokenList): + token_type: str = ... + @property + def mailboxes(self) -> List[Mailbox]: ... + @property + def all_mailboxes(self) -> List[Mailbox]: ... + +class GroupList(TokenList): + token_type: str = ... + @property + def mailboxes(self) -> List[Mailbox]: ... + @property + def all_mailboxes(self) -> List[Mailbox]: ... + +class Group(TokenList): + token_type: str = ... + @property + def mailboxes(self) -> List[Mailbox]: ... + @property + def all_mailboxes(self) -> List[Mailbox]: ... + @property + def display_name(self) -> str: ... + +class NameAddr(TokenList): + token_type: str = ... + @property + def display_name(self) -> str: ... + @property + def local_part(self) -> str: ... + @property + def domain(self) -> str: ... + @property + def route(self) -> Optional[List[Domain]]: ... + @property + def addr_spec(self) -> str: ... + +class AngleAddr(TokenList): + token_type: str = ... + @property + def local_part(self) -> str: ... + @property + def domain(self) -> str: ... + @property + def route(self) -> Optional[List[Domain]]: ... + @property + def addr_spec(self) -> str: ... + +class ObsRoute(TokenList): + token_type: str = ... + @property + def domains(self) -> List[Domain]: ... + +class Mailbox(TokenList): + token_type: str = ... + @property + def display_name(self) -> str: ... + @property + def local_part(self) -> str: ... + @property + def domain(self) -> str: ... + @property + def route(self) -> List[str]: ... + @property + def addr_spec(self) -> str: ... + +class InvalidMailbox(TokenList): + token_type: str = ... + @property + def display_name(self) -> None: ... + local_part: None = ... + domain: None = ... + route: None = ... + addr_spec: None = ... + +class Domain(TokenList): + token_type: str = ... + as_ew_allowed: bool = ... + @property + def domain(self) -> str: ... + +class DotAtom(TokenList): + token_type: str = ... + +class DotAtomText(TokenList): + token_type: str = ... + as_ew_allowed: bool = ... + +if sys.version_info >= (3, 8): + class NoFoldLiteral(TokenList): + token_type: str = ... + as_ew_allowed: bool = ... + +class AddrSpec(TokenList): + token_type: str = ... + as_ew_allowed: bool = ... + @property + def local_part(self) -> str: ... + @property + def domain(self) -> str: ... + @property + def value(self) -> str: ... + @property + def addr_spec(self) -> str: ... + +class ObsLocalPart(TokenList): + token_type: str = ... + as_ew_allowed: bool = ... + +class DisplayName(Phrase): + token_type: str = ... + ew_combine_allowed: bool = ... + @property + def display_name(self) -> str: ... + @property + def value(self) -> str: ... + +class LocalPart(TokenList): + token_type: str = ... + as_ew_allowed: bool = ... + @property + def value(self) -> str: ... + @property + def local_part(self) -> str: ... + +class DomainLiteral(TokenList): + token_type: str = ... + as_ew_allowed: bool = ... + @property + def domain(self) -> str: ... + @property + def ip(self) -> str: ... + +class MIMEVersion(TokenList): + token_type: str = ... + major: Optional[int] = ... + minor: Optional[int] = ... + +class Parameter(TokenList): + token_type: str = ... + sectioned: bool = ... + extended: bool = ... + charset: str = ... + @property + def section_number(self) -> int: ... + @property + def param_value(self) -> str: ... + +class InvalidParameter(Parameter): + token_type: str = ... + +class Attribute(TokenList): + token_type: str = ... + @property + def stripped_value(self) -> str: ... + +class Section(TokenList): + token_type: str = ... + number: Optional[int] = ... + +class Value(TokenList): + token_type: str = ... + @property + def stripped_value(self) -> str: ... + +class MimeParameters(TokenList): + token_type: str = ... + syntactic_break: bool = ... + @property + def params(self) -> Iterator[Tuple[str, str]]: ... + +class ParameterizedHeaderValue(TokenList): + syntactic_break: bool = ... + @property + def params(self) -> Iterable[Tuple[str, str]]: ... + +class ContentType(ParameterizedHeaderValue): + token_type: str = ... + as_ew_allowed: bool = ... + maintype: str = ... + subtype: str = ... + +class ContentDisposition(ParameterizedHeaderValue): + token_type: str = ... + as_ew_allowed: bool = ... + content_disposition: Any = ... + +class ContentTransferEncoding(TokenList): + token_type: str = ... + as_ew_allowed: bool = ... + cte: str = ... + +class HeaderLabel(TokenList): + token_type: str = ... + as_ew_allowed: bool = ... + +if sys.version_info >= (3, 8): + class MsgID(TokenList): + token_type: str = ... + as_ew_allowed: bool = ... + def fold(self, policy: Policy) -> str: ... + class MessageID(MsgID): + token_type: str = ... + class InvalidMessageID(MessageID): + token_type: str = ... + +class Header(TokenList): + token_type: str = ... + +class Terminal(str): + as_ew_allowed: bool = ... + ew_combine_allowed: bool = ... + syntactic_break: bool = ... + token_type: str = ... + defects: List[MessageDefect] = ... + def __new__(cls: Type[_T], value: str, token_type: str) -> _T: ... + 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 + +class WhiteSpaceTerminal(Terminal): + @property + def value(self) -> str: ... + def startswith_fws(self) -> bool: ... + +class ValueTerminal(Terminal): + @property + def value(self) -> ValueTerminal: ... + def startswith_fws(self) -> bool: ... + +class EWWhiteSpaceTerminal(WhiteSpaceTerminal): + @property + def value(self) -> str: ... + +class _InvalidEwError(HeaderParseError): ... + +DOT: Final[ValueTerminal] +ListSeparator: Final[ValueTerminal] +RouteComponentMarker: Final[ValueTerminal] + +def get_fws(value: str) -> Tuple[WhiteSpaceTerminal, str]: ... +def get_encoded_word(value: str) -> Tuple[EncodedWord, str]: ... +def get_unstructured(value: str) -> UnstructuredTokenList: ... +def get_qp_ctext(value: str) -> Tuple[WhiteSpaceTerminal, str]: ... +def get_qcontent(value: str) -> Tuple[ValueTerminal, str]: ... +def get_atext(value: str) -> Tuple[ValueTerminal, str]: ... +def get_bare_quoted_string(value: str) -> Tuple[BareQuotedString, str]: ... +def get_comment(value: str) -> Tuple[Comment, str]: ... +def get_cfws(value: str) -> Tuple[CFWSList, str]: ... +def get_quoted_string(value: str) -> Tuple[QuotedString, str]: ... +def get_atom(value: str) -> Tuple[Atom, str]: ... +def get_dot_atom_text(value: str) -> Tuple[DotAtomText, str]: ... +def get_dot_atom(value: str) -> Tuple[DotAtom, str]: ... +def get_word(value: str) -> Tuple[Any, str]: ... +def get_phrase(value: str) -> Tuple[Phrase, str]: ... +def get_local_part(value: str) -> Tuple[LocalPart, str]: ... +def get_obs_local_part(value: str) -> Tuple[ObsLocalPart, str]: ... +def get_dtext(value: str) -> Tuple[ValueTerminal, str]: ... +def get_domain_literal(value: str) -> Tuple[DomainLiteral, str]: ... +def get_domain(value: str) -> Tuple[Domain, str]: ... +def get_addr_spec(value: str) -> Tuple[AddrSpec, str]: ... +def get_obs_route(value: str) -> Tuple[ObsRoute, str]: ... +def get_angle_addr(value: str) -> Tuple[AngleAddr, str]: ... +def get_display_name(value: str) -> Tuple[DisplayName, str]: ... +def get_name_addr(value: str) -> Tuple[NameAddr, str]: ... +def get_mailbox(value: str) -> Tuple[Mailbox, str]: ... +def get_invalid_mailbox(value: str, endchars: str) -> Tuple[InvalidMailbox, str]: ... +def get_mailbox_list(value: str) -> Tuple[MailboxList, str]: ... +def get_group_list(value: str) -> Tuple[GroupList, str]: ... +def get_group(value: str) -> Tuple[Group, str]: ... +def get_address(value: str) -> Tuple[Address, str]: ... +def get_address_list(value: str) -> Tuple[AddressList, str]: ... + +if sys.version_info >= (3, 8): + def get_no_fold_literal(value: str) -> Tuple[NoFoldLiteral, str]: ... + def get_msg_id(value: str) -> Tuple[MsgID, str]: ... + def parse_message_id(value: str) -> MessageID: ... + +def parse_mime_version(value: str) -> MIMEVersion: ... +def get_invalid_parameter(value: str) -> Tuple[InvalidParameter, str]: ... +def get_ttext(value: str) -> Tuple[ValueTerminal, str]: ... +def get_token(value: str) -> Tuple[Token, str]: ... +def get_attrtext(value: str) -> Tuple[ValueTerminal, str]: ... +def get_attribute(value: str) -> Tuple[Attribute, str]: ... +def get_extended_attrtext(value: str) -> Tuple[ValueTerminal, str]: ... +def get_extended_attribute(value: str) -> Tuple[Attribute, str]: ... +def get_section(value: str) -> Tuple[Section, str]: ... +def get_value(value: str) -> Tuple[Value, str]: ... +def get_parameter(value: str) -> Tuple[Parameter, str]: ... +def parse_mime_parameters(value: str) -> MimeParameters: ... +def parse_content_type_header(value: str) -> ContentType: ... +def parse_content_disposition_header(value: str) -> ContentDisposition: ... +def parse_content_transfer_encoding_header(value: str) -> ContentTransferEncoding: ... diff --git a/mypy/typeshed/stdlib/email/errors.pyi b/mypy/typeshed/stdlib/email/errors.pyi index dd2b70b10fca..561eb0bd0ea5 100644 --- a/mypy/typeshed/stdlib/email/errors.pyi +++ b/mypy/typeshed/stdlib/email/errors.pyi @@ -1,9 +1,14 @@ +from typing import Optional + class MessageError(Exception): ... class MessageParseError(MessageError): ... class HeaderParseError(MessageParseError): ... class BoundaryError(MessageParseError): ... class MultipartConversionError(MessageError, TypeError): ... -class MessageDefect(ValueError): ... + +class MessageDefect(ValueError): + def __init__(self, line: Optional[str] = ...) -> None: ... + class NoBoundaryInMultipartDefect(MessageDefect): ... class StartBoundaryNotFoundDefect(MessageDefect): ... class FirstHeaderLineIsContinuationDefect(MessageDefect): ... diff --git a/mypy/typeshed/stdlib/email/generator.pyi b/mypy/typeshed/stdlib/email/generator.pyi index ff0c2d902147..522f74f31a43 100644 --- a/mypy/typeshed/stdlib/email/generator.pyi +++ b/mypy/typeshed/stdlib/email/generator.pyi @@ -5,14 +5,36 @@ from typing import BinaryIO, Optional, TextIO class Generator: def clone(self, fp: TextIO) -> Generator: ... def write(self, s: str) -> None: ... - def __init__(self, outfp: TextIO, mangle_from_: bool = ..., maxheaderlen: int = ..., *, policy: Policy = ...) -> None: ... + def __init__( + self, + outfp: TextIO, + mangle_from_: Optional[bool] = ..., + maxheaderlen: Optional[int] = ..., + *, + policy: Optional[Policy] = ..., + ) -> None: ... def flatten(self, msg: Message, unixfrom: bool = ..., linesep: Optional[str] = ...) -> None: ... class BytesGenerator: def clone(self, fp: BinaryIO) -> BytesGenerator: ... def write(self, s: str) -> None: ... - def __init__(self, outfp: BinaryIO, mangle_from_: bool = ..., maxheaderlen: int = ..., *, policy: Policy = ...) -> None: ... + def __init__( + self, + outfp: BinaryIO, + mangle_from_: Optional[bool] = ..., + maxheaderlen: Optional[int] = ..., + *, + policy: Optional[Policy] = ..., + ) -> None: ... def flatten(self, msg: Message, unixfrom: bool = ..., linesep: Optional[str] = ...) -> None: ... class DecodedGenerator(Generator): - def __init__(self, outfp: TextIO, mangle_from_: bool = ..., maxheaderlen: int = ..., *, fmt: Optional[str] = ...) -> None: ... + def __init__( + self, + outfp: TextIO, + mangle_from_: Optional[bool] = ..., + maxheaderlen: Optional[int] = ..., + fmt: Optional[str] = ..., + *, + policy: Optional[Policy] = ..., + ) -> None: ... diff --git a/mypy/typeshed/stdlib/email/headerregistry.pyi b/mypy/typeshed/stdlib/email/headerregistry.pyi index 4ccb4d312203..b661496b9b62 100644 --- a/mypy/typeshed/stdlib/email/headerregistry.pyi +++ b/mypy/typeshed/stdlib/email/headerregistry.pyi @@ -1,7 +1,17 @@ +import sys from datetime import datetime as _datetime +from email._header_value_parser import ( + AddressList, + ContentDisposition, + ContentTransferEncoding, + ContentType, + MIMEVersion, + TokenList, + UnstructuredTokenList, +) from email.errors import MessageDefect from email.policy import Policy -from typing import Any, Dict, Mapping, Optional, Tuple, Union +from typing import Any, Dict, Iterable, Mapping, Optional, Tuple, Type, Union class BaseHeader(str): @property @@ -11,27 +21,36 @@ class BaseHeader(str): @property def max_count(self) -> Optional[int]: ... def __new__(cls, name: str, value: Any) -> BaseHeader: ... - def init(self, *args: Any, **kw: Any) -> None: ... + def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect]) -> None: ... def fold(self, *, policy: Policy) -> str: ... class UnstructuredHeader: + @staticmethod + def value_parser(value: str) -> UnstructuredTokenList: ... @classmethod - def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + def parse(cls, value: str, kwds: Dict[str, Any]) -> None: ... class UniqueUnstructuredHeader(UnstructuredHeader): ... class DateHeader: - datetime: _datetime + @property + def datetime(self) -> _datetime: ... + @staticmethod + def value_parser(value: str) -> UnstructuredTokenList: ... @classmethod - def parse(cls, string: Union[str, _datetime], kwds: Dict[str, Any]) -> None: ... + def parse(cls, value: Union[str, _datetime], kwds: Dict[str, Any]) -> None: ... class UniqueDateHeader(DateHeader): ... class AddressHeader: - groups: Tuple[Group, ...] - addresses: Tuple[Address, ...] + @property + def groups(self) -> Tuple[Group, ...]: ... + @property + def addresses(self) -> Tuple[Address, ...]: ... + @staticmethod + def value_parser(value: str) -> AddressList: ... @classmethod - def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + def parse(cls, value: str, kwds: Dict[str, Any]) -> None: ... class UniqueAddressHeader(AddressHeader): ... @@ -42,40 +61,70 @@ class SingleAddressHeader(AddressHeader): class UniqueSingleAddressHeader(SingleAddressHeader): ... class MIMEVersionHeader: - version: Optional[str] - major: Optional[int] - minor: Optional[int] + @property + def version(self) -> Optional[str]: ... + @property + def major(self) -> Optional[int]: ... + @property + def minor(self) -> Optional[int]: ... + @staticmethod + def value_parser(value: str) -> MIMEVersion: ... @classmethod - def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + def parse(cls, value: str, kwds: Dict[str, Any]) -> None: ... class ParameterizedMIMEHeader: - params: Mapping[str, Any] + @property + def params(self) -> Mapping[str, Any]: ... @classmethod - def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + def parse(cls, value: str, kwds: Dict[str, Any]) -> None: ... class ContentTypeHeader(ParameterizedMIMEHeader): - content_type: str - maintype: str - subtype: str + @property + def content_type(self) -> str: ... + @property + def maintype(self) -> str: ... + @property + def subtype(self) -> str: ... + @staticmethod + def value_parser(value: str) -> ContentType: ... class ContentDispositionHeader(ParameterizedMIMEHeader): - content_disposition: str + @property + def content_disposition(self) -> str: ... + @staticmethod + def value_parser(value: str) -> ContentDisposition: ... class ContentTransferEncodingHeader: - cte: str + @property + def cte(self) -> str: ... @classmethod - def parse(cls, string: str, kwds: Dict[str, Any]) -> None: ... + def parse(cls, value: str, kwds: Dict[str, Any]) -> None: ... + @staticmethod + def value_parser(value: str) -> ContentTransferEncoding: ... + +if sys.version_info >= (3, 8): + from email._header_value_parser import MessageID + class MessageIDHeader: + @classmethod + def parse(cls, value: str, kwds: Dict[str, Any]) -> None: ... + @staticmethod + def value_parser(value: str) -> MessageID: ... class HeaderRegistry: - def __init__(self, base_class: BaseHeader = ..., default_class: BaseHeader = ..., use_default_map: bool = ...) -> None: ... - def map_to_type(self, name: str, cls: BaseHeader) -> None: ... - def __getitem__(self, name: str) -> BaseHeader: ... + def __init__( + 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 __call__(self, name: str, value: Any) -> BaseHeader: ... class Address: - display_name: str - username: str - domain: str + @property + def display_name(self) -> str: ... + @property + def username(self) -> str: ... + @property + def domain(self) -> str: ... @property def addr_spec(self) -> str: ... def __init__( @@ -84,7 +133,9 @@ class Address: def __str__(self) -> str: ... class Group: - display_name: Optional[str] - addresses: Tuple[Address, ...] - def __init__(self, display_name: Optional[str] = ..., addresses: Optional[Tuple[Address, ...]] = ...) -> None: ... + @property + def display_name(self) -> Optional[str]: ... + @property + def addresses(self) -> Tuple[Address, ...]: ... + def __init__(self, display_name: Optional[str] = ..., addresses: Optional[Iterable[Address]] = ...) -> None: ... def __str__(self) -> str: ... diff --git a/mypy/typeshed/stdlib/email/message.pyi b/mypy/typeshed/stdlib/email/message.pyi index 720d5e5d7b63..37c9caffa916 100644 --- a/mypy/typeshed/stdlib/email/message.pyi +++ b/mypy/typeshed/stdlib/email/message.pyi @@ -13,6 +13,7 @@ _ParamType = Union[str, Tuple[Optional[str], Optional[str], str]] _HeaderType = Any class Message: + policy: Policy # undocumented preamble: Optional[str] epilogue: Optional[str] defects: List[MessageDefect] @@ -21,7 +22,7 @@ class Message: def set_unixfrom(self, unixfrom: str) -> None: ... def get_unixfrom(self) -> Optional[str]: ... def attach(self, payload: Message) -> None: ... - def get_payload(self, i: int = ..., decode: bool = ...) -> Any: ... # returns Optional[_PayloadType] + def get_payload(self, i: Optional[int] = ..., decode: bool = ...) -> Any: ... # returns Optional[_PayloadType] def set_payload(self, payload: _PayloadType, charset: _CharsetType = ...) -> None: ... def set_charset(self, charset: _CharsetType) -> None: ... def get_charset(self) -> _CharsetType: ... @@ -62,13 +63,14 @@ class Message: value: str, header: str = ..., requote: bool = ..., - charset: str = ..., + charset: Optional[str] = ..., language: str = ..., replace: bool = ..., ) -> None: ... def __init__(self, policy: Policy = ...) -> None: ... class MIMEPart(Message): + def __init__(self, policy: Optional[Policy] = ...) -> None: ... def get_body(self, preferencelist: Sequence[str] = ...) -> Optional[Message]: ... def iter_attachments(self) -> Iterator[Message]: ... def iter_parts(self) -> Iterator[Message]: ... @@ -82,6 +84,7 @@ class MIMEPart(Message): def add_attachment(self, *args: Any, content_manager: Optional[ContentManager] = ..., **kw: Any) -> None: ... def clear(self) -> None: ... def clear_content(self) -> None: ... + def as_string(self, unixfrom: bool = ..., maxheaderlen: Optional[int] = ..., policy: Optional[Policy] = ...) -> str: ... def is_attachment(self) -> bool: ... class EmailMessage(MIMEPart): ... diff --git a/mypy/typeshed/stdlib/email/parser.pyi b/mypy/typeshed/stdlib/email/parser.pyi index f1e402408d47..d081540a9d81 100644 --- a/mypy/typeshed/stdlib/email/parser.pyi +++ b/mypy/typeshed/stdlib/email/parser.pyi @@ -1,18 +1,18 @@ import email.feedparser from email.message import Message from email.policy import Policy -from typing import BinaryIO, Callable, TextIO +from typing import BinaryIO, Callable, Optional, TextIO FeedParser = email.feedparser.FeedParser BytesFeedParser = email.feedparser.BytesFeedParser class Parser: - def __init__(self, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> None: ... + def __init__(self, _class: Optional[Callable[[], Message]] = ..., *, policy: Policy = ...) -> None: ... def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ... def parsestr(self, text: str, headersonly: bool = ...) -> Message: ... class HeaderParser(Parser): - def __init__(self, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> None: ... + def __init__(self, _class: Optional[Callable[[], Message]] = ..., *, policy: Policy = ...) -> None: ... def parse(self, fp: TextIO, headersonly: bool = ...) -> Message: ... def parsestr(self, text: str, headersonly: bool = ...) -> Message: ... diff --git a/mypy/typeshed/stdlib/email/utils.pyi b/mypy/typeshed/stdlib/email/utils.pyi index 7c4c409be80d..3a39d4fcfd02 100644 --- a/mypy/typeshed/stdlib/email/utils.pyi +++ b/mypy/typeshed/stdlib/email/utils.pyi @@ -8,31 +8,31 @@ _PDTZ = Tuple[int, int, int, int, int, int, int, int, int, Optional[int]] def quote(str: str) -> str: ... def unquote(str: str) -> str: ... -def parseaddr(address: Optional[str]) -> Tuple[str, str]: ... +def parseaddr(addr: Optional[str]) -> Tuple[str, str]: ... def formataddr(pair: Tuple[Optional[str], str], charset: Union[str, Charset] = ...) -> str: ... def getaddresses(fieldvalues: List[str]) -> List[Tuple[str, str]]: ... @overload -def parsedate(date: None) -> None: ... +def parsedate(data: None) -> None: ... @overload -def parsedate(date: str) -> Optional[Tuple[int, int, int, int, int, int, int, int, int]]: ... +def parsedate(data: str) -> Optional[Tuple[int, int, int, int, int, int, int, int, int]]: ... @overload -def parsedate_tz(date: None) -> None: ... +def parsedate_tz(data: None) -> None: ... @overload -def parsedate_tz(date: str) -> Optional[_PDTZ]: ... +def parsedate_tz(data: str) -> Optional[_PDTZ]: ... if sys.version_info >= (3, 10): @overload - def parsedate_to_datetime(date: None) -> None: ... + def parsedate_to_datetime(data: None) -> None: ... @overload - def parsedate_to_datetime(date: str) -> datetime.datetime: ... + def parsedate_to_datetime(data: str) -> datetime.datetime: ... else: - def parsedate_to_datetime(date: str) -> datetime.datetime: ... + def parsedate_to_datetime(data: str) -> datetime.datetime: ... -def mktime_tz(tuple: _PDTZ) -> int: ... +def mktime_tz(data: _PDTZ) -> int: ... def formatdate(timeval: Optional[float] = ..., localtime: bool = ..., usegmt: bool = ...) -> str: ... def format_datetime(dt: datetime.datetime, usegmt: bool = ...) -> str: ... -def localtime(dt: Optional[datetime.datetime] = ...) -> datetime.datetime: ... +def localtime(dt: Optional[datetime.datetime] = ..., isdst: int = ...) -> datetime.datetime: ... def make_msgid(idstring: Optional[str] = ..., domain: Optional[str] = ...) -> str: ... def decode_rfc2231(s: str) -> Tuple[Optional[str], Optional[str], str]: ... def encode_rfc2231(s: str, charset: Optional[str] = ..., language: Optional[str] = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/encodings/__init__.pyi b/mypy/typeshed/stdlib/encodings/__init__.pyi index d6f4389bc820..fe59a914383d 100644 --- a/mypy/typeshed/stdlib/encodings/__init__.pyi +++ b/mypy/typeshed/stdlib/encodings/__init__.pyi @@ -1,7 +1,7 @@ -import codecs -from typing import Any +from codecs import CodecInfo +from typing import Optional, Union -def search_function(encoding: str) -> codecs.CodecInfo: ... +class CodecRegistryError(LookupError, SystemError): ... -# Explicitly mark this package as incomplete. -def __getattr__(name: str) -> Any: ... +def normalize_encoding(encoding: Union[str, bytes]) -> str: ... +def search_function(encoding: str) -> Optional[CodecInfo]: ... diff --git a/mypy/typeshed/stdlib/encodings/utf_8.pyi b/mypy/typeshed/stdlib/encodings/utf_8.pyi index 67e139c88f60..96a156c792b6 100644 --- a/mypy/typeshed/stdlib/encodings/utf_8.pyi +++ b/mypy/typeshed/stdlib/encodings/utf_8.pyi @@ -1,15 +1,21 @@ import codecs -from typing import Tuple +from typing import Optional, Tuple class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input: str, final: bool = ...) -> bytes: ... class IncrementalDecoder(codecs.BufferedIncrementalDecoder): - def _buffer_decode(self, input: bytes, errors: str, final: bool) -> Tuple[str, int]: ... + @staticmethod + def _buffer_decode(__data: bytes, __errors: Optional[str] = ..., __final: bool = ...) -> Tuple[str, int]: ... -class StreamWriter(codecs.StreamWriter): ... -class StreamReader(codecs.StreamReader): ... +class StreamWriter(codecs.StreamWriter): + @staticmethod + def encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... + +class StreamReader(codecs.StreamReader): + @staticmethod + def decode(__data: bytes, __errors: Optional[str] = ..., __final: bool = ...) -> Tuple[str, int]: ... def getregentry() -> codecs.CodecInfo: ... -def encode(input: str, errors: str = ...) -> bytes: ... -def decode(input: bytes, errors: str = ...) -> str: ... +def encode(__str: str, __errors: Optional[str] = ...) -> Tuple[bytes, int]: ... +def decode(input: bytes, errors: Optional[str] = ...) -> Tuple[str, int]: ... diff --git a/mypy/typeshed/stdlib/enum.pyi b/mypy/typeshed/stdlib/enum.pyi index 1a1dcf005b2d..9b44bc020d77 100644 --- a/mypy/typeshed/stdlib/enum.pyi +++ b/mypy/typeshed/stdlib/enum.pyi @@ -13,7 +13,7 @@ _S = TypeVar("_S", bound=Type[Enum]) class EnumMeta(ABCMeta): def __iter__(self: Type[_T]) -> Iterator[_T]: ... def __reversed__(self: Type[_T]) -> Iterator[_T]: ... - def __contains__(self: Type[_T], member: object) -> bool: ... + def __contains__(self: Type[Any], member: object) -> bool: ... def __getitem__(self: Type[_T], name: str) -> _T: ... @property def __members__(self: Type[_T]) -> Mapping[str, _T]: ... @@ -45,6 +45,7 @@ class Enum(metaclass=EnumMeta): class IntEnum(int, Enum): value: int + def __new__(cls: Type[_T], value: Union[int, _T]) -> _T: ... def unique(enumeration: _S) -> _S: ... @@ -53,6 +54,7 @@ _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: ... class Flag(Enum): def __contains__(self: _T, other: _T) -> bool: ... @@ -65,6 +67,7 @@ class Flag(Enum): def __invert__(self: _T) -> _T: ... class IntFlag(int, Flag): + def __new__(cls: Type[_T], value: Union[int, _T]) -> _T: ... def __or__(self: _T, other: Union[int, _T]) -> _T: ... def __and__(self: _T, other: Union[int, _T]) -> _T: ... def __xor__(self: _T, other: Union[int, _T]) -> _T: ... diff --git a/mypy/typeshed/stdlib/fcntl.pyi b/mypy/typeshed/stdlib/fcntl.pyi index 7b94c6e941ce..42b88d020c6e 100644 --- a/mypy/typeshed/stdlib/fcntl.pyi +++ b/mypy/typeshed/stdlib/fcntl.pyi @@ -86,7 +86,7 @@ def fcntl(__fd: FileDescriptorLike, __cmd: int, __arg: int = ...) -> int: ... def fcntl(__fd: FileDescriptorLike, __cmd: int, __arg: bytes) -> bytes: ... _ReadOnlyBuffer = bytes -_WritableBuffer = Union[bytearray, memoryview, array] +_WritableBuffer = Union[bytearray, memoryview, array[Any]] @overload def ioctl(__fd: FileDescriptorLike, __request: int, __arg: int = ..., __mutate_flag: bool = ...) -> int: ... @overload diff --git a/mypy/typeshed/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index 10c46f42ea79..32c65937b1e3 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -91,14 +91,14 @@ class _SingleDispatchCallable(Generic[_T]): # @fun.register(complex) # def _(arg, verbose=False): ... @overload - def register(self, cls: type, 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, 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: ... @@ -110,11 +110,11 @@ if sys.version_info >= (3, 8): func: Callable[..., _T] def __init__(self, func: Callable[..., _T]) -> None: ... @overload - def register(self, cls: Type, 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, 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] @@ -123,7 +123,7 @@ if sys.version_info >= (3, 8): @overload def __get__(self, instance: None, owner: Optional[Type[Any]] = ...) -> cached_property[_T]: ... @overload - def __get__(self, instance: _S, owner: Optional[Type[Any]] = ...) -> _T: ... + def __get__(self, instance: object, owner: Optional[Type[Any]] = ...) -> _T: ... def __set_name__(self, owner: Type[Any], name: str) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/getopt.pyi b/mypy/typeshed/stdlib/getopt.pyi index c92be2a6a8e4..6ae226f52972 100644 --- a/mypy/typeshed/stdlib/getopt.pyi +++ b/mypy/typeshed/stdlib/getopt.pyi @@ -1,10 +1,9 @@ -from typing import List, Tuple - -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]]: ... class GetoptError(Exception): msg: str opt: str + def __init__(self, msg: str, opt: str = ...) -> None: ... error = GetoptError diff --git a/mypy/typeshed/stdlib/gettext.pyi b/mypy/typeshed/stdlib/gettext.pyi index 5624817b1435..74a5e56a74c6 100644 --- a/mypy/typeshed/stdlib/gettext.pyi +++ b/mypy/typeshed/stdlib/gettext.pyi @@ -52,7 +52,7 @@ def translation( domain: str, localedir: Optional[StrPath] = ..., languages: Optional[Iterable[str]] = ..., - class_: Type[_T] = ..., + class_: Type[Any] = ..., fallback: Literal[True] = ..., codeset: Optional[str] = ..., ) -> Any: ... diff --git a/mypy/typeshed/stdlib/gzip.pyi b/mypy/typeshed/stdlib/gzip.pyi index 4ce54b3b8a5d..8d061e051b93 100644 --- a/mypy/typeshed/stdlib/gzip.pyi +++ b/mypy/typeshed/stdlib/gzip.pyi @@ -2,15 +2,46 @@ import _compression import sys import zlib from _typeshed import AnyPath, ReadableBuffer -from typing import IO, Optional, TextIO, Union, overload +from io import FileIO +from typing import Any, Optional, Protocol, TextIO, Union, overload from typing_extensions import Literal -_OpenBinaryMode = Literal["r", "rb", "a", "ab", "w", "wb", "x", "xb"] +_ReadBinaryMode = Literal["r", "rb"] +_WriteBinaryMode = Literal["a", "ab", "w", "wb", "x", "xb"] _OpenTextMode = Literal["rt", "at", "wt", "xt"] + +READ: Literal[1] +WRITE: Literal[2] + +class _ReadableFileobj(Protocol): + def read(self, __n: int) -> bytes: ... + def seek(self, __n: int) -> Any: ... + # The following attributes and methods are optional: + # name: str + # mode: str + # def fileno() -> int: ... + +class _WritableFileobj(Protocol): + def write(self, __b: bytes) -> Any: ... + def flush(self) -> Any: ... + # The following attributes and methods are optional: + # name: str + # mode: str + # def fileno() -> int: ... + +@overload +def open( + filename: Union[AnyPath, _ReadableFileobj], + mode: _ReadBinaryMode = ..., + compresslevel: int = ..., + encoding: None = ..., + errors: None = ..., + newline: None = ..., +) -> GzipFile: ... @overload def open( - filename: Union[AnyPath, IO[bytes]], - mode: _OpenBinaryMode = ..., + filename: Union[AnyPath, _WritableFileobj], + mode: _WriteBinaryMode, compresslevel: int = ..., encoding: None = ..., errors: None = ..., @@ -27,7 +58,7 @@ def open( ) -> TextIO: ... @overload def open( - filename: Union[AnyPath, IO[bytes]], + filename: Union[AnyPath, _ReadableFileobj, _WritableFileobj], mode: str, compresslevel: int = ..., encoding: Optional[str] = ..., @@ -36,8 +67,8 @@ def open( ) -> Union[GzipFile, TextIO]: ... class _PaddedFile: - file: IO[bytes] - def __init__(self, f: IO[bytes], prepend: bytes = ...) -> None: ... + file: _ReadableFileobj + def __init__(self, f: _ReadableFileobj, prepend: bytes = ...) -> None: ... def read(self, size: int) -> bytes: ... def prepend(self, prepend: bytes = ...) -> None: ... def seek(self, off: int) -> int: ... @@ -47,17 +78,54 @@ if sys.version_info >= (3, 8): class BadGzipFile(OSError): ... class GzipFile(_compression.BaseStream): - myfileobj: Optional[IO[bytes]] - mode: str + myfileobj: Optional[FileIO] + mode: Literal[1, 2] name: str compress: zlib._Compress - fileobj: IO[bytes] + fileobj: Union[_ReadableFileobj, _WritableFileobj] + @overload + def __init__( + self, + filename: Optional[AnyPath], + mode: _ReadBinaryMode, + compresslevel: int = ..., + fileobj: Optional[_ReadableFileobj] = ..., + mtime: Optional[float] = ..., + ) -> None: ... + @overload + def __init__( + self, + *, + mode: _ReadBinaryMode, + compresslevel: int = ..., + fileobj: Optional[_ReadableFileobj] = ..., + mtime: Optional[float] = ..., + ) -> None: ... + @overload + def __init__( + self, + filename: Optional[AnyPath], + mode: _WriteBinaryMode, + compresslevel: int = ..., + fileobj: Optional[_WritableFileobj] = ..., + mtime: Optional[float] = ..., + ) -> None: ... + @overload + def __init__( + self, + *, + mode: _WriteBinaryMode, + compresslevel: int = ..., + fileobj: Optional[_WritableFileobj] = ..., + mtime: Optional[float] = ..., + ) -> None: ... + @overload def __init__( self, filename: Optional[AnyPath] = ..., mode: Optional[str] = ..., compresslevel: int = ..., - fileobj: Optional[IO[bytes]] = ..., + fileobj: Union[_ReadableFileobj, _WritableFileobj, None] = ..., mtime: Optional[float] = ..., ) -> None: ... @property @@ -82,7 +150,7 @@ class GzipFile(_compression.BaseStream): def readline(self, size: Optional[int] = ...) -> bytes: ... class _GzipReader(_compression.DecompressReader): - def __init__(self, fp: IO[bytes]) -> None: ... + def __init__(self, fp: _ReadableFileobj) -> None: ... def read(self, size: int = ...) -> bytes: ... if sys.version_info >= (3, 8): diff --git a/mypy/typeshed/stdlib/hashlib.pyi b/mypy/typeshed/stdlib/hashlib.pyi index 70b120d08a46..e4aee21450cc 100644 --- a/mypy/typeshed/stdlib/hashlib.pyi +++ b/mypy/typeshed/stdlib/hashlib.pyi @@ -17,6 +17,7 @@ class _Hash(object): def update(self, __data: ReadableBuffer) -> None: ... if sys.version_info >= (3, 9): + def new(name: str, data: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... def md5(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... def sha1(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... def sha224(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... @@ -25,6 +26,7 @@ if sys.version_info >= (3, 9): def sha512(string: ReadableBuffer = ..., *, usedforsecurity: bool = ...) -> _Hash: ... elif sys.version_info >= (3, 8): + def new(name: str, data: ReadableBuffer = ...) -> _Hash: ... def md5(string: ReadableBuffer = ...) -> _Hash: ... def sha1(string: ReadableBuffer = ...) -> _Hash: ... def sha224(string: ReadableBuffer = ...) -> _Hash: ... @@ -33,6 +35,7 @@ elif sys.version_info >= (3, 8): def sha512(string: ReadableBuffer = ...) -> _Hash: ... else: + def new(name: str, data: ReadableBuffer = ...) -> _Hash: ... def md5(__string: ReadableBuffer = ...) -> _Hash: ... def sha1(__string: ReadableBuffer = ...) -> _Hash: ... def sha224(__string: ReadableBuffer = ...) -> _Hash: ... @@ -40,8 +43,6 @@ else: def sha384(__string: ReadableBuffer = ...) -> _Hash: ... def sha512(__string: ReadableBuffer = ...) -> _Hash: ... -def new(name: str, data: ReadableBuffer = ...) -> _Hash: ... - algorithms_guaranteed: AbstractSet[str] algorithms_available: AbstractSet[str] diff --git a/mypy/typeshed/stdlib/heapq.pyi b/mypy/typeshed/stdlib/heapq.pyi index 5592e615fcd2..3d27a30bb412 100644 --- a/mypy/typeshed/stdlib/heapq.pyi +++ b/mypy/typeshed/stdlib/heapq.pyi @@ -6,9 +6,9 @@ _T = TypeVar("_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(__heap: List[_T]) -> None: ... +def heapify(__heap: List[Any]) -> None: ... def heapreplace(__heap: List[_T], __item: _T) -> _T: ... def merge(*iterables: Iterable[_T], key: Optional[Callable[[_T], Any]] = ..., reverse: bool = ...) -> Iterable[_T]: ... def nlargest(n: int, iterable: Iterable[_T], key: Optional[Callable[[_T], SupportsLessThan]] = ...) -> List[_T]: ... def nsmallest(n: int, iterable: Iterable[_T], key: Optional[Callable[[_T], SupportsLessThan]] = ...) -> List[_T]: ... -def _heapify_max(__x: List[_T]) -> None: ... # undocumented +def _heapify_max(__x: List[Any]) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/html/parser.pyi b/mypy/typeshed/stdlib/html/parser.pyi index 31240f78c58e..b49766bfc9b8 100644 --- a/mypy/typeshed/stdlib/html/parser.pyi +++ b/mypy/typeshed/stdlib/html/parser.pyi @@ -3,7 +3,7 @@ from typing import List, Optional, Tuple class HTMLParser(ParserBase): def __init__(self, *, convert_charrefs: bool = ...) -> None: ... - def feed(self, feed: str) -> None: ... + def feed(self, data: str) -> None: ... def close(self) -> None: ... def reset(self) -> None: ... def getpos(self) -> Tuple[int, int]: ... diff --git a/mypy/typeshed/stdlib/http/client.pyi b/mypy/typeshed/stdlib/http/client.pyi index 34402e40b468..2f6b2df08868 100644 --- a/mypy/typeshed/stdlib/http/client.pyi +++ b/mypy/typeshed/stdlib/http/client.pyi @@ -3,6 +3,7 @@ import io import ssl import sys import types +from _typeshed import WriteableBuffer from socket import socket from typing import ( IO, @@ -103,6 +104,9 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): reason: str def __init__(self, sock: socket, debuglevel: int = ..., method: Optional[str] = ..., url: Optional[str] = ...) -> None: ... def read(self, amt: Optional[int] = ...) -> bytes: ... + def read1(self, n: int = ...) -> bytes: ... + def readinto(self, b: WriteableBuffer) -> int: ... + def readline(self, limit: int = ...) -> bytes: ... # type: ignore @overload def getheader(self, name: str) -> Optional[str]: ... @overload @@ -198,14 +202,25 @@ error = HTTPException class NotConnected(HTTPException): ... class InvalidURL(HTTPException): ... -class UnknownProtocol(HTTPException): ... + +class UnknownProtocol(HTTPException): + def __init__(self, version: str) -> None: ... + class UnknownTransferEncoding(HTTPException): ... class UnimplementedFileMode(HTTPException): ... -class IncompleteRead(HTTPException): ... + +class IncompleteRead(HTTPException): + def __init__(self, partial: bytes, expected: Optional[int] = ...) -> None: ... + class ImproperConnectionState(HTTPException): ... class CannotSendRequest(ImproperConnectionState): ... class CannotSendHeader(ImproperConnectionState): ... class ResponseNotReady(ImproperConnectionState): ... -class BadStatusLine(HTTPException): ... -class LineTooLong(HTTPException): ... + +class BadStatusLine(HTTPException): + def __init__(self, line: str) -> None: ... + +class LineTooLong(HTTPException): + def __init__(self, line_type: str) -> None: ... + class RemoteDisconnected(ConnectionResetError, BadStatusLine): ... diff --git a/mypy/typeshed/stdlib/http/cookiejar.pyi b/mypy/typeshed/stdlib/http/cookiejar.pyi index 310ccee71bf8..a57c7c0fbe16 100644 --- a/mypy/typeshed/stdlib/http/cookiejar.pyi +++ b/mypy/typeshed/stdlib/http/cookiejar.pyi @@ -16,7 +16,7 @@ class CookieJar(Iterable[Cookie]): def make_cookies(self, response: HTTPResponse, request: Request) -> Sequence[Cookie]: ... def set_cookie(self, cookie: Cookie) -> None: ... def set_cookie_if_ok(self, cookie: Cookie, request: Request) -> None: ... - def clear(self, domain: str = ..., path: str = ..., name: str = ...) -> None: ... + def clear(self, domain: Optional[str] = ..., path: Optional[str] = ..., name: Optional[str] = ...) -> None: ... def clear_session_cookies(self) -> None: ... def __iter__(self) -> Iterator[Cookie]: ... def __len__(self) -> int: ... @@ -26,10 +26,12 @@ class FileCookieJar(CookieJar): delayload: bool if sys.version_info >= (3, 8): def __init__( - self, filename: Union[str, PathLike[str]] = ..., delayload: bool = ..., policy: Optional[CookiePolicy] = ... + self, filename: Optional[Union[str, PathLike[str]]] = ..., delayload: bool = ..., policy: Optional[CookiePolicy] = ... ) -> None: ... else: - def __init__(self, filename: str = ..., delayload: bool = ..., policy: Optional[CookiePolicy] = ...) -> None: ... + def __init__( + self, filename: Optional[str] = ..., delayload: bool = ..., policy: Optional[CookiePolicy] = ... + ) -> None: ... def save(self, filename: Optional[str] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...) -> None: ... def load(self, filename: Optional[str] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...) -> None: ... def revert(self, filename: Optional[str] = ..., ignore_discard: bool = ..., ignore_expires: bool = ...) -> None: ... @@ -126,4 +128,4 @@ class Cookie: @overload def get_nonstandard_attr(self, name: str, default: _T) -> Union[str, _T]: ... def set_nonstandard_attr(self, name: str, value: str) -> None: ... - def is_expired(self, now: int = ...) -> bool: ... + def is_expired(self, now: Optional[int] = ...) -> bool: ... diff --git a/mypy/typeshed/stdlib/http/cookies.pyi b/mypy/typeshed/stdlib/http/cookies.pyi index 14b0f817e8b7..18dfdb9aa3ce 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, List, Mapping, Optional, TypeVar, Union, overload +from typing import Any, Dict, Generic, Iterable, List, Mapping, Optional, Tuple, TypeVar, Union, overload _DataType = Union[str, Mapping[str, Union[str, Morsel[Any]]]] _T = TypeVar("_T") @@ -18,10 +18,17 @@ class Morsel(Dict[str, Any], Generic[_T]): value: str coded_value: _T key: str + def __init__(self) -> None: ... if sys.version_info >= (3, 7): def set(self, key: str, val: str, coded_val: _T) -> None: ... else: def set(self, key: str, val: str, coded_val: _T, LegalChars: str = ...) -> None: ... + def setdefault(self, key: str, val: Optional[str] = ...) -> str: ... + # The dict update can also get a keywords argument so this is incompatible + @overload # type: ignore + def update(self, values: Mapping[str, str]) -> None: ... + @overload + def update(self, values: Iterable[Tuple[str, str]]) -> None: ... def isReservedKey(self, K: str) -> bool: ... def output(self, attrs: Optional[List[str]] = ..., header: str = ...) -> str: ... def js_output(self, attrs: Optional[List[str]] = ...) -> str: ... diff --git a/mypy/typeshed/stdlib/http/server.pyi b/mypy/typeshed/stdlib/http/server.pyi index 995a089add96..7d61bc4d2e9d 100644 --- a/mypy/typeshed/stdlib/http/server.pyi +++ b/mypy/typeshed/stdlib/http/server.pyi @@ -1,7 +1,7 @@ import email.message import socketserver import sys -from typing import Any, Callable, ClassVar, Dict, List, Mapping, Optional, Sequence, Tuple, Union +from typing import Any, ClassVar, Dict, List, Mapping, Optional, Sequence, Tuple, Union if sys.version_info >= (3, 7): from builtins import _PathLike @@ -9,7 +9,6 @@ if sys.version_info >= (3, 7): class HTTPServer(socketserver.TCPServer): server_name: str server_port: int - def __init__(self, server_address: Tuple[str, int], RequestHandlerClass: Callable[..., BaseHTTPRequestHandler]) -> None: ... if sys.version_info >= (3, 7): class ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): diff --git a/mypy/typeshed/stdlib/importlib/abc.pyi b/mypy/typeshed/stdlib/importlib/abc.pyi index 0949d317cd86..8915b28591da 100644 --- a/mypy/typeshed/stdlib/importlib/abc.pyi +++ b/mypy/typeshed/stdlib/importlib/abc.pyi @@ -58,7 +58,8 @@ class FileLoader(ResourceLoader, ExecutionLoader, metaclass=ABCMeta): path: _Path def __init__(self, fullname: str, path: _Path) -> None: ... def get_data(self, path: _Path) -> bytes: ... - def get_filename(self, fullname: str) -> _Path: ... + def get_filename(self, name: Optional[str] = ...) -> _Path: ... + def load_module(self, name: Optional[str] = ...) -> types.ModuleType: ... if sys.version_info >= (3, 7): _PathLike = Union[bytes, str, os.PathLike[Any]] @@ -87,9 +88,9 @@ if sys.version_info >= (3, 9): @abstractmethod def is_file(self) -> bool: ... @abstractmethod - def joinpath(self, child: Traversable) -> Traversable: ... + def joinpath(self, child: _Path) -> Traversable: ... @abstractmethod - def __truediv__(self, child: Traversable) -> Traversable: ... + def __truediv__(self, child: _Path) -> Traversable: ... @abstractmethod def open(self, mode: Literal["r", "rb"] = ..., *args: Any, **kwargs: Any) -> IO[Any]: ... @property diff --git a/mypy/typeshed/stdlib/importlib/machinery.pyi b/mypy/typeshed/stdlib/importlib/machinery.pyi index 9d0333a2b669..31ffdf7a431e 100644 --- a/mypy/typeshed/stdlib/importlib/machinery.pyi +++ b/mypy/typeshed/stdlib/importlib/machinery.pyi @@ -9,10 +9,12 @@ from _importlib_modulespec import Loader, ModuleSpec as ModuleSpec # Exported class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): # MetaPathFinder @classmethod - def find_module(cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]]) -> Optional[importlib.abc.Loader]: ... + def find_module( + cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]] = ... + ) -> Optional[importlib.abc.Loader]: ... @classmethod def find_spec( - cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]], target: Optional[types.ModuleType] = ... + cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]] = ..., target: Optional[types.ModuleType] = ... ) -> Optional[ModuleSpec]: ... # InspectLoader @classmethod @@ -34,10 +36,12 @@ class BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader) class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): # MetaPathFinder @classmethod - def find_module(cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]]) -> Optional[importlib.abc.Loader]: ... + def find_module( + cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]] = ... + ) -> Optional[importlib.abc.Loader]: ... @classmethod def find_spec( - cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]], target: Optional[types.ModuleType] = ... + cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]] = ..., target: Optional[types.ModuleType] = ... ) -> Optional[ModuleSpec]: ... # InspectLoader @classmethod @@ -50,7 +54,7 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): def get_source(cls, fullname: str) -> None: ... # Loader @staticmethod - def module_repr(module: types.ModuleType) -> str: ... + def module_repr(m: types.ModuleType) -> str: ... @classmethod def create_module(cls, spec: ModuleSpec) -> Optional[types.ModuleType]: ... @staticmethod @@ -58,10 +62,12 @@ class FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader): class WindowsRegistryFinder(importlib.abc.MetaPathFinder): @classmethod - def find_module(cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]]) -> Optional[importlib.abc.Loader]: ... + def find_module( + cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]] = ... + ) -> Optional[importlib.abc.Loader]: ... @classmethod def find_spec( - cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]], target: Optional[types.ModuleType] = ... + cls, fullname: str, path: Optional[Sequence[importlib.abc._Path]] = ..., target: Optional[types.ModuleType] = ... ) -> Optional[ModuleSpec]: ... class PathFinder: @@ -90,9 +96,12 @@ 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): + def set_data(self, path: importlib.abc._Path, data: bytes, *, _mode: int = ...) -> None: ... + class SourcelessFileLoader(importlib.abc.FileLoader, importlib.abc.SourceLoader): ... class ExtensionFileLoader(importlib.abc.ExecutionLoader): - def get_filename(self, fullname: str) -> importlib.abc._Path: ... + def __init__(self, name: str, path: importlib.abc._Path) -> None: ... + def get_filename(self, name: Optional[str] = ...) -> importlib.abc._Path: ... def get_source(self, fullname: str) -> None: ... diff --git a/mypy/typeshed/stdlib/importlib/metadata.pyi b/mypy/typeshed/stdlib/importlib/metadata.pyi index bc50c38d30f2..ae39c89b542a 100644 --- a/mypy/typeshed/stdlib/importlib/metadata.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata.pyi @@ -9,11 +9,11 @@ from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Tuple, Union if sys.version_info >= (3, 8): class PackageNotFoundError(ModuleNotFoundError): ... - class EntryPointBase(NamedTuple): + class _EntryPointBase(NamedTuple): name: str value: str group: str - class EntryPoint(EntryPointBase): + class EntryPoint(_EntryPointBase): def load(self) -> Any: ... # Callable[[], Any] or an importable module @property def extras(self) -> List[str]: ... @@ -62,8 +62,6 @@ if sys.version_info >= (3, 8): def __init__(self, *, name: Optional[str] = ..., path: List[str] = ..., **kwargs: Any) -> None: ... @property def path(self) -> List[str]: ... - @property - def pattern(self) -> str: ... @abc.abstractmethod def find_distributions(self, context: DistributionFinder.Context = ...) -> Iterable[Distribution]: ... class MetadataPathFinder(DistributionFinder): diff --git a/mypy/typeshed/stdlib/importlib/resources.pyi b/mypy/typeshed/stdlib/importlib/resources.pyi index 65beccba8cfd..075761abf9da 100644 --- a/mypy/typeshed/stdlib/importlib/resources.pyi +++ b/mypy/typeshed/stdlib/importlib/resources.pyi @@ -1,4 +1,5 @@ import sys +from typing import Any # This is a >=3.7 module, so we conditionally include its source. if sys.version_info >= (3, 7): @@ -8,7 +9,7 @@ if sys.version_info >= (3, 7): from typing import BinaryIO, ContextManager, Iterator, TextIO, Union Package = Union[str, ModuleType] - Resource = Union[str, os.PathLike] + 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: ... @@ -18,5 +19,7 @@ if sys.version_info >= (3, 7): def contents(package: Package) -> Iterator[str]: ... if sys.version_info >= (3, 9): + from contextlib import AbstractContextManager from importlib.abc import Traversable def files(package: Package) -> Traversable: ... + def as_file(path: Traversable) -> AbstractContextManager[Path]: ... diff --git a/mypy/typeshed/stdlib/importlib/util.pyi b/mypy/typeshed/stdlib/importlib/util.pyi index e586f99b9875..e2fdcb32cc98 100644 --- a/mypy/typeshed/stdlib/importlib/util.pyi +++ b/mypy/typeshed/stdlib/importlib/util.pyi @@ -20,16 +20,15 @@ def spec_from_loader( loader: Optional[importlib.abc.Loader], *, origin: Optional[str] = ..., - loader_state: Optional[Any] = ..., is_package: Optional[bool] = ..., -) -> importlib.machinery.ModuleSpec: ... +) -> Optional[importlib.machinery.ModuleSpec]: ... def spec_from_file_location( name: str, - location: Union[str, bytes, os.PathLike[str], os.PathLike[bytes]], + location: Optional[Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]] = ..., *, loader: Optional[importlib.abc.Loader] = ..., submodule_search_locations: Optional[List[str]] = ..., -) -> importlib.machinery.ModuleSpec: ... +) -> Optional[importlib.machinery.ModuleSpec]: ... def module_from_spec(spec: importlib.machinery.ModuleSpec) -> types.ModuleType: ... class LazyLoader(importlib.abc.Loader): diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index aef3aac78635..4ae9bac0e21e 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -1,111 +1,198 @@ import sys -from typing import Any, Callable, Generic, Iterable, Iterator, Optional, Tuple, TypeVar, overload -from typing_extensions import Literal +from _typeshed import _T_co +from typing import ( + Any, + Callable, + Generic, + Iterable, + Iterator, + Optional, + SupportsComplex, + SupportsFloat, + SupportsInt, + Tuple, + Type, + TypeVar, + overload, +) +from typing_extensions import Literal, SupportsIndex _T = TypeVar("_T") _S = TypeVar("_S") -_N = TypeVar("_N", int, float) +_N = TypeVar("_N", int, float, SupportsFloat, SupportsInt, SupportsIndex, SupportsComplex) +_NStep = TypeVar("_NStep", int, float, SupportsFloat, SupportsInt, SupportsIndex, SupportsComplex) + Predicate = Callable[[_T], object] -def count(start: _N = ..., step: _N = ...) -> Iterator[_N]: ... # more general types? +# Technically count can take anything that implements a number protocol and has an add method +# but we can't enforce the add method +class count(Iterator[_N], Generic[_N]): + @overload + def __new__(cls) -> count[int]: ... + @overload + def __new__(cls, start: _N, step: _NStep = ...) -> count[_N]: ... + def __next__(self) -> _N: ... + def __iter__(self) -> Iterator[_N]: ... class cycle(Iterator[_T], Generic[_T]): def __init__(self, __iterable: Iterable[_T]) -> None: ... def __next__(self) -> _T: ... def __iter__(self) -> Iterator[_T]: ... -@overload -def repeat(object: _T) -> Iterator[_T]: ... -@overload -def repeat(object: _T, times: int) -> Iterator[_T]: ... - -if sys.version_info >= (3, 8): +class repeat(Iterator[_T], Generic[_T]): @overload - def accumulate(iterable: Iterable[_T], func: None = ..., *, initial: Optional[_T] = ...) -> Iterator[_T]: ... + def __init__(self, object: _T) -> None: ... @overload - def accumulate(iterable: Iterable[_T], func: Callable[[_S, _T], _S], *, initial: Optional[_S] = ...) -> Iterator[_S]: ... + def __init__(self, object: _T, times: int) -> None: ... + def __next__(self) -> _T: ... + def __iter__(self) -> Iterator[_T]: ... -else: - def accumulate(iterable: Iterable[_T], func: Optional[Callable[[_T, _T], _T]] = ...) -> Iterator[_T]: ... +class accumulate(Iterator[_T], Generic[_T]): + if sys.version_info >= (3, 8): + @overload + def __init__(self, iterable: Iterable[_T], func: None = ..., *, initial: Optional[_T] = ...) -> None: ... + @overload + def __init__(self, iterable: Iterable[_S], func: Callable[[_T, _S], _T], *, initial: Optional[_T] = ...) -> None: ... + else: + def __init__(self, iterable: Iterable[_T], func: Optional[Callable[[_T, _T], _T]] = ...) -> None: ... + def __iter__(self) -> Iterator[_T]: ... + def __next__(self) -> _T: ... class chain(Iterator[_T], Generic[_T]): def __init__(self, *iterables: Iterable[_T]) -> None: ... def __next__(self) -> _T: ... def __iter__(self) -> Iterator[_T]: ... - @staticmethod - def from_iterable(__iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... - -def compress(data: Iterable[_T], selectors: Iterable[Any]) -> Iterator[_T]: ... -def dropwhile(__predicate: Predicate[_T], __iterable: Iterable[_T]) -> Iterator[_T]: ... -def filterfalse(__predicate: Optional[Predicate[_T]], __iterable: Iterable[_T]) -> Iterator[_T]: ... -@overload -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]]]: ... -@overload -def islice(__iterable: Iterable[_T], __stop: Optional[int]) -> Iterator[_T]: ... -@overload -def islice( - __iterable: Iterable[_T], __start: Optional[int], __stop: Optional[int], __step: Optional[int] = ... -) -> Iterator[_T]: ... -def starmap(__function: Callable[..., _S], __iterable: Iterable[Iterable[Any]]) -> Iterator[_S]: ... -def takewhile(__predicate: Predicate[_T], __iterable: Iterable[_T]) -> Iterator[_T]: ... -def tee(__iterable: Iterable[_T], __n: int = ...) -> Tuple[Iterator[_T], ...]: ... -def zip_longest(*p: Iterable[Any], fillvalue: Any = ...) -> Iterator[Any]: ... + @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]: ... + +class compress(Iterator[_T], Generic[_T]): + def __init__(self, data: Iterable[_T], selectors: Iterable[Any]) -> None: ... + def __iter__(self) -> Iterator[_T]: ... + def __next__(self) -> _T: ... + +class dropwhile(Iterator[_T], Generic[_T]): + def __init__(self, __predicate: Predicate[_T], __iterable: Iterable[_T]) -> None: ... + def __iter__(self) -> Iterator[_T]: ... + def __next__(self) -> _T: ... + +class filterfalse(Iterator[_T], Generic[_T]): + def __init__(self, __predicate: Optional[Predicate[_T]], __iterable: Iterable[_T]) -> None: ... + def __iter__(self) -> Iterator[_T]: ... + def __next__(self) -> _T: ... _T1 = TypeVar("_T1") _T2 = TypeVar("_T2") + +class groupby(Iterator[Tuple[_T, Iterator[_S]]], Generic[_T, _S]): + @overload + def __new__(cls, iterable: Iterable[_T1], key: None = ...) -> groupby[_T1, _T1]: ... + @overload + def __new__(cls, iterable: Iterable[_T1], key: Callable[[_T1], _T2]) -> groupby[_T2, _T1]: ... + def __iter__(self) -> Iterator[Tuple[_T, Iterator[_S]]]: ... + def __next__(self) -> Tuple[_T, Iterator[_S]]: ... + +class islice(Iterator[_T], Generic[_T]): + @overload + def __init__(self, __iterable: Iterable[_T], __stop: Optional[int]) -> None: ... + @overload + def __init__( + self, __iterable: Iterable[_T], __start: Optional[int], __stop: Optional[int], __step: Optional[int] = ... + ) -> None: ... + def __iter__(self) -> Iterator[_T]: ... + def __next__(self) -> _T: ... + +class starmap(Iterator[_T], Generic[_T]): + def __init__(self, __function: Callable[..., _T], __iterable: Iterable[Iterable[Any]]) -> None: ... + def __iter__(self) -> Iterator[_T]: ... + def __next__(self) -> _T: ... + +class takewhile(Iterator[_T], Generic[_T]): + def __init__(self, __predicate: Predicate[_T], __iterable: Iterable[_T]) -> None: ... + def __iter__(self) -> Iterator[_T]: ... + def __next__(self) -> _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: ... + def __iter__(self) -> Iterator[Any]: ... + def __next__(self) -> Any: ... + _T3 = TypeVar("_T3") _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") _T6 = TypeVar("_T6") -@overload -def product(__iter1: Iterable[_T1]) -> Iterator[Tuple[_T1]]: ... -@overload -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]]: ... -@overload -def product( - __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_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]]: ... -@overload -def product( - __iter1: Iterable[_T1], - __iter2: Iterable[_T2], - __iter3: Iterable[_T3], - __iter4: Iterable[_T4], - __iter5: Iterable[_T5], - __iter6: Iterable[_T6], -) -> Iterator[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... -@overload -def product( - __iter1: Iterable[Any], - __iter2: Iterable[Any], - __iter3: Iterable[Any], - __iter4: Iterable[Any], - __iter5: Iterable[Any], - __iter6: Iterable[Any], - __iter7: Iterable[Any], - *iterables: Iterable[Any], -) -> Iterator[Tuple[Any, ...]]: ... -@overload -def product(*iterables: Iterable[_T1], repeat: int) -> Iterator[Tuple[_T1, ...]]: ... -@overload -def product(*iterables: Iterable[Any], repeat: int = ...) -> Iterator[Tuple[Any, ...]]: ... -def permutations(iterable: Iterable[_T], r: Optional[int] = ...) -> Iterator[Tuple[_T, ...]]: ... -@overload -def combinations(iterable: Iterable[_T], r: Literal[2]) -> Iterator[Tuple[_T, _T]]: ... -@overload -def combinations(iterable: Iterable[_T], r: Literal[3]) -> Iterator[Tuple[_T, _T, _T]]: ... -@overload -def combinations(iterable: Iterable[_T], r: Literal[4]) -> Iterator[Tuple[_T, _T, _T, _T]]: ... -@overload -def combinations(iterable: Iterable[_T], r: Literal[5]) -> Iterator[Tuple[_T, _T, _T, _T, _T]]: ... -@overload -def combinations(iterable: Iterable[_T], r: int) -> Iterator[Tuple[_T, ...]]: ... -def combinations_with_replacement(iterable: Iterable[_T], r: int) -> Iterator[Tuple[_T, ...]]: ... + +class product(Iterator[_T_co], Generic[_T_co]): + @overload + def __new__(cls, __iter1: Iterable[_T1]) -> product[Tuple[_T1]]: ... + @overload + def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2]) -> product[Tuple[_T1, _T2]]: ... + @overload + def __new__(cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3]) -> product[Tuple[_T1, _T2, _T3]]: ... + @overload + def __new__( + cls, __iter1: Iterable[_T1], __iter2: Iterable[_T2], __iter3: Iterable[_T3], __iter4: Iterable[_T4] + ) -> product[Tuple[_T1, _T2, _T3, _T4]]: ... + @overload + def __new__( + cls, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5], + ) -> product[Tuple[_T1, _T2, _T3, _T4, _T5]]: ... + @overload + def __new__( + cls, + __iter1: Iterable[_T1], + __iter2: Iterable[_T2], + __iter3: Iterable[_T3], + __iter4: Iterable[_T4], + __iter5: Iterable[_T5], + __iter6: Iterable[_T6], + ) -> product[Tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ... + @overload + def __new__( + cls, + __iter1: Iterable[Any], + __iter2: Iterable[Any], + __iter3: Iterable[Any], + __iter4: Iterable[Any], + __iter5: Iterable[Any], + __iter6: Iterable[Any], + __iter7: Iterable[Any], + *iterables: Iterable[Any], + ) -> product[Tuple[Any, ...]]: ... + @overload + def __new__(cls, *iterables: Iterable[_T1], repeat: int) -> product[Tuple[_T1, ...]]: ... + @overload + 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]): + def __init__(self, iterable: Iterable[_T], r: Optional[int] = ...) -> None: ... + def __iter__(self) -> Iterator[Tuple[_T, ...]]: ... + def __next__(self) -> Tuple[_T, ...]: ... + +class combinations(Iterator[_T_co], Generic[_T_co]): + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations[Tuple[_T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[3]) -> combinations[Tuple[_T, _T, _T]]: ... + @overload + def __new__(cls, iterable: Iterable[_T], r: Literal[4]) -> combinations[Tuple[_T, _T, _T, _T]]: ... + @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 __iter__(self) -> Iterator[_T_co]: ... + def __next__(self) -> _T_co: ... + +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, ...]: ... diff --git a/mypy/typeshed/stdlib/json/__init__.pyi b/mypy/typeshed/stdlib/json/__init__.pyi index 69c82a9c6cd1..7b7a89ae20e2 100644 --- a/mypy/typeshed/stdlib/json/__init__.pyi +++ b/mypy/typeshed/stdlib/json/__init__.pyi @@ -55,3 +55,4 @@ def load( object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]] = ..., **kwds: Any, ) -> Any: ... +def detect_encoding(b: bytes) -> str: ... # undocumented diff --git a/mypy/typeshed/stdlib/locale.pyi b/mypy/typeshed/stdlib/locale.pyi index c5e25c95aa09..920c006cda01 100644 --- a/mypy/typeshed/stdlib/locale.pyi +++ b/mypy/typeshed/stdlib/locale.pyi @@ -3,10 +3,10 @@ from decimal import Decimal from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple, Union # workaround for mypy#2010 -if sys.version_info < (3,): - from __builtin__ import str as _str -else: +if sys.version_info >= (3, 0): from builtins import str as _str +else: + from __builtin__ import str as _str CODESET: int D_T_FMT: int diff --git a/mypy/typeshed/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index 865c527ac844..59822ab3c66e 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -1,34 +1,17 @@ import sys import threading -from _typeshed import StrPath +from _typeshed import StrPath, SupportsWrite +from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence from string import Template from time import struct_time from types import FrameType, TracebackType -from typing import ( - IO, - Any, - Callable, - Dict, - Iterable, - List, - Mapping, - MutableMapping, - Optional, - Sequence, - Text, - Tuple, - Union, - overload, -) +from typing import IO, Any, ClassVar, Optional, Tuple, Type, Union _SysExcInfoType = Union[Tuple[type, BaseException, Optional[TracebackType]], Tuple[None, None, None]] -if sys.version_info >= (3, 5): - _ExcInfoType = Union[None, bool, _SysExcInfoType, BaseException] -else: - _ExcInfoType = Union[None, bool, _SysExcInfoType] +_ExcInfoType = Union[None, bool, _SysExcInfoType, BaseException] _ArgsType = Union[Tuple[Any, ...], Mapping[str, Any]] _FilterType = Union[Filter, Callable[[LogRecord], int]] -_Level = Union[int, Text] +_Level = Union[int, str] raiseExceptions: bool logThreads: bool @@ -38,26 +21,37 @@ _srcfile: Optional[str] def currentframe() -> FrameType: ... -if sys.version_info >= (3,): - _levelToName: Dict[int, str] - _nameToLevel: Dict[str, int] -else: - _levelNames: Dict[Union[int, str], Union[str, int]] # Union[int:str, str:int] +_levelToName: dict[int, str] +_nameToLevel: dict[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: ... def filter(self, record: LogRecord) -> bool: ... +class Manager(object): + root: RootLogger + disable: int + emittedNoHandlerWarning: bool + loggerDict: dict[str, Union[Logger, PlaceHolder]] + loggerClass: Optional[Type[Logger]] + logRecordFactory: Optional[Callable[..., LogRecord]] + def __init__(self, rootnode: RootLogger) -> None: ... + def getLogger(self, name: str) -> Logger: ... + def setLoggerClass(self, klass: Type[Logger]) -> None: ... + def setLogRecordFactory(self, factory: Callable[..., LogRecord]) -> None: ... + class Logger(Filterer): name: str level: int parent: Union[Logger, PlaceHolder] propagate: bool - handlers: List[Handler] + handlers: list[Handler] disabled: int + root: ClassVar[RootLogger] # undocumented + manager: ClassVar[Manager] # undocumented def __init__(self, name: str, level: _Level = ...) -> None: ... def setLevel(self, level: _Level) -> None: ... def isEnabledFor(self, level: int) -> bool: ... @@ -71,7 +65,7 @@ class Logger(Filterer): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def info( @@ -81,7 +75,7 @@ class Logger(Filterer): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def warning( @@ -91,7 +85,7 @@ class Logger(Filterer): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def warn( @@ -101,7 +95,7 @@ class Logger(Filterer): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def error( @@ -111,7 +105,7 @@ class Logger(Filterer): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def exception( @@ -121,7 +115,7 @@ class Logger(Filterer): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def critical( @@ -131,7 +125,7 @@ class Logger(Filterer): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def log( @@ -142,7 +136,7 @@ class Logger(Filterer): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def _log( @@ -151,18 +145,18 @@ class Logger(Filterer): msg: Any, args: _ArgsType, exc_info: Optional[_ExcInfoType] = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., stack_info: bool = ..., stacklevel: int = ..., ) -> None: ... # undocumented - elif sys.version_info >= (3,): + else: def debug( self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def info( @@ -171,7 +165,7 @@ class Logger(Filterer): *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def warning( @@ -180,7 +174,7 @@ class Logger(Filterer): *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def warn( @@ -189,7 +183,7 @@ class Logger(Filterer): *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def error( @@ -198,7 +192,7 @@ class Logger(Filterer): *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def critical( @@ -207,7 +201,7 @@ class Logger(Filterer): *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... fatal = critical @@ -218,7 +212,7 @@ class Logger(Filterer): *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def exception( @@ -227,7 +221,7 @@ class Logger(Filterer): *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def _log( @@ -236,86 +230,31 @@ class Logger(Filterer): msg: Any, args: _ArgsType, exc_info: Optional[_ExcInfoType] = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., stack_info: bool = ..., ) -> None: ... # undocumented - else: - def debug( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def info( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def warning( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - warn = warning - def error( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def critical( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - fatal = critical - def log( - self, - level: int, - msg: Any, - *args: Any, - exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any, - ) -> None: ... - def exception( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def _log( - self, - level: int, - msg: Any, - args: _ArgsType, - exc_info: Optional[_ExcInfoType] = ..., - extra: Optional[Dict[str, Any]] = ..., - ) -> None: ... # undocumented def filter(self, record: LogRecord) -> bool: ... def addHandler(self, hdlr: Handler) -> None: ... def removeHandler(self, hdlr: Handler) -> None: ... if sys.version_info >= (3, 8): - def findCaller(self, stack_info: bool = ..., stacklevel: int = ...) -> Tuple[str, int, str, Optional[str]]: ... - elif sys.version_info >= (3,): - def findCaller(self, stack_info: bool = ...) -> Tuple[str, int, str, Optional[str]]: ... + def findCaller(self, stack_info: bool = ..., stacklevel: int = ...) -> tuple[str, int, str, Optional[str]]: ... else: - def findCaller(self) -> Tuple[str, int, str]: ... + def findCaller(self, stack_info: bool = ...) -> tuple[str, int, str, Optional[str]]: ... def handle(self, record: LogRecord) -> None: ... - if sys.version_info >= (3,): - def makeRecord( - self, - name: str, - level: int, - fn: str, - lno: int, - msg: Any, - args: _ArgsType, - exc_info: Optional[_SysExcInfoType], - func: Optional[str] = ..., - extra: Optional[Mapping[str, Any]] = ..., - sinfo: Optional[str] = ..., - ) -> LogRecord: ... - else: - def makeRecord( - self, - name: str, - level: int, - fn: str, - lno: int, - msg: Any, - args: _ArgsType, - exc_info: Optional[_SysExcInfoType], - func: Optional[str] = ..., - extra: Optional[Mapping[str, Any]] = ..., - ) -> LogRecord: ... - if sys.version_info >= (3,): - def hasHandlers(self) -> bool: ... + def makeRecord( + self, + name: str, + level: int, + fn: str, + lno: int, + msg: Any, + args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ..., + extra: Optional[Mapping[str, Any]] = ..., + sinfo: Optional[str] = ..., + ) -> LogRecord: ... + def hasHandlers(self) -> bool: ... CRITICAL: int FATAL: int @@ -349,25 +288,21 @@ class Formatter: converter: Callable[[Optional[float]], struct_time] _fmt: Optional[str] datefmt: Optional[str] - if sys.version_info >= (3,): - _style: PercentStyle - default_time_format: str - default_msec_format: str + _style: PercentStyle + default_time_format: str + default_msec_format: str if sys.version_info >= (3, 8): def __init__( self, fmt: Optional[str] = ..., datefmt: Optional[str] = ..., style: str = ..., validate: bool = ... ) -> None: ... - elif sys.version_info >= (3,): - def __init__(self, fmt: Optional[str] = ..., datefmt: Optional[str] = ..., style: str = ...) -> None: ... else: - def __init__(self, fmt: Optional[str] = ..., datefmt: Optional[str] = ...) -> None: ... + def __init__(self, fmt: Optional[str] = ..., datefmt: Optional[str] = ..., style: str = ...) -> None: ... def format(self, record: LogRecord) -> str: ... def formatTime(self, record: LogRecord, datefmt: Optional[str] = ...) -> str: ... def formatException(self, ei: _SysExcInfoType) -> str: ... - if sys.version_info >= (3,): - def formatMessage(self, record: LogRecord) -> str: ... # undocumented - def formatStack(self, stack_info: str) -> str: ... + def formatMessage(self, record: LogRecord) -> str: ... # undocumented + def formatStack(self, stack_info: str) -> str: ... class Filter: def __init__(self, name: str = ...) -> None: ... @@ -393,42 +328,28 @@ class LogRecord: process: int processName: str relativeCreated: int - if sys.version_info >= (3,): - stack_info: Optional[str] + stack_info: Optional[str] thread: int threadName: str - if sys.version_info >= (3,): - def __init__( - self, - name: str, - level: int, - pathname: str, - lineno: int, - msg: Any, - args: _ArgsType, - exc_info: Optional[_SysExcInfoType], - func: Optional[str] = ..., - sinfo: Optional[str] = ..., - ) -> None: ... - else: - def __init__( - self, - name: str, - level: int, - pathname: str, - lineno: int, - msg: Any, - args: _ArgsType, - exc_info: Optional[_SysExcInfoType], - func: Optional[str] = ..., - ) -> None: ... + def __init__( + self, + name: str, + level: int, + pathname: str, + lineno: int, + msg: Any, + args: _ArgsType, + exc_info: Optional[_SysExcInfoType], + func: Optional[str] = ..., + sinfo: Optional[str] = ..., + ) -> None: ... def getMessage(self) -> str: ... class LoggerAdapter: logger: Logger extra: Mapping[str, Any] def __init__(self, logger: Logger, 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]]: ... if sys.version_info >= (3, 8): def debug( self, @@ -437,7 +358,7 @@ class LoggerAdapter: exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def info( @@ -447,7 +368,7 @@ class LoggerAdapter: exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def warning( @@ -457,7 +378,7 @@ class LoggerAdapter: exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def warn( @@ -467,7 +388,7 @@ class LoggerAdapter: exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def error( @@ -477,7 +398,7 @@ class LoggerAdapter: exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def exception( @@ -487,7 +408,7 @@ class LoggerAdapter: exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def critical( @@ -497,7 +418,7 @@ class LoggerAdapter: exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def log( @@ -508,17 +429,17 @@ class LoggerAdapter: exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... - elif sys.version_info >= (3,): + else: def debug( self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def info( @@ -527,7 +448,7 @@ class LoggerAdapter: *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def warning( @@ -536,7 +457,7 @@ class LoggerAdapter: *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def warn( @@ -545,7 +466,7 @@ class LoggerAdapter: *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def error( @@ -554,7 +475,7 @@ class LoggerAdapter: *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def exception( @@ -563,7 +484,7 @@ class LoggerAdapter: *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def critical( @@ -572,7 +493,7 @@ class LoggerAdapter: *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def log( @@ -582,66 +503,26 @@ class LoggerAdapter: *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., - **kwargs: Any, - ) -> None: ... - else: - def debug( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def info( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def warning( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def error( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def exception( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def critical( - self, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def log( - self, - level: int, - msg: Any, - *args: Any, - exc_info: _ExcInfoType = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def isEnabledFor(self, level: int) -> bool: ... - if sys.version_info >= (3,): - def getEffectiveLevel(self) -> int: ... - def setLevel(self, level: Union[int, str]) -> None: ... - def hasHandlers(self) -> bool: ... - if sys.version_info >= (3, 6): - def _log( - self, - level: int, - msg: Any, - args: _ArgsType, - exc_info: Optional[_ExcInfoType] = ..., - extra: Optional[Dict[str, Any]] = ..., - stack_info: bool = ..., - ) -> None: ... # undocumented - -if sys.version_info >= (3,): - def getLogger(name: Optional[str] = ...) -> Logger: ... - -else: - @overload - def getLogger() -> Logger: ... - @overload - def getLogger(name: Union[Text, str]) -> Logger: ... + def getEffectiveLevel(self) -> int: ... + def setLevel(self, level: Union[int, str]) -> None: ... + def hasHandlers(self) -> bool: ... + def _log( + self, + level: int, + msg: Any, + args: _ArgsType, + exc_info: Optional[_ExcInfoType] = ..., + extra: Optional[dict[str, Any]] = ..., + stack_info: bool = ..., + ) -> None: ... # undocumented +def getLogger(name: Optional[str] = ...) -> Logger: ... def getLoggerClass() -> type: ... - -if sys.version_info >= (3,): - def getLogRecordFactory() -> Callable[..., LogRecord]: ... +def getLogRecordFactory() -> Callable[..., LogRecord]: ... if sys.version_info >= (3, 8): def debug( @@ -650,7 +531,7 @@ if sys.version_info >= (3, 8): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def info( @@ -659,7 +540,7 @@ if sys.version_info >= (3, 8): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def warning( @@ -668,7 +549,7 @@ if sys.version_info >= (3, 8): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def warn( @@ -677,7 +558,7 @@ if sys.version_info >= (3, 8): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def error( @@ -686,7 +567,7 @@ if sys.version_info >= (3, 8): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def critical( @@ -695,7 +576,7 @@ if sys.version_info >= (3, 8): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def exception( @@ -704,7 +585,7 @@ if sys.version_info >= (3, 8): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def log( @@ -714,17 +595,17 @@ if sys.version_info >= (3, 8): exc_info: _ExcInfoType = ..., stack_info: bool = ..., stacklevel: int = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... -elif sys.version_info >= (3,): +else: def debug( msg: Any, *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def info( @@ -732,7 +613,7 @@ elif sys.version_info >= (3,): *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def warning( @@ -740,7 +621,7 @@ elif sys.version_info >= (3,): *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def warn( @@ -748,7 +629,7 @@ elif sys.version_info >= (3,): *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def error( @@ -756,7 +637,7 @@ elif sys.version_info >= (3,): *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def critical( @@ -764,7 +645,7 @@ elif sys.version_info >= (3,): *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def exception( @@ -772,7 +653,7 @@ elif sys.version_info >= (3,): *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... def log( @@ -781,34 +662,10 @@ elif sys.version_info >= (3,): *args: Any, exc_info: _ExcInfoType = ..., stack_info: bool = ..., - extra: Optional[Dict[str, Any]] = ..., + extra: Optional[dict[str, Any]] = ..., **kwargs: Any, ) -> None: ... -else: - def debug( - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def info( - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def warning( - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - warn = warning - def error( - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def critical( - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def exception( - msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - def log( - level: int, msg: Any, *args: Any, exc_info: _ExcInfoType = ..., extra: Optional[Dict[str, Any]] = ..., **kwargs: Any - ) -> None: ... - fatal = critical if sys.version_info >= (3, 7): @@ -830,12 +687,12 @@ if sys.version_info >= (3, 8): datefmt: Optional[str] = ..., style: str = ..., level: Optional[_Level] = ..., - stream: Optional[IO[str]] = ..., + stream: Optional[SupportsWrite[str]] = ..., handlers: Optional[Iterable[Handler]] = ..., force: bool = ..., ) -> None: ... -elif sys.version_info >= (3,): +else: def basicConfig( *, filename: Optional[StrPath] = ..., @@ -844,41 +701,23 @@ elif sys.version_info >= (3,): datefmt: Optional[str] = ..., style: str = ..., level: Optional[_Level] = ..., - stream: Optional[IO[str]] = ..., + stream: Optional[SupportsWrite[str]] = ..., handlers: Optional[Iterable[Handler]] = ..., ) -> None: ... -else: - @overload - def basicConfig() -> None: ... - @overload - def basicConfig( - *, - filename: Optional[str] = ..., - filemode: str = ..., - format: str = ..., - datefmt: Optional[str] = ..., - level: Optional[_Level] = ..., - stream: IO[str] = ..., - ) -> None: ... - def shutdown(handlerList: Sequence[Any] = ...) -> None: ... # handlerList is undocumented def setLoggerClass(klass: type) -> None: ... def captureWarnings(capture: bool) -> None: ... +def setLogRecordFactory(factory: Callable[..., LogRecord]) -> None: ... -if sys.version_info >= (3,): - def setLogRecordFactory(factory: Callable[..., LogRecord]) -> None: ... - -if sys.version_info >= (3,): - lastResort: Optional[StreamHandler] +lastResort: Optional[StreamHandler] class StreamHandler(Handler): - stream: IO[str] # undocumented - if sys.version_info >= (3, 2): - terminator: str - def __init__(self, stream: Optional[IO[str]] = ...) -> None: ... + stream: SupportsWrite[str] # undocumented + terminator: str + def __init__(self, stream: Optional[SupportsWrite[str]] = ...) -> None: ... if sys.version_info >= (3, 7): - def setStream(self, stream: IO[str]) -> Optional[IO[str]]: ... + def setStream(self, stream: SupportsWrite[str]) -> Optional[SupportsWrite[str]]: ... class FileHandler(StreamHandler): baseFilename: str # undocumented @@ -901,18 +740,20 @@ class RootLogger(Logger): root: RootLogger -if sys.version_info >= (3,): - class PercentStyle(object): - default_format: str - asctime_format: str - asctime_search: str - _fmt: str - def __init__(self, fmt: str) -> None: ... - def usesTime(self) -> bool: ... - def format(self, record: Any) -> str: ... - class StrFormatStyle(PercentStyle): ... - class StringTemplateStyle(PercentStyle): - _tpl: Template - _STYLES: Dict[str, Tuple[PercentStyle, str]] +class PercentStyle(object): + default_format: str + asctime_format: str + asctime_search: str + _fmt: str + def __init__(self, fmt: str) -> None: ... + def usesTime(self) -> bool: ... + def format(self, record: Any) -> str: ... + +class StrFormatStyle(PercentStyle): ... + +class StringTemplateStyle(PercentStyle): + _tpl: Template + +_STYLES: dict[str, tuple[PercentStyle, str]] BASIC_FORMAT: str diff --git a/mypy/typeshed/stdlib/logging/config.pyi b/mypy/typeshed/stdlib/logging/config.pyi index 535d583d759a..89fa555faa8f 100644 --- a/mypy/typeshed/stdlib/logging/config.pyi +++ b/mypy/typeshed/stdlib/logging/config.pyi @@ -1,32 +1,20 @@ import sys from _typeshed import AnyPath, StrPath +from collections.abc import Callable +from configparser import RawConfigParser from threading import Thread -from typing import IO, Any, Callable, Dict, Optional, Union - -if sys.version_info >= (3,): - from configparser import RawConfigParser -else: - from ConfigParser import RawConfigParser +from typing import IO, Any, Optional, Union if sys.version_info >= (3, 7): _Path = AnyPath else: _Path = StrPath -def dictConfig(config: Dict[str, Any]) -> None: ... - -if sys.version_info >= (3, 4): - def fileConfig( - fname: Union[_Path, IO[str], RawConfigParser], - defaults: Optional[Dict[str, str]] = ..., - disable_existing_loggers: bool = ..., - ) -> None: ... - def listen(port: int = ..., verify: Optional[Callable[[bytes], Optional[bytes]]] = ...) -> Thread: ... - -else: - def fileConfig( - fname: Union[str, IO[str]], defaults: Optional[Dict[str, str]] = ..., disable_existing_loggers: bool = ... - ) -> None: ... - def listen(port: int = ...) -> Thread: ... - +def dictConfig(config: dict[str, Any]) -> None: ... +def fileConfig( + fname: Union[_Path, IO[str], RawConfigParser], + defaults: Optional[dict[str, str]] = ..., + disable_existing_loggers: bool = ..., +) -> None: ... +def listen(port: int = ..., verify: Optional[Callable[[bytes], Optional[bytes]]] = ...) -> Thread: ... def stopListening() -> None: ... diff --git a/mypy/typeshed/stdlib/logging/handlers.pyi b/mypy/typeshed/stdlib/logging/handlers.pyi index 3c726fc2a3c0..4c20d4af2b56 100644 --- a/mypy/typeshed/stdlib/logging/handlers.pyi +++ b/mypy/typeshed/stdlib/logging/handlers.pyi @@ -2,16 +2,15 @@ import datetime import ssl import sys from _typeshed import StrPath +from collections.abc import Callable from logging import FileHandler, Handler, LogRecord from socket import SocketKind, SocketType -from typing import Any, Callable, ClassVar, Dict, List, Optional, Tuple, Union +from typing import Any, ClassVar, Optional, Union if sys.version_info >= (3, 7): from queue import Queue, SimpleQueue -elif sys.version_info >= (3,): - from queue import Queue else: - from Queue import Queue + from queue import Queue DEFAULT_TCP_LOGGING_PORT: int DEFAULT_UDP_LOGGING_PORT: int @@ -26,90 +25,45 @@ class WatchedFileHandler(FileHandler): def __init__(self, filename: StrPath, mode: str = ..., encoding: Optional[str] = ..., delay: bool = ...) -> None: ... def _statstream(self) -> None: ... -if sys.version_info >= (3,): - class BaseRotatingHandler(FileHandler): - terminator: str - namer: Optional[Callable[[str], str]] - rotator: Optional[Callable[[str, str], None]] - def __init__(self, filename: StrPath, mode: str, encoding: Optional[str] = ..., delay: bool = ...) -> None: ... - def rotation_filename(self, default_name: str) -> None: ... - def rotate(self, source: str, dest: str) -> None: ... - -if sys.version_info >= (3,): - class RotatingFileHandler(BaseRotatingHandler): - def __init__( - self, - filename: StrPath, - mode: str = ..., - maxBytes: int = ..., - backupCount: int = ..., - encoding: Optional[str] = ..., - delay: bool = ..., - ) -> None: ... - def doRollover(self) -> None: ... - -else: - class RotatingFileHandler(Handler): - def __init__( - self, - filename: str, - mode: str = ..., - maxBytes: int = ..., - backupCount: int = ..., - encoding: Optional[str] = ..., - delay: bool = ..., - ) -> None: ... - def doRollover(self) -> None: ... +class BaseRotatingHandler(FileHandler): + terminator: str + namer: Optional[Callable[[str], str]] + rotator: Optional[Callable[[str, str], None]] + def __init__(self, filename: StrPath, mode: str, encoding: Optional[str] = ..., delay: bool = ...) -> None: ... + def rotation_filename(self, default_name: str) -> None: ... + def rotate(self, source: str, dest: str) -> None: ... -if sys.version_info >= (3,): - class TimedRotatingFileHandler(BaseRotatingHandler): - if sys.version_info >= (3, 4): - def __init__( - self, - filename: StrPath, - when: str = ..., - interval: int = ..., - backupCount: int = ..., - encoding: Optional[str] = ..., - delay: bool = ..., - utc: bool = ..., - atTime: Optional[datetime.datetime] = ..., - ) -> None: ... - else: - def __init__( - self, - filename: str, - when: str = ..., - interval: int = ..., - backupCount: int = ..., - encoding: Optional[str] = ..., - delay: bool = ..., - utc: bool = ..., - ) -> None: ... - def doRollover(self) -> None: ... +class RotatingFileHandler(BaseRotatingHandler): + def __init__( + self, + filename: StrPath, + mode: str = ..., + maxBytes: int = ..., + backupCount: int = ..., + encoding: Optional[str] = ..., + delay: bool = ..., + ) -> None: ... + def doRollover(self) -> None: ... -else: - class TimedRotatingFileHandler(Handler): - def __init__( - self, - filename: str, - when: str = ..., - interval: int = ..., - backupCount: int = ..., - encoding: Optional[str] = ..., - delay: bool = ..., - utc: bool = ..., - ) -> None: ... - def doRollover(self) -> None: ... +class TimedRotatingFileHandler(BaseRotatingHandler): + def __init__( + self, + filename: StrPath, + when: str = ..., + interval: int = ..., + backupCount: int = ..., + encoding: Optional[str] = ..., + delay: bool = ..., + utc: bool = ..., + atTime: Optional[datetime.datetime] = ..., + ) -> None: ... + def doRollover(self) -> None: ... class SocketHandler(Handler): retryStart: float retryFactor: float retryMax: float - if sys.version_info >= (3, 4): - def __init__(self, host: str, port: Optional[int]) -> None: ... - else: - def __init__(self, host: str, port: int) -> None: ... + def __init__(self, host: str, port: Optional[int]) -> None: ... def makeSocket(self, timeout: float = ...) -> SocketType: ... # timeout is undocumented def makePickle(self, record: LogRecord) -> bytes: ... def send(self, s: bytes) -> None: ... @@ -157,14 +111,13 @@ class SysLogHandler(Handler): LOG_LOCAL7: int unixsocket: bool # undocumented socktype: SocketKind # undocumented - if sys.version_info >= (3,): - ident: str # undocumented + ident: str # 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 + 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: Union[Tuple[str, int], str] = ..., facility: int = ..., socktype: Optional[SocketKind] = ... + self, address: Union[tuple[str, int], str] = ..., facility: int = ..., socktype: Optional[SocketKind] = ... ) -> None: ... def encodePriority(self, facility: Union[int, str], priority: Union[int, str]) -> int: ... def mapPriority(self, levelName: str) -> str: ... @@ -178,81 +131,58 @@ class NTEventLogHandler(Handler): class SMTPHandler(Handler): # TODO `secure` can also be an empty tuple - if sys.version_info >= (3,): - def __init__( - self, - mailhost: Union[str, Tuple[str, int]], - fromaddr: str, - toaddrs: List[str], - subject: str, - credentials: Optional[Tuple[str, str]] = ..., - secure: Union[Tuple[str], Tuple[str, str], None] = ..., - timeout: float = ..., - ) -> None: ... - else: - def __init__( - self, - mailhost: Union[str, Tuple[str, int]], - fromaddr: str, - toaddrs: List[str], - subject: str, - credentials: Optional[Tuple[str, str]] = ..., - secure: Union[Tuple[str], Tuple[str, str], None] = ..., - ) -> None: ... + def __init__( + self, + mailhost: Union[str, tuple[str, int]], + fromaddr: str, + toaddrs: list[str], + subject: str, + credentials: Optional[tuple[str, str]] = ..., + secure: Union[tuple[str], tuple[str, str], None] = ..., + timeout: float = ..., + ) -> 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: ... class MemoryHandler(BufferingHandler): - if sys.version_info >= (3, 6): - def __init__( - self, capacity: int, flushLevel: int = ..., target: Optional[Handler] = ..., flushOnClose: bool = ... - ) -> None: ... - else: - def __init__(self, capacity: int, flushLevel: int = ..., target: Optional[Handler] = ...) -> None: ... + def __init__( + self, capacity: int, flushLevel: int = ..., target: Optional[Handler] = ..., flushOnClose: bool = ... + ) -> None: ... def setTarget(self, target: Handler) -> None: ... class HTTPHandler(Handler): - if sys.version_info >= (3, 5): - def __init__( - self, - host: str, - url: str, - method: str = ..., - secure: bool = ..., - credentials: Optional[Tuple[str, str]] = ..., - context: Optional[ssl.SSLContext] = ..., - ) -> None: ... - elif sys.version_info >= (3,): + def __init__( + self, + host: str, + url: str, + method: str = ..., + secure: bool = ..., + credentials: Optional[tuple[str, str]] = ..., + context: Optional[ssl.SSLContext] = ..., + ) -> None: ... + def mapLogRecord(self, record: LogRecord) -> dict[str, Any]: ... + +class QueueHandler(Handler): + if sys.version_info >= (3, 7): + def __init__(self, queue: Union[SimpleQueue[Any], Queue[Any]]) -> None: ... + else: + def __init__(self, queue: Queue[Any]) -> None: ... + def prepare(self, record: LogRecord) -> Any: ... + def enqueue(self, record: LogRecord) -> None: ... + +class QueueListener: + if sys.version_info >= (3, 7): def __init__( - self, host: str, url: str, method: str = ..., secure: bool = ..., credentials: Optional[Tuple[str, str]] = ... + self, queue: Union[SimpleQueue[Any], Queue[Any]], *handlers: Handler, respect_handler_level: bool = ... ) -> None: ... else: - def __init__(self, host: str, url: str, method: str = ...) -> None: ... - def mapLogRecord(self, record: LogRecord) -> Dict[str, Any]: ... - -if sys.version_info >= (3,): - class QueueHandler(Handler): - if sys.version_info >= (3, 7): - def __init__(self, queue: Union[SimpleQueue[Any], Queue[Any]]) -> None: ... - else: - def __init__(self, queue: Queue[Any]) -> None: ... - def prepare(self, record: LogRecord) -> Any: ... - def enqueue(self, record: LogRecord) -> None: ... - class QueueListener: - if sys.version_info >= (3, 7): - def __init__( - self, queue: Union[SimpleQueue[Any], Queue[Any]], *handlers: Handler, respect_handler_level: bool = ... - ) -> None: ... - elif sys.version_info >= (3, 5): - def __init__(self, queue: Queue[Any], *handlers: Handler, respect_handler_level: bool = ...) -> None: ... - else: - def __init__(self, queue: Queue, *handlers: Handler) -> None: ... - def dequeue(self, block: bool) -> LogRecord: ... - def prepare(self, record: LogRecord) -> Any: ... - def start(self) -> None: ... - def stop(self) -> None: ... - def enqueue_sentinel(self) -> None: ... + def __init__(self, queue: Queue[Any], *handlers: Handler, respect_handler_level: bool = ...) -> None: ... + def dequeue(self, block: bool) -> LogRecord: ... + def prepare(self, record: LogRecord) -> Any: ... + def start(self) -> None: ... + def stop(self) -> None: ... + def enqueue_sentinel(self) -> None: ... diff --git a/mypy/typeshed/stdlib/netrc.pyi b/mypy/typeshed/stdlib/netrc.pyi index 50fe3c0e0e6c..20a0513ea54a 100644 --- a/mypy/typeshed/stdlib/netrc.pyi +++ b/mypy/typeshed/stdlib/netrc.pyi @@ -1,9 +1,11 @@ +from _typeshed import AnyPath from typing import Dict, List, Optional, Tuple class NetrcParseError(Exception): filename: Optional[str] lineno: Optional[int] msg: str + def __init__(self, msg: str, filename: Optional[AnyPath] = ..., lineno: Optional[int] = ...) -> None: ... # (login, account, password) tuple _NetrcTuple = Tuple[str, Optional[str], Optional[str]] @@ -11,5 +13,5 @@ _NetrcTuple = Tuple[str, Optional[str], Optional[str]] class netrc: hosts: Dict[str, _NetrcTuple] macros: Dict[str, List[str]] - def __init__(self, file: str = ...) -> None: ... + def __init__(self, file: Optional[AnyPath] = ...) -> None: ... def authenticators(self, host: str) -> Optional[_NetrcTuple]: ... diff --git a/mypy/typeshed/stdlib/ntpath.pyi b/mypy/typeshed/stdlib/ntpath.pyi index 9fe5a7df6c85..33536f751205 100644 --- a/mypy/typeshed/stdlib/ntpath.pyi +++ b/mypy/typeshed/stdlib/ntpath.pyi @@ -86,9 +86,9 @@ def isdir(s: AnyPath) -> bool: ... def islink(path: AnyPath) -> bool: ... def ismount(path: AnyPath) -> bool: ... @overload -def join(a: StrPath, *paths: StrPath) -> str: ... +def join(path: StrPath, *paths: StrPath) -> str: ... @overload -def join(a: BytesPath, *paths: BytesPath) -> bytes: ... +def join(path: BytesPath, *paths: BytesPath) -> bytes: ... @overload def relpath(path: BytesPath, start: Optional[BytesPath] = ...) -> bytes: ... @overload diff --git a/mypy/typeshed/stdlib/operator.pyi b/mypy/typeshed/stdlib/operator.pyi index f82d4c6671f5..03510fed90fc 100644 --- a/mypy/typeshed/stdlib/operator.pyi +++ b/mypy/typeshed/stdlib/operator.pyi @@ -1,8 +1,8 @@ import sys from typing import ( Any, - Callable, Container, + Generic, Mapping, MutableMapping, MutableSequence, @@ -14,6 +14,7 @@ from typing import ( ) _T = TypeVar("_T") +_T_co = TypeVar("_T_co", covariant=True) _K = TypeVar("_K") _V = TypeVar("_V") @@ -86,17 +87,17 @@ 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[_T], __b: int) -> None: ... +def delitem(__a: MutableSequence[Any], __b: int) -> None: ... @overload -def delitem(__a: MutableSequence[_T], __b: slice) -> None: ... +def delitem(__a: MutableSequence[Any], __b: slice) -> None: ... @overload -def delitem(__a: MutableMapping[_K, _V], __b: _K) -> None: ... +def delitem(__a: MutableMapping[_K, Any], __b: _K) -> None: ... @overload -def __delitem__(a: MutableSequence[_T], b: int) -> None: ... +def __delitem__(a: MutableSequence[Any], b: int) -> None: ... @overload -def __delitem__(a: MutableSequence[_T], b: slice) -> None: ... +def __delitem__(a: MutableSequence[Any], b: slice) -> None: ... @overload -def __delitem__(a: MutableMapping[_K, _V], b: _K) -> None: ... +def __delitem__(a: MutableMapping[_K, Any], b: _K) -> None: ... if sys.version_info < (3,): def delslice(a: MutableSequence[Any], b: int, c: int) -> None: ... @@ -148,15 +149,36 @@ if sys.version_info < (3,): if sys.version_info >= (3, 4): def length_hint(__obj: Any, __default: int = ...) -> int: ... -@overload -def attrgetter(attr: str) -> Callable[[Any], Any]: ... -@overload -def attrgetter(*attrs: str) -> Callable[[Any], Tuple[Any, ...]]: ... -@overload -def itemgetter(item: Any) -> Callable[[Any], Any]: ... -@overload -def itemgetter(*items: Any) -> Callable[[Any], Tuple[Any, ...]]: ... -def methodcaller(__name: str, *args: Any, **kwargs: Any) -> Callable[..., Any]: ... +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: ... + +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: ... + +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: ... diff --git a/mypy/typeshed/stdlib/optparse.pyi b/mypy/typeshed/stdlib/optparse.pyi index 3d06ac65ed23..2229807bc641 100644 --- a/mypy/typeshed/stdlib/optparse.pyi +++ b/mypy/typeshed/stdlib/optparse.pyi @@ -53,7 +53,6 @@ class HelpFormatter: short_first: Any width: int def __init__(self, indent_increment: int, max_help_position: int, width: Optional[int], short_first: int) -> None: ... - def _format__Text(self, _Text: _Text) -> _Text: ... def dedent(self) -> None: ... def expand_default(self, option: Option) -> _Text: ... def format_description(self, description: _Text) -> _Text: ... @@ -96,6 +95,7 @@ class Option: _short_opts: List[_Text] action: _Text dest: Optional[_Text] + default: Any nargs: int type: Any callback: Optional[Callable[..., Any]] @@ -164,8 +164,8 @@ class Values: def _update_careful(self, dict: Mapping[_Text, Any]) -> None: ... def _update_loose(self, dict: Mapping[_Text, Any]) -> None: ... def ensure_value(self, attr: _Text, value: Any) -> Any: ... - def read_file(self, filename: _Text, mode: _Text) -> None: ... - def read_module(self, modname: _Text, mode: _Text) -> None: ... + def read_file(self, filename: _Text, mode: _Text = ...) -> None: ... + def read_module(self, modname: _Text, mode: _Text = ...) -> None: ... def __getattr__(self, name: str) -> Any: ... def __setattr__(self, name: str, value: Any) -> None: ... @@ -186,7 +186,7 @@ class OptionParser(OptionContainer): def __init__( self, usage: Optional[_Text] = ..., - option_list: Iterable[Option] = ..., + option_list: Optional[Iterable[Option]] = ..., option_class: Type[Option] = ..., version: Optional[_Text] = ..., conflict_handler: _Text = ..., diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 7df6229842ef..f88f9c6a9cc0 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -11,6 +11,7 @@ from _typeshed import ( from builtins import OSError, _PathLike 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, Any, @@ -176,7 +177,36 @@ R_OK: int W_OK: int X_OK: int +_EnvironCodeFunc = Callable[[AnyStr], AnyStr] + class _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]): + encodekey: _EnvironCodeFunc[AnyStr] + decodekey: _EnvironCodeFunc[AnyStr] + encodevalue: _EnvironCodeFunc[AnyStr] + decodevalue: _EnvironCodeFunc[AnyStr] + if sys.version_info >= (3, 9): + def __init__( + self, + data: MutableMapping[AnyStr, AnyStr], + encodekey: _EnvironCodeFunc[AnyStr], + decodekey: _EnvironCodeFunc[AnyStr], + encodevalue: _EnvironCodeFunc[AnyStr], + decodevalue: _EnvironCodeFunc[AnyStr], + ) -> None: ... + else: + putenv: Callable[[AnyStr, AnyStr], None] + unsetenv: Callable[[AnyStr, AnyStr], None] + def __init__( + self, + data: MutableMapping[AnyStr, AnyStr], + encodekey: _EnvironCodeFunc[AnyStr], + decodekey: _EnvironCodeFunc[AnyStr], + encodevalue: _EnvironCodeFunc[AnyStr], + decodevalue: _EnvironCodeFunc[AnyStr], + putenv: Callable[[AnyStr, AnyStr], None], + unsetenv: Callable[[AnyStr, AnyStr], None], + ) -> None: ... + def setdefault(self, key: AnyStr, value: AnyStr) -> AnyStr: ... # type: ignore def copy(self) -> Dict[AnyStr, AnyStr]: ... def __delitem__(self, key: AnyStr) -> None: ... def __getitem__(self, key: AnyStr) -> AnyStr: ... @@ -726,6 +756,7 @@ if sys.platform != "win32": def plock(op: int) -> None: ... # ???op is int? class _wrap_close(_TextIOWrapper): + def __init__(self, stream: _TextIOWrapper, proc: Popen[str]) -> None: ... def close(self) -> Optional[int]: ... # type: ignore def popen(cmd: str, mode: str = ..., buffering: int = ...) -> _wrap_close: ... diff --git a/mypy/typeshed/stdlib/pipes.pyi b/mypy/typeshed/stdlib/pipes.pyi index 2c2fd400a0c8..fb9d7e4e1d16 100644 --- a/mypy/typeshed/stdlib/pipes.pyi +++ b/mypy/typeshed/stdlib/pipes.pyi @@ -8,7 +8,7 @@ class Template: def append(self, cmd: str, kind: str) -> None: ... def prepend(self, cmd: str, kind: str) -> None: ... def open(self, file: str, rw: str) -> os._wrap_close: ... - def copy(self, file: str, rw: str) -> os._wrap_close: ... + def copy(self, infile: str, outfile: str) -> int: ... # Not documented, but widely used. # Documented as shlex.quote since 3.3. diff --git a/mypy/typeshed/stdlib/pkgutil.pyi b/mypy/typeshed/stdlib/pkgutil.pyi index 5fd025411325..0935e922562e 100644 --- a/mypy/typeshed/stdlib/pkgutil.pyi +++ b/mypy/typeshed/stdlib/pkgutil.pyi @@ -1,6 +1,6 @@ import sys from _typeshed import SupportsRead -from typing import IO, Any, Callable, Iterable, Iterator, NamedTuple, Optional, Tuple, Union +from typing import IO, Any, Callable, Iterable, Iterator, List, NamedTuple, Optional, Tuple, Union if sys.version_info >= (3,): from importlib.abc import Loader, MetaPathFinder, PathEntryFinder @@ -18,10 +18,10 @@ if sys.version_info >= (3, 6): else: _ModuleInfoLike = Tuple[Union[MetaPathFinder, PathEntryFinder], str, bool] -def extend_path(path: Iterable[str], name: str) -> Iterable[str]: ... +def extend_path(path: List[str], name: str) -> List[str]: ... class ImpImporter: - def __init__(self, dirname: Optional[str] = ...) -> None: ... + def __init__(self, path: Optional[str] = ...) -> None: ... class ImpLoader: def __init__(self, fullname: str, file: IO[str], filename: str, etc: Tuple[str, str, int]) -> None: ... @@ -36,3 +36,6 @@ def walk_packages( path: Optional[Iterable[str]] = ..., prefix: str = ..., onerror: Optional[Callable[[str], None]] = ... ) -> Iterator[_ModuleInfoLike]: ... def get_data(package: str, resource: str) -> Optional[bytes]: ... + +if sys.version_info >= (3, 9): + def resolve_name(name: str) -> Any: ... diff --git a/mypy/typeshed/stdlib/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/pyexpat/__init__.pyi index c8305567e92e..65f6b0e9f7de 100644 --- a/mypy/typeshed/stdlib/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/pyexpat/__init__.pyi @@ -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] +_Model = Tuple[int, int, Optional[str], Tuple[Any, ...]] class XMLParserType(object): def Parse(self, __data: Union[Text, bytes], __isfinal: bool = ...) -> int: ... diff --git a/mypy/typeshed/stdlib/random.pyi b/mypy/typeshed/stdlib/random.pyi index 9a28024c2c39..0f1e280490ac 100644 --- a/mypy/typeshed/stdlib/random.pyi +++ b/mypy/typeshed/stdlib/random.pyi @@ -1,6 +1,7 @@ import _random import sys -from typing import AbstractSet, Any, Callable, Iterable, List, MutableSequence, Optional, Sequence, Tuple, TypeVar, Union +from collections.abc import Callable, Iterable, MutableSequence, Sequence, Set +from typing import Any, NoReturn, Optional, Tuple, TypeVar, Union _T = TypeVar("_T") @@ -22,14 +23,14 @@ class Random(_random.Random): *, cum_weights: Optional[Sequence[float]] = ..., k: int = ..., - ) -> List[_T]: ... + ) -> list[_T]: ... def shuffle(self, x: MutableSequence[Any], random: Optional[Callable[[], float]] = ...) -> None: ... if sys.version_info >= (3, 9): def sample( - self, population: Union[Sequence[_T], AbstractSet[_T]], k: int, *, counts: Optional[Iterable[_T]] = ... - ) -> List[_T]: ... + self, population: Union[Sequence[_T], Set[_T]], k: int, *, counts: Optional[Iterable[_T]] = ... + ) -> list[_T]: ... else: - def sample(self, population: Union[Sequence[_T], AbstractSet[_T]], k: int) -> List[_T]: ... + def sample(self, population: Union[Sequence[_T], Set[_T]], k: int) -> list[_T]: ... def random(self) -> float: ... def uniform(self, a: float, b: float) -> float: ... def triangular(self, low: float = ..., high: float = ..., mode: Optional[float] = ...) -> float: ... @@ -44,7 +45,9 @@ class Random(_random.Random): def weibullvariate(self, alpha: float, beta: float) -> float: ... # SystemRandom is not implemented for all OS's; good on Windows & Linux -class SystemRandom(Random): ... +class SystemRandom(Random): + 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: ... @@ -64,14 +67,14 @@ def choices( *, cum_weights: Optional[Sequence[float]] = ..., k: int = ..., -) -> List[_T]: ... +) -> list[_T]: ... def shuffle(x: MutableSequence[Any], random: Optional[Callable[[], float]] = ...) -> None: ... if sys.version_info >= (3, 9): - def sample(population: Union[Sequence[_T], AbstractSet[_T]], k: int, *, counts: Optional[Iterable[_T]] = ...) -> List[_T]: ... + def sample(population: Union[Sequence[_T], Set[_T]], k: int, *, counts: Optional[Iterable[_T]] = ...) -> list[_T]: ... else: - def sample(population: Union[Sequence[_T], AbstractSet[_T]], k: int) -> List[_T]: ... + def sample(population: Union[Sequence[_T], Set[_T]], k: int) -> list[_T]: ... def random() -> float: ... def uniform(a: float, b: float) -> float: ... diff --git a/mypy/typeshed/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi index 264174440956..e690e76586a0 100644 --- a/mypy/typeshed/stdlib/re.pyi +++ b/mypy/typeshed/stdlib/re.pyi @@ -1,5 +1,6 @@ import enum import sys +from sre_constants import error as error from typing import Any, AnyStr, Callable, Iterator, List, Optional, Tuple, Union, overload # ----- re variables and constants ----- @@ -50,13 +51,6 @@ if sys.version_info < (3, 7): # undocumented _pattern_type: type -class error(Exception): - msg: str - pattern: str - pos: Optional[int] - lineno: Optional[int] - colno: Optional[int] - @overload def compile(pattern: AnyStr, flags: _FlagsType = ...) -> Pattern[AnyStr]: ... @overload diff --git a/mypy/typeshed/stdlib/resource.pyi b/mypy/typeshed/stdlib/resource.pyi index 38e28898a1e4..ff17bc1a0e44 100644 --- a/mypy/typeshed/stdlib/resource.pyi +++ b/mypy/typeshed/stdlib/resource.pyi @@ -1,5 +1,5 @@ import sys -from typing import NamedTuple, Tuple, overload +from typing import Any, Dict, Tuple, overload RLIMIT_AS: int RLIMIT_CORE: int @@ -23,7 +23,10 @@ if sys.platform == "linux": RLIMIT_SIGPENDING: int RUSAGE_THREAD: int -class _RUsage(NamedTuple): +_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 @@ -43,7 +46,7 @@ class _RUsage(NamedTuple): def getpagesize() -> int: ... def getrlimit(__resource: int) -> Tuple[int, int]: ... -def getrusage(__who: int) -> _RUsage: ... +def getrusage(__who: int) -> struct_rusage: ... def setrlimit(__resource: int, __limits: Tuple[int, int]) -> None: ... if sys.platform == "linux": diff --git a/mypy/typeshed/stdlib/runpy.pyi b/mypy/typeshed/stdlib/runpy.pyi index e27849d9c480..d40c3668ad2f 100644 --- a/mypy/typeshed/stdlib/runpy.pyi +++ b/mypy/typeshed/stdlib/runpy.pyi @@ -18,5 +18,5 @@ class _ModifiedArgv0: def run_module( mod_name: str, init_globals: Optional[Dict[str, Any]] = ..., run_name: Optional[str] = ..., alter_sys: bool = ... -) -> None: ... -def run_path(path_name: str, init_globals: Optional[Dict[str, Any]] = ..., run_name: str = ...) -> None: ... +) -> Dict[str, Any]: ... +def run_path(path_name: str, init_globals: Optional[Dict[str, Any]] = ..., run_name: Optional[str] = ...) -> Dict[str, Any]: ... diff --git a/mypy/typeshed/stdlib/shelve.pyi b/mypy/typeshed/stdlib/shelve.pyi index bbbd72e44b24..ed062f62b49b 100644 --- a/mypy/typeshed/stdlib/shelve.pyi +++ b/mypy/typeshed/stdlib/shelve.pyi @@ -1,7 +1,7 @@ -import collections +import collections.abc from typing import Any, Dict, Iterator, Optional, Tuple -class Shelf(collections.MutableMapping[Any, Any]): +class Shelf(collections.abc.MutableMapping[Any, Any]): def __init__( self, dict: Dict[bytes, Any], protocol: Optional[int] = ..., writeback: bool = ..., keyencoding: str = ... ) -> None: ... diff --git a/mypy/typeshed/stdlib/shlex.pyi b/mypy/typeshed/stdlib/shlex.pyi index 0eb89d33cc8b..741f516dcfdc 100644 --- a/mypy/typeshed/stdlib/shlex.pyi +++ b/mypy/typeshed/stdlib/shlex.pyi @@ -28,7 +28,7 @@ class shlex(Iterable[str]): punctuation_chars: str def __init__( self, - instream: Union[str, TextIO] = ..., + instream: Optional[Union[str, TextIO]] = ..., infile: Optional[str] = ..., posix: bool = ..., punctuation_chars: Union[bool, str] = ..., @@ -36,10 +36,10 @@ class shlex(Iterable[str]): def get_token(self) -> str: ... def push_token(self, tok: str) -> None: ... def read_token(self) -> str: ... - def sourcehook(self, filename: str) -> Tuple[str, TextIO]: ... + def sourcehook(self, newfile: str) -> Tuple[str, TextIO]: ... # TODO argument types def push_source(self, newstream: Any, newfile: Any = ...) -> None: ... def pop_source(self) -> None: ... - def error_leader(self, infile: str = ..., lineno: int = ...) -> None: ... + def error_leader(self, infile: Optional[str] = ..., lineno: Optional[int] = ...) -> None: ... def __iter__(self: _SLT) -> _SLT: ... def __next__(self) -> str: ... diff --git a/mypy/typeshed/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi index b814112a175a..c0779d871c14 100644 --- a/mypy/typeshed/stdlib/shutil.pyi +++ b/mypy/typeshed/stdlib/shutil.pyi @@ -159,7 +159,11 @@ if sys.version_info >= (3,): # See http://bugs.python.org/issue30218 def unpack_archive(filename: str, extract_dir: Optional[StrPath] = ..., format: Optional[str] = ...) -> None: ... def register_unpack_format( - name: str, extensions: List[str], function: Any, extra_args: Sequence[Tuple[str, Any]] = ..., description: str = ... + name: str, + extensions: List[str], + function: Any, + extra_args: Optional[Sequence[Tuple[str, Any]]] = ..., + description: str = ..., ) -> None: ... def unregister_unpack_format(name: str) -> None: ... def get_unpack_formats() -> List[Tuple[str, List[str], str]]: ... diff --git a/mypy/typeshed/stdlib/smtpd.pyi b/mypy/typeshed/stdlib/smtpd.pyi index 051fe72eabd7..a4f9bfa6593c 100644 --- a/mypy/typeshed/stdlib/smtpd.pyi +++ b/mypy/typeshed/stdlib/smtpd.pyi @@ -2,7 +2,7 @@ import asynchat import asyncore import socket import sys -from typing import Any, DefaultDict, List, Optional, Text, Tuple, Type +from typing import Any, DefaultDict, List, Optional, Text, Tuple, Type, Union _Address = Tuple[str, int] # (host, port) @@ -79,8 +79,26 @@ class SMTPServer(asyncore.dispatcher): else: 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: str, **kwargs: Any) -> Optional[str]: ... + def process_message( + self, peer: _Address, mailfrom: str, rcpttos: List[Text], data: Union[bytes, str], **kwargs: Any + ) -> Optional[str]: ... class DebuggingServer(SMTPServer): ... -class PureProxy(SMTPServer): ... -class MailmanProxy(PureProxy): ... + +class PureProxy(SMTPServer): + def process_message( # type: ignore + self, + peer: _Address, + mailfrom: str, + rcpttos: List[Text], + data: Union[bytes, str], + ) -> Optional[str]: ... + +class MailmanProxy(PureProxy): + def process_message( # type: ignore + self, + peer: _Address, + mailfrom: str, + rcpttos: List[Text], + data: Union[bytes, str], + ) -> Optional[str]: ... diff --git a/mypy/typeshed/stdlib/smtplib.pyi b/mypy/typeshed/stdlib/smtplib.pyi index fa9d37e4065f..4f376d2b645c 100644 --- a/mypy/typeshed/stdlib/smtplib.pyi +++ b/mypy/typeshed/stdlib/smtplib.pyi @@ -124,7 +124,7 @@ class SMTP: msg: _Message, from_addr: Optional[str] = ..., to_addrs: Optional[Union[str, Sequence[str]]] = ..., - mail_options: List[str] = ..., + mail_options: Sequence[str] = ..., rcpt_options: Sequence[str] = ..., ) -> _SendErrs: ... def close(self) -> None: ... diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index da8fbcf566fc..1d315fc1267d 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -604,7 +604,7 @@ 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, str] +_Address = Union[Tuple[Any, ...], str] _RetAddress = Any # TODO Most methods allow bytes as address objects diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index ae3b01bfb5ca..51def54066d6 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -16,7 +16,7 @@ def DateFromTicks(ticks: float) -> Date: ... def TimeFromTicks(ticks: float) -> Time: ... def TimestampFromTicks(ticks: float) -> Timestamp: ... -version_info: str +version_info: Tuple[int, int, int] sqlite_version_info: Tuple[int, int, int] if sys.version_info >= (3,): Binary = memoryview @@ -289,7 +289,7 @@ class Row(object): def __hash__(self): ... def __iter__(self): ... def __le__(self, other): ... - def __len__(self, *args: Any, **kwargs: Any): ... + def __len__(self): ... def __lt__(self, other): ... def __ne__(self, other): ... diff --git a/mypy/typeshed/stdlib/sre_constants.pyi b/mypy/typeshed/stdlib/sre_constants.pyi index 2b411d5c69c9..d66f19eda717 100644 --- a/mypy/typeshed/stdlib/sre_constants.pyi +++ b/mypy/typeshed/stdlib/sre_constants.pyi @@ -8,7 +8,7 @@ class error(Exception): pos: Optional[int] lineno: int colno: int - def __init__(self, msg: str, pattern: Union[str, bytes] = ..., pos: int = ...) -> None: ... + def __init__(self, msg: str, pattern: Optional[Union[str, bytes]] = ..., pos: Optional[int] = ...) -> None: ... class _NamedIntConstant(int): name: Any diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index 36656f5534ab..160501d1e1e7 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -138,6 +138,7 @@ if sys.version_info >= (3, 6): OP_NO_TLSv1: int OP_NO_TLSv1_1: int OP_NO_TLSv1_2: int + OP_NO_TLSv1_3: int OP_CIPHER_SERVER_PREFERENCE: int OP_SINGLE_DH_USE: int OP_SINGLE_ECDH_USE: int @@ -145,7 +146,6 @@ if sys.version_info >= (3, 6): OP_NO_TICKET: int if sys.version_info >= (3, 7): OP_NO_RENEGOTIATION: int - OP_NO_TLSv1_3: int if sys.version_info >= (3, 8): OP_ENABLE_MIDDLEBOX_COMPAT: int OP_ALL: Options @@ -154,6 +154,7 @@ if sys.version_info >= (3, 6): OP_NO_TLSv1: Options OP_NO_TLSv1_1: Options OP_NO_TLSv1_2: Options + OP_NO_TLSv1_3: Options OP_CIPHER_SERVER_PREFERENCE: Options OP_SINGLE_DH_USE: Options OP_SINGLE_ECDH_USE: Options @@ -161,7 +162,6 @@ if sys.version_info >= (3, 6): OP_NO_TICKET: Options if sys.version_info >= (3, 7): OP_NO_RENEGOTIATION: Options - OP_NO_TLSv1_3: Options if sys.version_info >= (3, 8): OP_ENABLE_MIDDLEBOX_COMPAT: Options else: @@ -228,16 +228,16 @@ class _ASN1Object(NamedTuple): longname: str oid: str -if sys.version_info < (3,): - class Purpose(_ASN1Object): - SERVER_AUTH: ClassVar[Purpose] - CLIENT_AUTH: ClassVar[Purpose] - -else: +if sys.version_info >= (3, 0): class Purpose(_ASN1Object, enum.Enum): SERVER_AUTH: _ASN1Object CLIENT_AUTH: _ASN1Object +else: + class Purpose(_ASN1Object): + SERVER_AUTH: ClassVar[Purpose] + CLIENT_AUTH: ClassVar[Purpose] + class SSLSocket(socket.socket): context: SSLContext server_side: bool @@ -245,6 +245,42 @@ class SSLSocket(socket.socket): if sys.version_info >= (3, 6): session: Optional[SSLSession] session_reused: Optional[bool] + if sys.version_info < (3, 7): + def __init__( + self, + sock: Optional[socket.socket] = ..., + keyfile: Optional[str] = ..., + certfile: Optional[str] = ..., + server_side: bool = ..., + cert_reqs: int = ..., + ssl_version: int = ..., + ca_certs: Optional[str] = ..., + do_handshake_on_connect: bool = ..., + family: int = ..., + type: int = ..., + proto: int = ..., + fileno: Optional[int] = ..., + suppress_ragged_eofs: bool = ..., + npn_protocols: Optional[Iterable[str]] = ..., + ciphers: Optional[str] = ..., + server_hostname: Optional[str] = ..., + _context: Optional[SSLContext] = ..., + _session: Optional[Any] = ..., + ) -> None: ... + else: + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + def connect(self, addr: Union[socket._Address, bytes]) -> None: ... + def connect_ex(self, addr: Union[socket._Address, bytes]) -> int: ... + def recv(self, buflen: int = ..., flags: int = ...) -> bytes: ... + def recv_into(self, buffer: socket._WriteBuffer, nbytes: Optional[int] = ..., flags: int = ...) -> int: ... + def recvfrom(self, buflen: int = ..., flags: int = ...) -> tuple[bytes, socket._RetAddress]: ... + def recvfrom_into( + self, buffer: socket._WriteBuffer, nbytes: Optional[int] = ..., flags: int = ... + ) -> tuple[int, socket._RetAddress]: ... + @overload + def sendto(self, data: bytes, flags_or_addr: socket._Address) -> int: ... + @overload + def sendto(self, data: bytes, flags_or_addr: Union[int, socket._Address], addr: Optional[socket._Address] = ...) -> int: ... def read(self, len: int = ..., buffer: Optional[bytearray] = ...) -> bytes: ... def write(self, data: bytes) -> int: ... def do_handshake(self, block: bool = ...) -> None: ... # block is undocumented @@ -286,6 +322,10 @@ class SSLContext: options: int if sys.version_info >= (3, 8): post_handshake_auth: bool + if sys.version_info >= (3, 5): + def __new__(cls, protocol: int = ..., *args: Any, **kwargs: Any) -> SSLContext: ... + else: + def __new__(cls, protocol: int, *args: Any, **kwargs: Any) -> SSLContext: ... @property def protocol(self) -> int: ... verify_flags: int @@ -362,6 +402,12 @@ if sys.version_info >= (3, 5): if sys.version_info >= (3, 6): session: Optional[SSLSession] session_reused: bool + if sys.version_info >= (3, 7): + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + else: + def __init__( + self, sslobj: Any, owner: Optional[Union[SSLSocket, SSLObject]] = ..., session: Optional[Any] = ... + ) -> None: ... def read(self, len: int = ..., buffer: Optional[bytearray] = ...) -> bytes: ... def write(self, data: bytes) -> int: ... @overload @@ -421,7 +467,8 @@ SSL_ERROR_ZERO_RETURN: int def get_protocol_name(protocol_code: int) -> str: ... -AF_INET: int +if sys.version_info < (3, 9): + AF_INET: int PEM_FOOTER: str PEM_HEADER: str SOCK_STREAM: int diff --git a/mypy/typeshed/stdlib/struct.pyi b/mypy/typeshed/stdlib/struct.pyi index 9edf6842be3d..096f8b7b85ca 100644 --- a/mypy/typeshed/stdlib/struct.pyi +++ b/mypy/typeshed/stdlib/struct.pyi @@ -8,7 +8,7 @@ class error(Exception): ... _FmtType = Union[bytes, Text] if sys.version_info >= (3,): _BufferType = Union[array[int], bytes, bytearray, memoryview, mmap] - _WriteBufferType = Union[array, bytearray, memoryview, mmap] + _WriteBufferType = Union[array[Any], bytearray, memoryview, mmap] else: _BufferType = Union[array[int], bytes, bytearray, buffer, memoryview, mmap] _WriteBufferType = Union[array[Any], bytearray, buffer, memoryview, mmap] diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index b9d7108a96e6..3a0361ca0931 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -23,10 +23,16 @@ if sys.version_info >= (3, 9): # reveal_type(e.cmd) # Any, but morally is _CMD _FILE = Union[None, int, IO[Any]] _TXT = Union[bytes, str] -# Python 3.6 does't support _CMD being a single PathLike. -# See: https://bugs.python.org/issue31961 -_CMD = Union[_TXT, Sequence[AnyPath]] -_ENV = Union[Mapping[bytes, _TXT], Mapping[str, _TXT]] +if sys.version_info >= (3, 8): + _CMD = Union[AnyPath, Sequence[AnyPath]] +else: + # Python 3.6 doesn't support _CMD being a single PathLike. + # See: https://bugs.python.org/issue31961 + _CMD = Union[_TXT, Sequence[AnyPath]] +if sys.platform == "win32": + _ENV = Mapping[str, str] +else: + _ENV = Union[Mapping[bytes, AnyPath], Mapping[str, AnyPath]] _S = TypeVar("_S") _T = TypeVar("_T") @@ -417,7 +423,7 @@ if sys.version_info >= (3, 7): pass_fds: Any = ..., *, timeout: Optional[float] = ..., - input: _TXT = ..., + input: Optional[_TXT] = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., text: Literal[True], @@ -442,7 +448,7 @@ if sys.version_info >= (3, 7): pass_fds: Any = ..., *, timeout: Optional[float] = ..., - input: _TXT = ..., + input: Optional[_TXT] = ..., encoding: str, errors: Optional[str] = ..., text: Optional[bool] = ..., @@ -467,7 +473,7 @@ if sys.version_info >= (3, 7): pass_fds: Any = ..., *, timeout: Optional[float] = ..., - input: _TXT = ..., + input: Optional[_TXT] = ..., encoding: Optional[str] = ..., errors: str, text: Optional[bool] = ..., @@ -493,7 +499,7 @@ if sys.version_info >= (3, 7): pass_fds: Any = ..., # where the real keyword only ones start timeout: Optional[float] = ..., - input: _TXT = ..., + input: Optional[_TXT] = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., text: Optional[bool] = ..., @@ -518,7 +524,7 @@ if sys.version_info >= (3, 7): pass_fds: Any = ..., *, timeout: Optional[float] = ..., - input: _TXT = ..., + input: Optional[_TXT] = ..., encoding: None = ..., errors: None = ..., text: Literal[None, False] = ..., @@ -543,7 +549,7 @@ if sys.version_info >= (3, 7): pass_fds: Any = ..., *, timeout: Optional[float] = ..., - input: _TXT = ..., + input: Optional[_TXT] = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., text: Optional[bool] = ..., @@ -570,7 +576,7 @@ else: pass_fds: Any = ..., *, timeout: Optional[float] = ..., - input: _TXT = ..., + input: Optional[_TXT] = ..., encoding: str, errors: Optional[str] = ..., ) -> str: ... @@ -594,7 +600,7 @@ else: pass_fds: Any = ..., *, timeout: Optional[float] = ..., - input: _TXT = ..., + input: Optional[_TXT] = ..., encoding: Optional[str] = ..., errors: str, ) -> str: ... @@ -618,7 +624,7 @@ else: *, universal_newlines: Literal[True], timeout: Optional[float] = ..., - input: _TXT = ..., + input: Optional[_TXT] = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., ) -> str: ... @@ -642,7 +648,7 @@ else: pass_fds: Any = ..., *, timeout: Optional[float] = ..., - input: _TXT = ..., + input: Optional[_TXT] = ..., encoding: None = ..., errors: None = ..., ) -> bytes: ... @@ -666,7 +672,7 @@ else: pass_fds: Any = ..., *, timeout: Optional[float] = ..., - input: _TXT = ..., + input: Optional[_TXT] = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., ) -> Any: ... # morally: -> _TXT diff --git a/mypy/typeshed/stdlib/sunau.pyi b/mypy/typeshed/stdlib/sunau.pyi index b9475937c012..175068861ee9 100644 --- a/mypy/typeshed/stdlib/sunau.pyi +++ b/mypy/typeshed/stdlib/sunau.pyi @@ -20,9 +20,7 @@ AUDIO_FILE_ENCODING_ADPCM_G723_5: int AUDIO_FILE_ENCODING_ALAW_8: int AUDIO_UNKNOWN_SIZE: int -if sys.version_info < (3, 0): - _sunau_params = Tuple[int, int, int, int, str, str] -else: +if sys.version_info >= (3, 0): class _sunau_params(NamedTuple): nchannels: int sampwidth: int @@ -31,6 +29,9 @@ else: comptype: str compname: str +else: + _sunau_params = Tuple[int, int, int, int, str, str] + class Au_read: def __init__(self, f: _File) -> None: ... if sys.version_info >= (3, 3): @@ -65,14 +66,11 @@ class Au_write: def getframerate(self) -> int: ... def setnframes(self, nframes: int) -> None: ... def getnframes(self) -> int: ... - def setcomptype(self, comptype: str, compname: str) -> None: ... + def setcomptype(self, type: str, name: str) -> None: ... def getcomptype(self) -> str: ... def getcompname(self) -> str: ... def setparams(self, params: _sunau_params) -> None: ... def getparams(self) -> _sunau_params: ... - def setmark(self, id: Any, pos: Any, name: Any) -> NoReturn: ... - def getmark(self, id: Any) -> NoReturn: ... - def getmarkers(self) -> None: ... def tell(self) -> int: ... # should be any bytes-like object after 3.4, but we don't have a type for that def writeframesraw(self, data: bytes) -> None: ... diff --git a/mypy/typeshed/stdlib/symtable.pyi b/mypy/typeshed/stdlib/symtable.pyi index 9fe53402d4ec..b528481bf510 100644 --- a/mypy/typeshed/stdlib/symtable.pyi +++ b/mypy/typeshed/stdlib/symtable.pyi @@ -1,9 +1,10 @@ import sys -from typing import List, Sequence, Text, Tuple +from typing import Any, List, Optional, Sequence, Text, Tuple def symtable(code: Text, filename: Text, compile_type: Text) -> SymbolTable: ... class SymbolTable(object): + def __init__(self, raw_table: Any, filename: str) -> None: ... def get_type(self) -> str: ... def get_id(self) -> int: ... def get_name(self) -> str: ... @@ -29,6 +30,12 @@ class Class(SymbolTable): def get_methods(self) -> Tuple[str, ...]: ... class Symbol(object): + if sys.version_info >= (3, 8): + def __init__( + self, name: str, flags: int, namespaces: Optional[Sequence[SymbolTable]] = ..., *, module_scope: bool = ... + ) -> None: ... + else: + def __init__(self, name: str, flags: int, namespaces: Optional[Sequence[SymbolTable]] = ...) -> None: ... def get_name(self) -> str: ... def is_referenced(self) -> bool: ... def is_parameter(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/sysconfig.pyi b/mypy/typeshed/stdlib/sysconfig.pyi index ed0aa6d5b501..b8044bcaa615 100644 --- a/mypy/typeshed/stdlib/sysconfig.pyi +++ b/mypy/typeshed/stdlib/sysconfig.pyi @@ -11,7 +11,7 @@ def get_path(name: str, scheme: str = ..., vars: Optional[Dict[str, Any]] = ..., def get_paths(scheme: str = ..., vars: Optional[Dict[str, Any]] = ..., expand: bool = ...) -> Dict[str, str]: ... def get_python_version() -> str: ... def get_platform() -> str: ... -def is_python_build() -> bool: ... -def parse_config_h(fp: IO[Any], vars: Optional[Dict[str, Any]]) -> Dict[str, Any]: ... +def is_python_build(check_home: bool = ...) -> bool: ... +def parse_config_h(fp: IO[Any], vars: Optional[Dict[str, Any]] = ...) -> Dict[str, Any]: ... def get_config_h_filename() -> str: ... def get_makefile_filename() -> str: ... diff --git a/mypy/typeshed/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi index 12e80480cc17..1faba6e948e5 100644 --- a/mypy/typeshed/stdlib/tarfile.pyi +++ b/mypy/typeshed/stdlib/tarfile.pyi @@ -1,3 +1,4 @@ +import io import sys from _typeshed import AnyPath, StrPath from types import TracebackType @@ -72,7 +73,11 @@ def open( compresslevel: Optional[int] = ..., ) -> TarFile: ... +class ExFileObject(io.BufferedReader): + def __init__(self, tarfile: TarFile, tarinfo: TarInfo) -> None: ... + class TarFile(Iterable[TarInfo]): + OPEN_METH: Mapping[str, str] name: Optional[AnyPath] mode: str fileobj: Optional[IO[bytes]] @@ -82,9 +87,11 @@ class TarFile(Iterable[TarInfo]): ignore_zeros: Optional[bool] encoding: Optional[str] errors: str + fileobject: Type[ExFileObject] pax_headers: Optional[Mapping[str, str]] debug: Optional[int] errorlevel: Optional[int] + offset: int # undocumented if sys.version_info < (3,): posix: bool def __init__( @@ -126,6 +133,74 @@ class TarFile(Iterable[TarInfo]): debug: Optional[int] = ..., errorlevel: Optional[int] = ..., ) -> TarFile: ... + @classmethod + def taropen( + cls, + name: Optional[AnyPath], + mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., + *, + compresslevel: int = ..., + format: Optional[int] = ..., + tarinfo: Optional[Type[TarInfo]] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + ) -> TarFile: ... + @classmethod + def gzopen( + cls, + name: Optional[AnyPath], + mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., + compresslevel: int = ..., + *, + format: Optional[int] = ..., + tarinfo: Optional[Type[TarInfo]] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + ) -> TarFile: ... + @classmethod + def bz2open( + cls, + name: Optional[AnyPath], + mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., + compresslevel: int = ..., + *, + format: Optional[int] = ..., + tarinfo: Optional[Type[TarInfo]] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + ) -> TarFile: ... + @classmethod + def xzopen( + cls, + name: Optional[AnyPath], + mode: str = ..., + fileobj: Optional[IO[bytes]] = ..., + preset: Optional[int] = ..., + *, + format: Optional[int] = ..., + tarinfo: Optional[Type[TarInfo]] = ..., + dereference: Optional[bool] = ..., + ignore_zeros: Optional[bool] = ..., + encoding: Optional[str] = ..., + pax_headers: Optional[Mapping[str, str]] = ..., + debug: Optional[int] = ..., + errorlevel: Optional[int] = ..., + ) -> TarFile: ... def getmember(self, name: str) -> TarInfo: ... def getmembers(self) -> List[TarInfo]: ... def getnames(self) -> List[str]: ... @@ -218,6 +293,13 @@ class TarInfo: path: str size: int mtime: int + chksum: int + devmajor: int + devminor: int + offset: int + offset_data: int + sparse: Optional[bytes] + tarfile: Optional[TarFile] mode: int type: bytes linkname: str @@ -235,9 +317,24 @@ class TarInfo: def frombuf(cls, buf: bytes) -> TarInfo: ... @classmethod def fromtarfile(cls, tarfile: TarFile) -> TarInfo: ... + @property + def linkpath(self) -> str: ... + @linkpath.setter + def linkpath(self, linkname: str) -> None: ... + def get_info(self) -> Mapping[str, Union[str, int, bytes, Mapping[str, str]]]: ... def tobuf(self, format: Optional[int] = ..., encoding: Optional[str] = ..., errors: str = ...) -> bytes: ... + def create_ustar_header( + self, info: Mapping[str, Union[str, int, bytes, Mapping[str, str]]], encoding: str, errors: str + ) -> bytes: ... + def create_gnu_header( + self, info: Mapping[str, Union[str, int, bytes, Mapping[str, str]]], encoding: str, errors: str + ) -> bytes: ... + def create_pax_header(self, info: Mapping[str, Union[str, int, bytes, Mapping[str, str]]], encoding: str) -> bytes: ... + @classmethod + def create_pax_global_header(cls, pax_headers: Mapping[str, str]) -> bytes: ... def isfile(self) -> bool: ... def isreg(self) -> bool: ... + def issparse(self) -> bool: ... def isdir(self) -> bool: ... def issym(self) -> bool: ... def islnk(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi index 7b87fd46e368..ddf9f582809c 100644 --- a/mypy/typeshed/stdlib/tempfile.pyi +++ b/mypy/typeshed/stdlib/tempfile.pyi @@ -13,8 +13,7 @@ tempdir: Optional[str] template: str _S = TypeVar("_S") -_T = TypeVar("_T") # for pytype, define typevar in same file as alias -_DirT = Union[_T, os.PathLike[_T]] +_DirT = Union[AnyStr, os.PathLike[AnyStr]] if sys.version_info >= (3, 8): @overload @@ -164,6 +163,39 @@ else: dir: Optional[_DirT[AnyStr]] = ..., ) -> IO[Any]: ... +class _TemporaryFileWrapper(IO[str]): + file: IO[str] + name: Any + delete: bool + def __init__(self, file: IO[str], name: Any, delete: bool = ...) -> None: ... + def __enter__(self) -> _TemporaryFileWrapper: ... + def __exit__( + self, exc: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[TracebackType] + ) -> Optional[bool]: ... + def __getattr__(self, name: str) -> Any: ... + def close(self) -> None: ... + def unlink(self, path: str) -> None: ... + # These methods don't exist directly on this object, but + # are delegated to the underlying IO object through __getattr__. + # We need to add them here so that this class is concrete. + def __iter__(self) -> Iterator[str]: ... + def __next__(self) -> str: ... + def fileno(self) -> int: ... + def flush(self) -> None: ... + def isatty(self) -> bool: ... + def next(self) -> 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 seek(self, offset: int, whence: int = ...) -> int: ... + def seekable(self) -> bool: ... + def tell(self) -> int: ... + def truncate(self, size: Optional[int] = ...) -> int: ... + def writable(self) -> bool: ... + def write(self, s: str) -> int: ... + def writelines(self, lines: Iterable[str]) -> None: ... + # It does not actually derive from IO[AnyStr], but it does implement the # protocol. class SpooledTemporaryFile(IO[AnyStr]): @@ -278,7 +310,10 @@ class SpooledTemporaryFile(IO[AnyStr]): def __next__(self) -> AnyStr: ... class TemporaryDirectory(Generic[AnyStr]): - name: str + name: AnyStr + @overload + def __init__(self: TemporaryDirectory[str], suffix: None = ..., prefix: None = ..., dir: None = ...) -> None: ... + @overload def __init__( self, suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ... ) -> None: ... @@ -290,6 +325,9 @@ class TemporaryDirectory(Generic[AnyStr]): if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... +@overload +def mkstemp() -> Tuple[int, str]: ... +@overload def mkstemp( suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ..., text: bool = ... ) -> Tuple[int, AnyStr]: ... @@ -297,6 +335,9 @@ def mkstemp( def mkdtemp() -> str: ... @overload def mkdtemp(suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ...) -> AnyStr: ... +@overload +def mktemp() -> str: ... +@overload def mktemp(suffix: Optional[AnyStr] = ..., prefix: Optional[AnyStr] = ..., dir: Optional[_DirT[AnyStr]] = ...) -> AnyStr: ... def gettempdirb() -> bytes: ... def gettempprefixb() -> bytes: ... diff --git a/mypy/typeshed/stdlib/threading.pyi b/mypy/typeshed/stdlib/threading.pyi index 625ec7b5c4f6..af0b0af89d9b 100644 --- a/mypy/typeshed/stdlib/threading.pyi +++ b/mypy/typeshed/stdlib/threading.pyi @@ -54,7 +54,7 @@ class Thread: target: Optional[Callable[..., Any]] = ..., name: Optional[str] = ..., args: Iterable[Any] = ..., - kwargs: Mapping[str, Any] = ..., + kwargs: Optional[Mapping[str, Any]] = ..., *, daemon: Optional[bool] = ..., ) -> None: ... @@ -65,7 +65,7 @@ class Thread: target: Optional[Callable[..., Any]] = ..., name: Optional[Text] = ..., args: Iterable[Any] = ..., - kwargs: Mapping[Text, Any] = ..., + kwargs: Optional[Mapping[Text, Any]] = ..., ) -> None: ... def start(self) -> None: ... def run(self) -> None: ... @@ -130,14 +130,15 @@ class Condition: class Semaphore: def __init__(self, value: int = ...) -> None: ... - def __enter__(self) -> bool: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType] ) -> Optional[bool]: ... if sys.version_info >= (3,): - def acquire(self, blocking: bool = ..., timeout: float = ...) -> bool: ... + def acquire(self, blocking: bool = ..., timeout: Optional[float] = ...) -> bool: ... + def __enter__(self, blocking: bool = ..., timeout: Optional[float] = ...) -> bool: ... else: def acquire(self, blocking: bool = ...) -> bool: ... + def __enter__(self, blocking: bool = ...) -> bool: ... if sys.version_info >= (3, 9): def release(self, n: int = ...) -> None: ... else: diff --git a/mypy/typeshed/stdlib/timeit.pyi b/mypy/typeshed/stdlib/timeit.pyi index 336dd5c69c69..8de9af28d7ad 100644 --- a/mypy/typeshed/stdlib/timeit.pyi +++ b/mypy/typeshed/stdlib/timeit.pyi @@ -39,4 +39,6 @@ else: stmt: _stmt = ..., setup: _stmt = ..., timer: _Timer = ..., repeat: int = ..., number: int = ... ) -> List[float]: ... -def main(args: Optional[Sequence[str]]) -> None: ... +_timerFunc = Callable[[], float] + +def main(args: Optional[Sequence[str]] = ..., *, _wrap_timer: Optional[Callable[[_timerFunc], _timerFunc]] = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index c5ea645a1e8e..56e8d60b9779 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -349,7 +349,7 @@ class Misc: def bind( self, sequence: Optional[str] = ..., - func: Optional[Callable[[Event[Misc]], Optional[Literal["break"]]]] = ..., + func: Optional[Callable[[Event[Misc]], Any]] = ..., add: Optional[bool] = ..., ) -> str: ... @overload @@ -362,7 +362,7 @@ class Misc: def bind_all( self, sequence: Optional[str] = ..., - func: Optional[Callable[[Event[Misc]], Optional[Literal["break"]]]] = ..., + func: Optional[Callable[[Event[Misc]], Any]] = ..., add: Optional[bool] = ..., ) -> str: ... @overload @@ -374,7 +374,7 @@ class Misc: self, className: str, sequence: Optional[str] = ..., - func: Optional[Callable[[Event[Misc]], Optional[Literal["break"]]]] = ..., + func: Optional[Callable[[Event[Misc]], Any]] = ..., add: Optional[bool] = ..., ) -> str: ... @overload @@ -645,7 +645,7 @@ class Tk(Misc, Wm): # 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] - eval: Callable[[str], str] + def eval(self, __code: str) -> str: ... adderrorinfo: Any createcommand: Any createfilehandler: Any @@ -841,7 +841,7 @@ class Widget(BaseWidget, Pack, Place, Grid): def bind( self: _W, sequence: Optional[str] = ..., - func: Optional[Callable[[Event[_W]], Optional[Literal["break"]]]] = ..., + func: Optional[Callable[[Event[_W]], Any]] = ..., add: Optional[bool] = ..., ) -> str: ... @overload @@ -872,6 +872,7 @@ class Toplevel(BaseWidget, Wm): highlightcolor: _Color = ..., highlightthickness: _ScreenUnits = ..., menu: Menu = ..., + name: str = ..., padx: _ScreenUnits = ..., pady: _ScreenUnits = ..., relief: _Relief = ..., @@ -1100,7 +1101,7 @@ class Canvas(Widget, XView, YView): self, tagOrId: Union[str, int], sequence: Optional[str] = ..., - func: Optional[Callable[[Event[Canvas]], Optional[Literal["break"]]]] = ..., + func: Optional[Callable[[Event[Canvas]], Any]] = ..., add: Optional[bool] = ..., ) -> str: ... @overload @@ -2193,7 +2194,7 @@ class Scale(Widget): tickinterval: float = ..., to: float = ..., troughcolor: _Color = ..., - variable: DoubleVar = ..., + variable: Union[IntVar, DoubleVar] = ..., width: _ScreenUnits = ..., ) -> None: ... @overload @@ -2233,7 +2234,7 @@ class Scale(Widget): tickinterval: float = ..., to: float = ..., troughcolor: _Color = ..., - variable: DoubleVar = ..., + variable: Union[IntVar, DoubleVar] = ..., width: _ScreenUnits = ..., ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... @overload @@ -2503,7 +2504,7 @@ class Text(Widget, XView, YView): def mark_set(self, markName: str, index: _TextIndex) -> None: ... def mark_unset(self, *markNames: str) -> None: ... def mark_next(self, index: _TextIndex) -> Optional[str]: ... - def mark_previous(self, index: _TextIndex): ... + def mark_previous(self, index: _TextIndex) -> Optional[str]: ... # **kw of peer_create is same as the kwargs of Text.__init__ def peer_create(self, newPathName: Union[str, Text], cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... def peer_names(self) -> Tuple[_tkinter.Tcl_Obj, ...]: ... @@ -2531,7 +2532,7 @@ class Text(Widget, XView, YView): self, tagName: str, sequence: Optional[str], - func: Optional[Callable[[Event[Text]], Optional[Literal["break"]]]], + func: Optional[Callable[[Event[Text]], Any]], add: Optional[bool] = ..., ) -> str: ... @overload @@ -2646,7 +2647,7 @@ class PhotoImage(Image): cnf: Dict[str, Any] = ..., master: Optional[Union[Misc, _tkinter.TkappType]] = ..., *, - data: str = ..., # not same as data argument of put() + data: Union[str, bytes] = ..., # not same as data argument of put() format: str = ..., file: AnyPath = ..., gamma: float = ..., @@ -2657,7 +2658,7 @@ class PhotoImage(Image): def configure( self, *, - data: str = ..., + data: Union[str, bytes] = ..., format: str = ..., file: AnyPath = ..., gamma: float = ..., @@ -2689,7 +2690,7 @@ class BitmapImage(Image): master: Optional[Union[Misc, _tkinter.TkappType]] = ..., *, background: _Color = ..., - data: str = ..., + data: Union[str, bytes] = ..., file: AnyPath = ..., foreground: _Color = ..., maskdata: str = ..., diff --git a/mypy/typeshed/stdlib/tkinter/colorchooser.pyi b/mypy/typeshed/stdlib/tkinter/colorchooser.pyi new file mode 100644 index 000000000000..c99c16f0e3bf --- /dev/null +++ b/mypy/typeshed/stdlib/tkinter/colorchooser.pyi @@ -0,0 +1,9 @@ +from tkinter.commondialog import Dialog +from typing import Any, ClassVar, Optional, Tuple, Union + +class Chooser(Dialog): + command: ClassVar[str] + +def askcolor( + color: Optional[Union[str, bytes]] = ..., **options: Any +) -> Union[Tuple[None, None], Tuple[Tuple[float, float, float], str]]: ... diff --git a/mypy/typeshed/stdlib/tkinter/commondialog.pyi b/mypy/typeshed/stdlib/tkinter/commondialog.pyi index d6a8a0d1f5a6..8efefe468b04 100644 --- a/mypy/typeshed/stdlib/tkinter/commondialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/commondialog.pyi @@ -1,7 +1,7 @@ -from typing import Any, Mapping, Optional +from typing import Any, ClassVar, Mapping, Optional class Dialog: - command: Optional[Any] = ... + command: ClassVar[Optional[str]] = ... master: Optional[Any] = ... options: Mapping[str, Any] = ... def __init__(self, master: Optional[Any] = ..., **options) -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/dnd.pyi b/mypy/typeshed/stdlib/tkinter/dnd.pyi new file mode 100644 index 000000000000..7371f91b524e --- /dev/null +++ b/mypy/typeshed/stdlib/tkinter/dnd.pyi @@ -0,0 +1,13 @@ +from _typeshed.tkinter import DndSource +from tkinter import Event, Misc, Tk +from typing import ClassVar, Optional + +class DndHandler: + root: ClassVar[Optional[Tk]] + def __init__(self, source: DndSource, event: Event[Misc]) -> None: ... + def cancel(self, event: Optional[Event[Misc]] = ...) -> None: ... + def finish(self, event: Optional[Event[Misc]], commit: int = ...) -> None: ... + def on_motion(self, event: Event[Misc]) -> None: ... + def on_release(self, event: Event[Misc]) -> None: ... + +def dnd_start(source, event) -> Optional[DndHandler]: ... diff --git a/mypy/typeshed/stdlib/tkinter/filedialog.pyi b/mypy/typeshed/stdlib/tkinter/filedialog.pyi index 8c281c6bdbad..86238f0be798 100644 --- a/mypy/typeshed/stdlib/tkinter/filedialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/filedialog.pyi @@ -1,5 +1,5 @@ from tkinter import Button, Entry, Frame, Listbox, Scrollbar, Toplevel, commondialog -from typing import Any, Dict, Optional, Tuple +from typing import Any, ClassVar, Dict, Optional, Tuple dialogstates: Dict[Any, Tuple[Any, Any]] @@ -49,13 +49,13 @@ class SaveFileDialog(FileDialog): class _Dialog(commondialog.Dialog): ... class Open(_Dialog): - command: str = ... + command: ClassVar[str] = ... class SaveAs(_Dialog): - command: str = ... + command: ClassVar[str] = ... class Directory(commondialog.Dialog): - command: str = ... + command: ClassVar[str] = ... def askopenfilename(**options): ... def asksaveasfilename(**options): ... diff --git a/mypy/typeshed/stdlib/tkinter/font.pyi b/mypy/typeshed/stdlib/tkinter/font.pyi index 791a8a847306..81eacd507202 100644 --- a/mypy/typeshed/stdlib/tkinter/font.pyi +++ b/mypy/typeshed/stdlib/tkinter/font.pyi @@ -9,9 +9,8 @@ ITALIC: Literal["italic"] def nametofont(name: str) -> Font: ... -# See 'FONT DESCRIPTIONS' in font man page. This uses str because Literal -# inside Tuple doesn't work. -_FontDescription = Union[str, Font, Tuple[str, int], Tuple[str, int, str], Tuple[str, int, tkinter._TkinterSequence[str]]] +# Can contain e.g. nested sequences ('FONT DESCRIPTIONS' in font man page) +_FontDescription = Union[str, Font, tkinter._TkinterSequence[Any]] class _FontDict(TypedDict): family: str diff --git a/mypy/typeshed/stdlib/tkinter/messagebox.pyi b/mypy/typeshed/stdlib/tkinter/messagebox.pyi index b44e66081fab..b291a45e87c9 100644 --- a/mypy/typeshed/stdlib/tkinter/messagebox.pyi +++ b/mypy/typeshed/stdlib/tkinter/messagebox.pyi @@ -1,5 +1,5 @@ from tkinter.commondialog import Dialog -from typing import Any, Optional +from typing import Any, ClassVar, Optional ERROR: str INFO: str @@ -19,7 +19,7 @@ YES: str NO: str class Message(Dialog): - command: str = ... + command: ClassVar[str] = ... def showinfo(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> str: ... def showwarning(title: Optional[str] = ..., message: Optional[str] = ..., **options: Any) -> str: ... diff --git a/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi b/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi new file mode 100644 index 000000000000..12c614072ba2 --- /dev/null +++ b/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi @@ -0,0 +1,8 @@ +from tkinter import Frame, Grid, Misc, Pack, Place, Scrollbar, Text +from typing import Any, Optional + +# The methods from Pack, Place, and Grid are dynamically added over the parent's impls +class ScrolledText(Text): + frame: Frame + vbar: Scrollbar + def __init__(self, master: Optional[Misc] = ..., **kwargs: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/simpledialog.pyi b/mypy/typeshed/stdlib/tkinter/simpledialog.pyi new file mode 100644 index 000000000000..b29bb7bfc153 --- /dev/null +++ b/mypy/typeshed/stdlib/tkinter/simpledialog.pyi @@ -0,0 +1,27 @@ +from tkinter import Event, Misc, Toplevel +from typing import Any, List, Optional + +class Dialog(Toplevel): + def __init__(self, parent: Optional[Misc], title: Optional[str] = ...) -> None: ... + def body(self, master) -> None: ... + def buttonbox(self): ... + +class SimpleDialog: + def __init__( + self, + master: Optional[Misc], + text: str = ..., + buttons: List[str] = ..., + default: Optional[int] = ..., + cancel: Optional[int] = ..., + title: Optional[str] = ..., + class_: Optional[str] = ..., + ) -> None: ... + def go(self) -> Optional[int]: ... + def return_event(self, event: Event[Misc]) -> None: ... + def wm_delete_window(self) -> None: ... + def done(self, num: int) -> None: ... + +def askfloat(title: Optional[str], prompt: str, **kwargs: Any) -> float: ... +def askinteger(title: Optional[str], prompt: str, **kwargs: Any) -> int: ... +def askstring(title: Optional[str], prompt: str, **kwargs: Any) -> str: ... diff --git a/mypy/typeshed/stdlib/tkinter/tix.pyi b/mypy/typeshed/stdlib/tkinter/tix.pyi new file mode 100644 index 000000000000..78493900f119 --- /dev/null +++ b/mypy/typeshed/stdlib/tkinter/tix.pyi @@ -0,0 +1,305 @@ +import tkinter +from typing import Any, Dict, List, Optional, Tuple +from typing_extensions import Literal + +WINDOW: Literal["window"] +TEXT: Literal["text"] +STATUS: Literal["status"] +IMMEDIATE: Literal["immediate"] +IMAGE: Literal["image"] +IMAGETEXT: Literal["imagetext"] +BALLOON: Literal["balloon"] +AUTO: Literal["auto"] +ACROSSTOP: Literal["acrosstop"] + +ASCII: Literal["ascii"] +CELL: Literal["cell"] +COLUMN: Literal["column"] +DECREASING: Literal["decreasing"] +INCREASING: Literal["increasing"] +INTEGER: Literal["integer"] +MAIN: Literal["main"] +MAX: Literal["max"] +REAL: Literal["real"] +ROW: Literal["row"] +S_REGION: Literal["s-region"] +X_REGION: Literal["x-region"] +Y_REGION: Literal["y-region"] + +# These should be kept in sync with _tkinter constants, except TCL_ALL_EVENTS which doesn't match ALL_EVENTS +TCL_DONT_WAIT: Literal[2] +TCL_WINDOW_EVENTS: Literal[4] +TCL_FILE_EVENTS: Literal[8] +TCL_TIMER_EVENTS: Literal[16] +TCL_IDLE_EVENTS: Literal[32] +TCL_ALL_EVENTS: Literal[0] + +class tixCommand: + def tix_addbitmapdir(self, directory: str) -> None: ... + def tix_cget(self, option: str) -> Any: ... + def tix_configure(self, cnf: Optional[Dict[str, Any]] = ..., **kw: Any) -> Any: ... + def tix_filedialog(self, dlgclass: Optional[str] = ...) -> str: ... + def tix_getbitmap(self, name: str) -> str: ... + def tix_getimage(self, name: str) -> str: ... + def tix_option_get(self, name: str) -> Any: ... + def tix_resetoptions(self, newScheme: str, newFontSet: str, newScmPrio: Optional[str] = ...) -> None: ... + +class Tk(tkinter.Tk, tixCommand): + def __init__(self, screenName: Optional[str] = ..., baseName: Optional[str] = ..., className: str = ...): ... + +class TixWidget(tkinter.Widget): + def __init__( + self, + master: Optional[tkinter.Misc] = ..., + widgetName: Optional[str] = ..., + static_options: Optional[List[str]] = ..., + cnf: Dict[str, Any] = ..., + kw: Dict[str, Any] = ..., + ) -> None: ... + def __getattr__(self, name: str) -> Any: ... + def set_silent(self, value: str) -> None: ... + def subwidget(self, name: str) -> tkinter.Widget: ... + def subwidgets_all(self) -> List[tkinter.Widget]: ... + def config_all(self, option: Any, value: Any) -> None: ... + def image_create( + self, imgtype: str, cnf: Dict[str, Any] = ..., master: Optional[tkinter.Widget] = ..., **kw: Any + ) -> None: ... + def image_delete(self, imgname: str) -> None: ... + +class TixSubWidget(TixWidget): + def __init__( + self, master: tkinter.Widget, name: str, destroy_physically: int = ..., check_intermediate: int = ... + ) -> None: ... + +class DisplayStyle: + def __init__( + self, itemtype: str, cnf: Dict[str, Any] = ..., *, master: Optional[tkinter.Widget] = ..., **kw: Any + ) -> None: ... + def __getitem__(self, key: str) -> Any: ... + def __setitem__(self, key: str, value: Any) -> None: ... + def delete(self) -> None: ... + def config(self, cnf: Dict[str, Any] = ..., **kw: Any) -> Any: ... + +class Balloon(TixWidget): + def __init__(self, master: Optional[tkinter.Widget] = ..., cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def bind_widget(self, widget: tkinter.Widget, cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def unbind_widget(self, widget: tkinter.Widget) -> None: ... + +class ButtonBox(TixWidget): + def __init__(self, master: Optional[tkinter.Widget] = ..., cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def add(self, name: str, cnf: Dict[str, Any] = ..., **kw: Any) -> tkinter.Widget: ... + def invoke(self, name: str) -> None: ... + +class ComboBox(TixWidget): + def __init__(self, master: Optional[tkinter.Widget] = ..., cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def add_history(self, str: str) -> None: ... + def append_history(self, str: str) -> None: ... + def insert(self, index: int, str: str) -> None: ... + def pick(self, index: int) -> None: ... + +class Control(TixWidget): + def __init__(self, master: Optional[tkinter.Widget] = ..., cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def decrement(self) -> None: ... + def increment(self) -> None: ... + def invoke(self) -> None: ... + +class LabelEntry(TixWidget): + def __init__(self, master: Optional[tkinter.Widget] = ..., cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + +class LabelFrame(TixWidget): + def __init__(self, master: Optional[tkinter.Widget] = ..., cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + +class Meter(TixWidget): + def __init__(self, master: Optional[tkinter.Widget] = ..., cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + +class OptionMenu(TixWidget): + def __init__(self, master: Optional[tkinter.Widget], cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def add_command(self, name: str, cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def add_separator(self, name: str, cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def delete(self, name: str) -> None: ... + def disable(self, name: str) -> None: ... + def enable(self, name: str) -> None: ... + +class PopupMenu(TixWidget): + def __init__(self, master: Optional[tkinter.Widget], cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def bind_widget(self, widget: tkinter.Widget) -> None: ... + def unbind_widget(self, widget: tkinter.Widget) -> None: ... + def post_widget(self, widget: tkinter.Widget, x: int, y: int) -> None: ... + +class Select(TixWidget): + def __init__(self, master: Optional[tkinter.Widget], cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def add(self, name: str, cnf: Dict[str, Any] = ..., **kw: Any) -> tkinter.Widget: ... + def invoke(self, name: str) -> None: ... + +class StdButtonBox(TixWidget): + def __init__(self, master: Optional[tkinter.Widget] = ..., cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def invoke(self, name: str) -> None: ... + +class DirList(TixWidget): + def __init__(self, master: Optional[tkinter.Widget], cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def chdir(self, dir: str) -> None: ... + +class DirTree(TixWidget): + def __init__(self, master: Optional[tkinter.Widget], cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def chdir(self, dir: str) -> None: ... + +class DirSelectDialog(TixWidget): + def __init__(self, master: Optional[tkinter.Widget], cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def popup(self) -> None: ... + def popdown(self) -> None: ... + +class DirSelectBox(TixWidget): + def __init__(self, master: Optional[tkinter.Widget], cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + +class ExFileSelectBox(TixWidget): + def __init__(self, master: Optional[tkinter.Widget], cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def filter(self) -> None: ... + def invoke(self) -> None: ... + +class FileSelectBox(TixWidget): + def __init__(self, master: Optional[tkinter.Widget], cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def apply_filter(self) -> None: ... + def invoke(self) -> None: ... + +class FileEntry(TixWidget): + def __init__(self, master: Optional[tkinter.Widget], cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def invoke(self) -> None: ... + def file_dialog(self) -> None: ... + +class HList(TixWidget, tkinter.XView, tkinter.YView): + def __init__(self, master: Optional[tkinter.Widget] = ..., cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def add(self, entry: str, cnf: Dict[str, Any] = ..., **kw: Any) -> tkinter.Widget: ... + def add_child(self, parent: Optional[str] = ..., cnf: Dict[str, Any] = ..., **kw: Any) -> tkinter.Widget: ... + def anchor_set(self, entry: str) -> None: ... + def anchor_clear(self) -> None: ... + # FIXME: Overload, certain combos return, others don't + def column_width(self, col: int = ..., width: Optional[int] = ..., chars: Optional[int] = ...) -> Optional[int]: ... + def delete_all(self) -> None: ... + def delete_entry(self, entry: str) -> None: ... + def delete_offsprings(self, entry: str) -> None: ... + def delete_siblings(self, entry: str) -> None: ... + def dragsite_set(self, index: int) -> None: ... + def dragsite_clear(self) -> None: ... + def dropsite_set(self, index: int) -> None: ... + def dropsite_clear(self) -> None: ... + def header_create(self, col: int, cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def header_configure(self, col: int, cnf: Dict[str, Any] = ..., **kw: Any) -> Optional[Any]: ... + def header_cget(self, col: int, opt: Any) -> Any: ... + def header_exists(self, col: int) -> bool: ... + def header_exist(self, col: int) -> bool: ... + def header_delete(self, col: int) -> None: ... + def header_size(self, col: int) -> int: ... + def hide_entry(self, entry: str) -> None: ... + def indicator_create(self, entry: str, cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def indicator_configure(self, entry: str, cnf: Dict[str, Any] = ..., **kw: Any) -> Optional[Any]: ... + def indicator_cget(self, entry: str, opt: Any) -> Any: ... + def indicator_exists(self, entry: str) -> bool: ... + def indicator_delete(self, entry: str) -> None: ... + 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: Optional[str] = ...) -> Tuple[str, ...]: ... + def info_data(self, entry: str) -> Any: ... + def info_dragsite(self) -> str: ... + def info_dropsite(self) -> str: ... + def info_exists(self, entry: str) -> bool: ... + def info_hidden(self, entry: str) -> bool: ... + 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 item_cget(self, entry: str, col: int, opt: Any) -> Any: ... + def item_configure(self, entry: str, col: int, cnf: Dict[str, Any] = ..., **kw: Any) -> Optional[Any]: ... + def item_create(self, entry: str, col: int, cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def item_exists(self, entry: str, col: int) -> bool: ... + def item_delete(self, entry: str, col: int) -> None: ... + def entrycget(self, entry: str, opt: Any) -> Any: ... + def entryconfigure(self, entry: str, cnf: Dict[str, Any] = ..., **kw: Any) -> Optional[Any]: ... + def nearest(self, y: int) -> str: ... + def see(self, entry: str) -> None: ... + def selection_clear(self, cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def selection_includes(self, entry: str) -> bool: ... + def selection_set(self, first: str, last: Optional[str] = ...) -> None: ... + def show_entry(self, entry: str) -> None: ... + +class CheckList(TixWidget): + def __init__(self, master: Optional[tkinter.Widget] = ..., cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def autosetmode(self) -> None: ... + 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 getstatus(self, entrypath: str) -> str: ... + def setstatus(self, entrypath: str, mode: str = ...) -> None: ... + +class Tree(TixWidget): + def __init__(self, master: Optional[tkinter.Widget] = ..., cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def autosetmode(self) -> None: ... + def close(self, entrypath: str) -> None: ... + def getmode(self, entrypath: str) -> str: ... + def open(self, entrypath: str) -> None: ... + def setmode(self, entrypath: str, mode: str = ...) -> None: ... + +class TList(TixWidget, tkinter.XView, tkinter.YView): + def __init__(self, master: Optional[tkinter.Widget] = ..., cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def active_set(self, index: int) -> None: ... + def active_clear(self) -> None: ... + def anchor_set(self, index: int) -> None: ... + def anchor_clear(self) -> None: ... + def delete(self, from_: int, to: Optional[int] = ...) -> None: ... + def dragsite_set(self, index: int) -> None: ... + def dragsite_clear(self) -> None: ... + def dropsite_set(self, index: int) -> None: ... + def dropsite_clear(self) -> None: ... + def insert(self, index: int, cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def info_active(self) -> int: ... + def info_anchor(self) -> int: ... + 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_size(self) -> int: ... + def info_up(self, index: int) -> int: ... + def nearest(self, x: int, y: int) -> int: ... + def see(self, index: int) -> None: ... + def selection_clear(self, cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def selection_includes(self, index: int) -> bool: ... + def selection_set(self, first: int, last: Optional[int] = ...) -> None: ... + +class PanedWindow(TixWidget): + def __init__(self, master: Optional[tkinter.Widget], 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 panecget(self, entry: str, opt: Any) -> Any: ... + def paneconfigure(self, entry: str, cnf: Dict[str, Any] = ..., **kw: Any) -> Optional[Any]: ... + def panes(self) -> List[tkinter.Widget]: ... + +class ListNoteBook(TixWidget): + def __init__(self, master: Optional[tkinter.Widget], cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def add(self, name: str, cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def page(self, name: str) -> tkinter.Widget: ... + def pages(self) -> List[tkinter.Widget]: ... + def raise_page(self, name: str) -> None: ... + +class NoteBook(TixWidget): + def __init__(self, master: Optional[tkinter.Widget] = ..., 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 page(self, name: str) -> tkinter.Widget: ... + def pages(self) -> List[tkinter.Widget]: ... + def raise_page(self, name: str) -> None: ... + def raised(self) -> bool: ... + +class InputOnly(TixWidget): + def __init__(self, master: Optional[tkinter.Widget] = ..., cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + +class Form: + def __setitem__(self, key: str, value: Any) -> None: ... + def config(self, cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def form(self, cnf: Dict[str, Any] = ..., **kw: Any) -> None: ... + def check(self) -> bool: ... + def forget(self) -> None: ... + def grid(self, xsize: int = ..., ysize: int = ...) -> Optional[Tuple[int, int]]: ... + def info(self, option: Optional[str] = ...) -> Any: ... + def slaves(self) -> List[tkinter.Widget]: ... diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index 1baac3372644..17aa24197f63 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -582,7 +582,7 @@ class Progressbar(Widget): style: str = ..., takefocus: tkinter._TakeFocusValue = ..., value: float = ..., - variable: tkinter.DoubleVar = ..., + variable: Union[tkinter.IntVar, tkinter.DoubleVar] = ..., ) -> None: ... @overload def configure( @@ -598,7 +598,7 @@ class Progressbar(Widget): style: str = ..., takefocus: tkinter._TakeFocusValue = ..., value: float = ..., - variable: tkinter.DoubleVar = ..., + variable: Union[tkinter.IntVar, tkinter.DoubleVar] = ..., ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... @overload def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... @@ -671,7 +671,7 @@ class Scale(Widget, tkinter.Scale): takefocus: tkinter._TakeFocusValue = ..., to: float = ..., value: float = ..., - variable: tkinter.DoubleVar = ..., + variable: Union[tkinter.IntVar, tkinter.DoubleVar] = ..., ) -> None: ... @overload # type: ignore def configure( @@ -688,7 +688,7 @@ class Scale(Widget, tkinter.Scale): takefocus: tkinter._TakeFocusValue = ..., to: float = ..., value: float = ..., - variable: tkinter.DoubleVar = ..., + variable: Union[tkinter.IntVar, tkinter.DoubleVar] = ..., ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... @overload def configure(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... @@ -708,7 +708,7 @@ class Scale(Widget, tkinter.Scale): takefocus: tkinter._TakeFocusValue = ..., to: float = ..., value: float = ..., - variable: tkinter.DoubleVar = ..., + variable: Union[tkinter.IntVar, tkinter.DoubleVar] = ..., ) -> Optional[Dict[str, Tuple[str, str, str, Any, Any]]]: ... @overload def config(self, cnf: str) -> Tuple[str, str, str, Any, Any]: ... @@ -938,9 +938,9 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def prev(self, item): ... def see(self, item): ... if sys.version_info >= (3, 8): - def selection(self) -> List[Any]: ... + def selection(self) -> Tuple[str, ...]: ... else: - def selection(self, selop: Optional[Any] = ..., items: Optional[Any] = ...) -> List[Any]: ... + def selection(self, selop: Optional[Any] = ..., items: Optional[Any] = ...) -> Tuple[str, ...]: ... def selection_set(self, items): ... def selection_add(self, items): ... def selection_remove(self, items): ... @@ -953,7 +953,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): self, tagname: str, sequence: Optional[str] = ..., - callback: Optional[Callable[[tkinter.Event[Treeview]], Optional[Literal["break"]]]] = ..., + callback: Optional[Callable[[tkinter.Event[Treeview]], Any]] = ..., ) -> str: ... @overload def tag_bind(self, tagname: str, sequence: Optional[str], callback: str) -> None: ... diff --git a/mypy/typeshed/stdlib/trace.pyi b/mypy/typeshed/stdlib/trace.pyi index 6cdb537baa7c..810639869e20 100644 --- a/mypy/typeshed/stdlib/trace.pyi +++ b/mypy/typeshed/stdlib/trace.pyi @@ -1,11 +1,20 @@ import types from _typeshed import StrPath -from typing import Any, Callable, Mapping, Optional, Sequence, Tuple, TypeVar, Union +from typing import Any, Callable, Dict, Mapping, Optional, Sequence, Tuple, TypeVar, Union _T = TypeVar("_T") _localtrace = Callable[[types.FrameType, str, Any], Callable[..., Any]] +_fileModuleFunction = Tuple[str, Optional[str], str] class CoverageResults: + def __init__( + self, + counts: Optional[Dict[Tuple[str, int], int]] = ..., + calledfuncs: Optional[Dict[_fileModuleFunction, int]] = ..., + infile: Optional[StrPath] = ..., + callers: Optional[Dict[Tuple[_fileModuleFunction, _fileModuleFunction], int]] = ..., + outfile: Optional[StrPath] = ..., + ) -> None: ... # undocumented def update(self, other: CoverageResults) -> None: ... def write_results(self, show_missing: bool = ..., summary: bool = ..., coverdir: Optional[StrPath] = ...) -> None: ... def write_results_file( @@ -33,7 +42,7 @@ class Trace: locals: Optional[Mapping[str, Any]] = ..., ) -> None: ... def runfunc(self, func: Callable[..., _T], *args: Any, **kw: Any) -> _T: ... - def file_module_function_of(self, frame: types.FrameType) -> Tuple[str, Optional[str], str]: ... + 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: ... def globaltrace_lt(self, frame: types.FrameType, why: str, arg: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi index 3972ca875fa8..86635427462d 100644 --- a/mypy/typeshed/stdlib/traceback.pyi +++ b/mypy/typeshed/stdlib/traceback.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import SupportsWrite from types import FrameType, TracebackType -from typing import IO, Any, Dict, Generator, Iterable, Iterator, List, Mapping, Optional, Tuple, Type +from typing import IO, Any, Dict, Generator, Iterable, Iterator, List, Mapping, Optional, Set, Tuple, Type _PT = Tuple[str, int, str, Optional[str]] @@ -90,20 +90,45 @@ if sys.version_info >= (3, 5): text: str offset: int msg: str - def __init__( - self, - exc_type: Type[BaseException], - exc_value: BaseException, - exc_traceback: TracebackType, - *, - limit: Optional[int] = ..., - lookup_lines: bool = ..., - capture_locals: bool = ..., - ) -> None: ... - @classmethod - def from_exception( - cls, exc: BaseException, *, limit: Optional[int] = ..., lookup_lines: bool = ..., capture_locals: bool = ... - ) -> TracebackException: ... + if sys.version_info >= (3, 10): + def __init__( + self, + exc_type: Type[BaseException], + exc_value: BaseException, + exc_traceback: TracebackType, + *, + limit: Optional[int] = ..., + lookup_lines: bool = ..., + capture_locals: bool = ..., + compact: bool = ..., + _seen: Optional[Set[int]] = ..., + ) -> None: ... + @classmethod + def from_exception( + cls, + exc: BaseException, + *, + limit: Optional[int] = ..., + lookup_lines: bool = ..., + capture_locals: bool = ..., + compact: bool = ..., + ) -> TracebackException: ... + else: + def __init__( + self, + exc_type: Type[BaseException], + exc_value: BaseException, + exc_traceback: TracebackType, + *, + limit: Optional[int] = ..., + lookup_lines: bool = ..., + capture_locals: bool = ..., + _seen: Optional[Set[int]] = ..., + ) -> None: ... + @classmethod + def from_exception( + cls, exc: BaseException, *, limit: Optional[int] = ..., lookup_lines: bool = ..., capture_locals: bool = ... + ) -> TracebackException: ... def format(self, *, chain: bool = ...) -> Generator[str, None, None]: ... def format_exception_only(self) -> Generator[str, None, None]: ... class FrameSummary(Iterable[Any]): @@ -117,6 +142,7 @@ if sys.version_info >= (3, 5): filename: str, lineno: int, name: str, + *, lookup_line: bool = ..., locals: Optional[Mapping[str, str]] = ..., line: Optional[str] = ..., diff --git a/mypy/typeshed/stdlib/turtle.pyi b/mypy/typeshed/stdlib/turtle.pyi index eee601823a59..a44b25926968 100644 --- a/mypy/typeshed/stdlib/turtle.pyi +++ b/mypy/typeshed/stdlib/turtle.pyi @@ -295,8 +295,6 @@ class _Screen(TurtleScreen): def bye(self) -> None: ... def exitonclick(self) -> None: ... -def Screen() -> _Screen: ... - class Turtle(RawTurtle): def __init__(self, shape: str = ..., undobuffersize: int = ..., visible: bool = ...) -> None: ... @@ -381,6 +379,14 @@ if sys.version_info >= (3,): def onkeypress(fun: Callable[[], Any], key: Optional[str] = ...) -> None: ... onkeyrelease = onkey +# Functions copied from _Screen: + +def setup(width: float = ..., height: float = ..., startx: Optional[int] = ..., starty: Optional[int] = ...) -> None: ... +def title(titlestring: str) -> None: ... +def bye() -> None: ... +def exitonclick() -> None: ... +def Screen() -> _Screen: ... + # Functions copied from TNavigator: def degrees(fullcircle: float = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index d5b419c177ed..7fb0de7acff1 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -1,20 +1,6 @@ import sys -from typing import ( - Any, - Awaitable, - Callable, - Dict, - Generic, - Iterable, - Iterator, - Mapping, - Optional, - Tuple, - Type, - TypeVar, - Union, - overload, -) +import typing +from typing import Any, Awaitable, Callable, Dict, Generic, Iterable, Iterator, Mapping, Optional, Tuple, Type, TypeVar, overload from typing_extensions import Literal, final # ModuleType is exported from this module, but for circular import @@ -160,7 +146,7 @@ class GeneratorType: def send(self, __arg: Any) -> Any: ... @overload def throw( - self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... + self, __typ: Type[BaseException], __val: typing.Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... ) -> Any: ... @overload def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> Any: ... @@ -175,7 +161,7 @@ class AsyncGeneratorType(Generic[_T_co, _T_contra]): def asend(self, __val: _T_contra) -> Awaitable[_T_co]: ... @overload def athrow( - self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... + self, __typ: Type[BaseException], __val: typing.Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... ) -> Awaitable[_T_co]: ... @overload def athrow(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> Awaitable[_T_co]: ... @@ -190,7 +176,7 @@ class CoroutineType: def send(self, __arg: Any) -> Any: ... @overload def throw( - self, __typ: Type[BaseException], __val: Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... + self, __typ: Type[BaseException], __val: typing.Union[BaseException, object] = ..., __tb: Optional[TracebackType] = ... ) -> Any: ... @overload def throw(self, __typ: BaseException, __val: None = ..., __tb: Optional[TracebackType] = ...) -> Any: ... @@ -220,7 +206,7 @@ class MethodType: def __call__(self, *args: Any, **kwargs: Any) -> Any: ... class BuiltinFunctionType: - __self__: Union[object, ModuleType] + __self__: typing.Union[object, ModuleType] __name__: str __qualname__: str def __call__(self, *args: Any, **kwargs: Any) -> Any: ... @@ -287,36 +273,42 @@ class FrameType: class GetSetDescriptorType: __name__: str __objclass__: type - def __get__(self, obj: Any, type: type = ...) -> Any: ... - def __set__(self, obj: Any) -> None: ... + def __get__(self, __obj: Any, __type: type = ...) -> Any: ... + def __set__(self, __instance: Any, __value: Any) -> None: ... def __delete__(self, obj: Any) -> None: ... class MemberDescriptorType: __name__: str __objclass__: type - def __get__(self, obj: Any, type: type = ...) -> Any: ... - def __set__(self, obj: Any) -> None: ... + def __get__(self, __obj: Any, __type: type = ...) -> Any: ... + def __set__(self, __instance: Any, __value: Any) -> None: ... def __delete__(self, obj: Any) -> None: ... if sys.version_info >= (3, 7): def new_class( - name: str, bases: Iterable[object] = ..., kwds: Dict[str, Any] = ..., exec_body: Callable[[Dict[str, Any]], None] = ... + name: str, + bases: Iterable[object] = ..., + kwds: Optional[Dict[str, Any]] = ..., + exec_body: Optional[Callable[[Dict[str, Any]], None]] = ..., ) -> type: ... def resolve_bases(bases: Iterable[object]) -> Tuple[Any, ...]: ... else: def new_class( - name: str, bases: Tuple[type, ...] = ..., kwds: Dict[str, Any] = ..., exec_body: Callable[[Dict[str, Any]], None] = ... + name: str, + bases: Tuple[type, ...] = ..., + kwds: Optional[Dict[str, Any]] = ..., + exec_body: Optional[Callable[[Dict[str, Any]], None]] = ..., ) -> type: ... def prepare_class( - name: str, bases: Tuple[type, ...] = ..., kwds: Dict[str, Any] = ... + name: str, bases: Tuple[type, ...] = ..., kwds: Optional[Dict[str, Any]] = ... ) -> Tuple[type, Dict[str, Any], Dict[str, Any]]: ... # Actually a different type, but `property` is special and we want that too. DynamicClassAttribute = property -def coroutine(f: Callable[..., Any]) -> CoroutineType: ... +def coroutine(func: Callable[..., Any]) -> CoroutineType: ... if sys.version_info >= (3, 9): class GenericAlias: @@ -331,4 +323,8 @@ if sys.version_info >= (3, 10): class NoneType: def __bool__(self) -> Literal[False]: ... EllipsisType = ellipsis # noqa F811 from builtins + from builtins import _NotImplementedType + NotImplementedType = _NotImplementedType # noqa F811 from builtins + class Union: + __args__: Tuple[Any, ...] diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index a2ed53cf9557..03aee05e3216 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -362,7 +362,7 @@ class MutableSet(AbstractSet[_T], Generic[_T]): def __isub__(self, s: AbstractSet[Any]) -> MutableSet[_T]: ... class MappingView(Sized): - def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... # undocumented + def __init__(self, mapping: Mapping[Any, Any]) -> None: ... # undocumented def __len__(self) -> int: ... class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): @@ -381,7 +381,7 @@ class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, def __rxor__(self, o: Iterable[_T]) -> Set[Union[Tuple[_KT_co, _VT_co], _T]]: ... class KeysView(MappingView, AbstractSet[_KT_co], Generic[_KT_co]): - def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... # undocumented + def __init__(self, mapping: Mapping[_KT_co, Any]) -> None: ... # undocumented def __and__(self, o: Iterable[Any]) -> Set[_KT_co]: ... def __rand__(self, o: Iterable[_T]) -> Set[_T]: ... def __contains__(self, o: object) -> bool: ... @@ -396,7 +396,7 @@ class KeysView(MappingView, AbstractSet[_KT_co], Generic[_KT_co]): def __rxor__(self, o: Iterable[_T]) -> Set[Union[_KT_co, _T]]: ... class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): - def __init__(self, mapping: Mapping[_KT_co, _VT_co]) -> None: ... # undocumented + def __init__(self, mapping: Mapping[Any, _VT_co]) -> None: ... # undocumented def __contains__(self, o: object) -> bool: ... def __iter__(self) -> Iterator[_VT_co]: ... if sys.version_info >= (3, 8): @@ -661,12 +661,14 @@ class _TypedDict(Mapping[str, object], metaclass=ABCMeta): # 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: ... + def pop(self, k: NoReturn, default: _T = ...) -> object: ... # type: ignore def update(self: _T, __m: _T) -> None: ... def __delitem__(self, k: NoReturn) -> None: ... 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]: ... diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi new file mode 100644 index 000000000000..8dd41b53908a --- /dev/null +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -0,0 +1,117 @@ +import abc +import sys +from typing import ( + TYPE_CHECKING as TYPE_CHECKING, + Any, + Callable, + ClassVar as ClassVar, + ContextManager as ContextManager, + Counter as Counter, + DefaultDict as DefaultDict, + Deque as Deque, + Dict, + ItemsView, + KeysView, + Mapping, + NewType as NewType, + NoReturn as NoReturn, + Optional, + Text as Text, + Tuple, + Type as Type, + TypeVar, + ValuesView, + overload as overload, +) + +_T = TypeVar("_T") +_F = TypeVar("_F", bound=Callable[..., Any]) +_TC = TypeVar("_TC", bound=Type[object]) + +class _SpecialForm: + def __getitem__(self, typeargs: Any) -> Any: ... + +def runtime_checkable(cls: _TC) -> _TC: ... + +# This alias for above is kept here for backwards compatibility. +runtime = runtime_checkable +Protocol: _SpecialForm = ... +Final: _SpecialForm = ... + +def final(f: _F) -> _F: ... + +Literal: _SpecialForm = ... + +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: ... + # 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: ... + if sys.version_info >= (3, 0): + def items(self) -> ItemsView[str, object]: ... + def keys(self) -> KeysView[str]: ... + def values(self) -> ValuesView[object]: ... + else: + def has_key(self, k: str) -> bool: ... + def viewitems(self) -> ItemsView[str, object]: ... + def viewkeys(self) -> KeysView[str]: ... + def viewvalues(self) -> ValuesView[object]: ... + def __delitem__(self, k: NoReturn) -> None: ... + +# TypedDict is a (non-subscriptable) special form. +TypedDict: object = ... + +if sys.version_info >= (3, 3): + from typing import ChainMap as ChainMap + +if sys.version_info >= (3, 5): + from typing import ( + AsyncContextManager as AsyncContextManager, + AsyncIterable as AsyncIterable, + AsyncIterator as AsyncIterator, + Awaitable as Awaitable, + Coroutine as Coroutine, + ) + +if sys.version_info >= (3, 6): + from typing import AsyncGenerator as AsyncGenerator + +def get_type_hints( + obj: Callable[..., Any], + globalns: Optional[Dict[str, Any]] = ..., + localns: Optional[Dict[str, Any]] = ..., + include_extras: bool = ..., +) -> Dict[str, Any]: ... + +if sys.version_info >= (3, 7): + def get_args(tp: Any) -> Tuple[Any, ...]: ... + def get_origin(tp: Any) -> Optional[Any]: ... + +Annotated: _SpecialForm = ... +_AnnotatedAlias: Any = ... # undocumented + +# TypeAlias is a (non-subscriptable) special form. +class TypeAlias: ... + +@runtime_checkable +class SupportsIndex(Protocol, metaclass=abc.ABCMeta): + @abc.abstractmethod + def __index__(self) -> int: ... + +# PEP 612 support for Python < 3.9 +if sys.version_info >= (3, 10): + from typing import Concatenate as Concatenate, ParamSpec as ParamSpec +else: + class ParamSpec: + __name__: str + def __init__(self, name: str) -> None: ... + Concatenate: _SpecialForm = ... + +# PEP 647 +TypeGuard: _SpecialForm = ... diff --git a/mypy/typeshed/stdlib/unittest/case.pyi b/mypy/typeshed/stdlib/unittest/case.pyi index e3c23f8e97f1..16036264af11 100644 --- a/mypy/typeshed/stdlib/unittest/case.pyi +++ b/mypy/typeshed/stdlib/unittest/case.pyi @@ -2,6 +2,7 @@ import datetime import logging import sys import unittest.result +from collections.abc import Set from types import TracebackType from typing import ( Any, @@ -9,8 +10,6 @@ from typing import ( Callable, Container, ContextManager, - Dict, - FrozenSet, Generic, Iterable, List, @@ -19,7 +18,6 @@ from typing import ( Optional, Pattern, Sequence, - Set, Tuple, Type, TypeVar, @@ -180,10 +178,8 @@ class TestCase: ) -> 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: Union[Set[Any], FrozenSet[Any]], set2: Union[Set[Any], FrozenSet[Any]], msg: Any = ... - ) -> None: ... - def assertDictEqual(self, d1: Dict[Any, Any], d2: Dict[Any, Any], msg: Any = ...) -> None: ... + def assertSetEqual(self, set1: Set[object], set2: Set[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: ... def defaultTestResult(self) -> unittest.result.TestResult: ... diff --git a/mypy/typeshed/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi index cfa9e38a6316..fd767272e66a 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -1,5 +1,5 @@ import sys -from typing import Any, Callable, Generic, List, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, overload +from typing import Any, Callable, Generic, Iterable, List, Mapping, Optional, Sequence, Tuple, Type, TypeVar, Union, overload _F = TypeVar("_F", bound=Callable[..., Any]) _T = TypeVar("_T") @@ -161,63 +161,20 @@ class _patch(Generic[_T]): autospec: Any kwargs: Mapping[str, Any] additional_patchers: Any - if sys.version_info >= (3, 8): - @overload - def __init__( - self: _patch[Union[MagicMock, AsyncMock]], - getter: Callable[[], Any], - attribute: str, - *, - spec: Optional[Any], - create: bool, - spec_set: Optional[Any], - autospec: Optional[Any], - new_callable: Optional[Any], - kwargs: Mapping[str, Any], - ) -> None: ... - # This overload also covers the case, where new==DEFAULT. In this case, 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. - @overload - def __init__( - self: _patch[_T], - getter: Callable[[], Any], - attribute: str, - new: _T, - spec: Optional[Any], - create: bool, - spec_set: Optional[Any], - autospec: Optional[Any], - new_callable: Optional[Any], - kwargs: Mapping[str, Any], - ) -> None: ... - else: - @overload - def __init__( - self: _patch[MagicMock], - getter: Callable[[], Any], - attribute: str, - *, - spec: Optional[Any], - create: bool, - spec_set: Optional[Any], - autospec: Optional[Any], - new_callable: Optional[Any], - kwargs: Mapping[str, Any], - ) -> None: ... - @overload - def __init__( - self: _patch[_T], - getter: Callable[[], Any], - attribute: str, - new: _T, - spec: Optional[Any], - create: bool, - spec_set: Optional[Any], - autospec: Optional[Any], - new_callable: Optional[Any], - kwargs: Mapping[str, Any], - ) -> None: ... + # 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: Optional[Any], + create: bool, + spec_set: Optional[Any], + autospec: Optional[Any], + new_callable: Optional[Any], + kwargs: Mapping[str, Any], + ) -> None: ... def copy(self) -> _patch[_T]: ... def __call__(self, func: Callable[..., _R]) -> Callable[..., _R]: ... def decorate_class(self, klass: _TT) -> _TT: ... @@ -385,7 +342,7 @@ if sys.version_info >= (3, 8): def assert_awaited_with(self, *args: Any, **kwargs: Any) -> None: ... def assert_awaited_once_with(self, *args: Any, **kwargs: Any) -> None: ... def assert_any_await(self, *args: Any, **kwargs: Any) -> None: ... - def assert_has_awaits(self, calls: _CallList, any_order: bool = ...) -> None: ... + def assert_has_awaits(self, calls: Iterable[_Call], any_order: bool = ...) -> None: ... def assert_not_awaited(self) -> None: ... def reset_mock(self, *args: Any, **kwargs: Any) -> None: ... await_count: int diff --git a/mypy/typeshed/stdlib/urllib/error.pyi b/mypy/typeshed/stdlib/urllib/error.pyi index 926f32d03598..d6ef9ff5f94f 100644 --- a/mypy/typeshed/stdlib/urllib/error.pyi +++ b/mypy/typeshed/stdlib/urllib/error.pyi @@ -1,13 +1,17 @@ -from typing import IO, Mapping, Optional, Union +from email.message import Message +from typing import IO, Mapping, Optional, Tuple, Union from urllib.response import addinfourl # Stubs for urllib.error class URLError(IOError): reason: Union[str, BaseException] + def __init__(self, reason: Union[str, BaseException], filename: Optional[str] = ...) -> None: ... class HTTPError(URLError, addinfourl): code: int def __init__(self, url: str, code: int, msg: str, hdrs: Mapping[str, str], fp: Optional[IO[bytes]]) -> None: ... -class ContentTooShortError(URLError): ... +class ContentTooShortError(URLError): + content: Tuple[str, Message] + def __init__(self, message: str, content: Tuple[str, Message]) -> None: ... diff --git a/mypy/typeshed/stdlib/urllib/parse.pyi b/mypy/typeshed/stdlib/urllib/parse.pyi index d9ecfa4b6ac0..00bdb5109044 100644 --- a/mypy/typeshed/stdlib/urllib/parse.pyi +++ b/mypy/typeshed/stdlib/urllib/parse.pyi @@ -79,32 +79,24 @@ class DefragResultBytes(_DefragResultBase[bytes], _ResultMixinBytes): ... class SplitResultBytes(_SplitResultBytesBase, _NetlocResultMixinBytes): ... class ParseResultBytes(_ParseResultBytesBase, _NetlocResultMixinBytes): ... -if sys.version_info >= (3, 8): - def parse_qs( - qs: Optional[AnyStr], - keep_blank_values: bool = ..., - strict_parsing: bool = ..., - encoding: str = ..., - errors: str = ..., - max_num_fields: Optional[int] = ..., - ) -> Dict[AnyStr, List[AnyStr]]: ... - def parse_qsl( - qs: Optional[AnyStr], - keep_blank_values: bool = ..., - strict_parsing: bool = ..., - encoding: str = ..., - errors: str = ..., - max_num_fields: Optional[int] = ..., - ) -> List[Tuple[AnyStr, AnyStr]]: ... - -else: - def parse_qs( - qs: Optional[AnyStr], keep_blank_values: bool = ..., strict_parsing: bool = ..., encoding: str = ..., errors: str = ... - ) -> Dict[AnyStr, List[AnyStr]]: ... - def parse_qsl( - qs: Optional[AnyStr], keep_blank_values: bool = ..., strict_parsing: bool = ..., encoding: str = ..., errors: str = ... - ) -> List[Tuple[AnyStr, AnyStr]]: ... - +def parse_qs( + qs: Optional[AnyStr], + keep_blank_values: bool = ..., + strict_parsing: bool = ..., + encoding: str = ..., + errors: str = ..., + max_num_fields: Optional[int] = ..., + separator: str = ..., +) -> Dict[AnyStr, List[AnyStr]]: ... +def parse_qsl( + qs: Optional[AnyStr], + keep_blank_values: bool = ..., + strict_parsing: bool = ..., + encoding: str = ..., + errors: str = ..., + max_num_fields: Optional[int] = ..., + separator: str = ..., +) -> List[Tuple[AnyStr, AnyStr]]: ... @overload def quote(string: str, safe: _Str = ..., encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ... @overload diff --git a/mypy/typeshed/stdlib/wave.pyi b/mypy/typeshed/stdlib/wave.pyi index c89ba628e59e..d415630427da 100644 --- a/mypy/typeshed/stdlib/wave.pyi +++ b/mypy/typeshed/stdlib/wave.pyi @@ -7,9 +7,7 @@ class Error(Exception): ... WAVE_FORMAT_PCM: int -if sys.version_info < (3, 0): - _wave_params = Tuple[int, int, int, int, str, str] -else: +if sys.version_info >= (3, 0): class _wave_params(NamedTuple): nchannels: int sampwidth: int @@ -18,6 +16,9 @@ else: comptype: str compname: str +else: + _wave_params = Tuple[int, int, int, int, str, str] + class Wave_read: def __init__(self, f: _File) -> None: ... if sys.version_info >= (3, 0): diff --git a/mypy/typeshed/stdlib/weakref.pyi b/mypy/typeshed/stdlib/weakref.pyi index 9dc723388f08..b43b634d6216 100644 --- a/mypy/typeshed/stdlib/weakref.pyi +++ b/mypy/typeshed/stdlib/weakref.pyi @@ -59,24 +59,25 @@ class WeakValueDictionary(MutableMapping[_KT, _VT]): def __iter__(self) -> Iterator[_KT]: ... def __str__(self) -> str: ... def copy(self) -> WeakValueDictionary[_KT, _VT]: ... - if sys.version_info < (3, 0): + if sys.version_info >= (3, 0): + # 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 + else: 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]]: ... - else: - # 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 itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: ... def valuerefs(self) -> List[KeyedRef[_KT, _VT]]: ... class KeyedRef(ref[_T], Generic[_KT, _T]): key: _KT - def __new__(type, ob: _T, callback: Callable[[_T], Any], key: _KT) -> KeyedRef: ... + # This __new__ method uses a non-standard name for the "cls" parameter + def __new__(type, ob: _T, callback: Callable[[_T], Any], key: _KT) -> KeyedRef[_KT, _T]: ... # type: ignore def __init__(self, ob: _T, callback: Callable[[_T], Any], key: _KT) -> None: ... class WeakKeyDictionary(MutableMapping[_KT, _VT]): @@ -94,7 +95,12 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def __iter__(self) -> Iterator[_KT]: ... def __str__(self) -> str: ... def copy(self) -> WeakKeyDictionary[_KT, _VT]: ... - if sys.version_info < (3, 0): + if sys.version_info >= (3, 0): + # 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 + else: def keys(self) -> List[_KT]: ... def values(self) -> List[_VT]: ... def items(self) -> List[Tuple[_KT, _VT]]: ... @@ -102,18 +108,13 @@ class WeakKeyDictionary(MutableMapping[_KT, _VT]): def itervalues(self) -> Iterator[_VT]: ... def iteritems(self) -> Iterator[Tuple[_KT, _VT]]: ... def iterkeyrefs(self) -> Iterator[ref[_KT]]: ... - else: - # 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 keyrefs(self) -> List[ref[_KT]]: ... if sys.version_info >= (3, 4): class finalize: - def __init__(self, __obj: _S, __func: Callable[..., _T], *args: Any, **kwargs: Any) -> None: ... - def __call__(self, _: Any = ...) -> Optional[_T]: ... - def detach(self) -> Optional[Tuple[_S, _T, Tuple[Any, ...], Dict[str, Any]]]: ... - def peek(self) -> Optional[Tuple[_S, _T, Tuple[Any, ...], Dict[str, Any]]]: ... + def __init__(self, __obj: object, __func: Callable[..., Any], *args: Any, **kwargs: Any) -> None: ... + def __call__(self, _: Any = ...) -> Optional[Any]: ... + def detach(self) -> Optional[Tuple[Any, Any, Tuple[Any, ...], Dict[str, Any]]]: ... + def peek(self) -> Optional[Tuple[Any, Any, Tuple[Any, ...], Dict[str, Any]]]: ... alive: bool atexit: bool diff --git a/mypy/typeshed/stdlib/wsgiref/simple_server.pyi b/mypy/typeshed/stdlib/wsgiref/simple_server.pyi index 66cd94fa7f7f..74511ece2bd5 100644 --- a/mypy/typeshed/stdlib/wsgiref/simple_server.pyi +++ b/mypy/typeshed/stdlib/wsgiref/simple_server.pyi @@ -4,10 +4,10 @@ from typing import List, Optional, Type, TypeVar, overload from .handlers import SimpleHandler from .types import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment -if sys.version_info < (3,): - from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer -else: +if sys.version_info >= (3, 0): from http.server import BaseHTTPRequestHandler, HTTPServer +else: + from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer server_version: str # undocumented sys_version: str # undocumented diff --git a/mypy/typeshed/stdlib/wsgiref/util.pyi b/mypy/typeshed/stdlib/wsgiref/util.pyi index 0382fc2854e8..1c66bc1fabdf 100644 --- a/mypy/typeshed/stdlib/wsgiref/util.pyi +++ b/mypy/typeshed/stdlib/wsgiref/util.pyi @@ -10,10 +10,10 @@ class FileWrapper: def __init__(self, filelike: IO[bytes], blksize: int = ...) -> None: ... def __getitem__(self, key: Any) -> bytes: ... def __iter__(self) -> FileWrapper: ... - if sys.version_info < (3,): - def next(self) -> bytes: ... - else: + if sys.version_info >= (3, 0): def __next__(self) -> bytes: ... + else: + def next(self) -> bytes: ... def guess_scheme(environ: WSGIEnvironment) -> str: ... def application_uri(environ: WSGIEnvironment) -> str: ... diff --git a/mypy/typeshed/stdlib/wsgiref/validate.pyi b/mypy/typeshed/stdlib/wsgiref/validate.pyi index 570546e6545d..bc9f0b8c680f 100644 --- a/mypy/typeshed/stdlib/wsgiref/validate.pyi +++ b/mypy/typeshed/stdlib/wsgiref/validate.pyi @@ -9,12 +9,12 @@ def validator(application: WSGIApplication) -> WSGIApplication: ... class InputWrapper: input: InputStream def __init__(self, wsgi_input: InputStream) -> None: ... - if sys.version_info < (3,): - def read(self, size: int = ...) -> bytes: ... - def readline(self) -> bytes: ... - else: + if sys.version_info >= (3, 0): def read(self, size: int) -> bytes: ... def readline(self, size: int = ...) -> bytes: ... + else: + def read(self, size: int = ...) -> bytes: ... + def readline(self) -> bytes: ... def readlines(self, hint: int = ...) -> bytes: ... def __iter__(self) -> Iterable[bytes]: ... def close(self) -> NoReturn: ... @@ -44,9 +44,9 @@ class IteratorWrapper: check_start_response: Optional[bool] def __init__(self, wsgi_iterator: Iterator[bytes], check_start_response: Optional[bool]) -> None: ... def __iter__(self) -> IteratorWrapper: ... - if sys.version_info < (3,): - def next(self) -> bytes: ... - else: + if sys.version_info >= (3, 0): def __next__(self) -> bytes: ... + else: + def next(self) -> bytes: ... def close(self) -> None: ... def __del__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/dom/domreg.pyi b/mypy/typeshed/stdlib/xml/dom/domreg.pyi index 6f479b097b65..bf63ff09e106 100644 --- a/mypy/typeshed/stdlib/xml/dom/domreg.pyi +++ b/mypy/typeshed/stdlib/xml/dom/domreg.pyi @@ -1,5 +1,5 @@ from _typeshed.xml import DOMImplementation -from typing import Any, Callable, Dict, Iterable, Optional, Tuple, Union +from typing import Callable, Dict, Iterable, Optional, Tuple, Union well_known_implementations: Dict[str, str] registered: Dict[str, Callable[[], DOMImplementation]] diff --git a/mypy/typeshed/stdlib/xml/dom/minidom.pyi b/mypy/typeshed/stdlib/xml/dom/minidom.pyi index 7a6eb192b384..dc128e016548 100644 --- a/mypy/typeshed/stdlib/xml/dom/minidom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/minidom.pyi @@ -1,6 +1,6 @@ -from typing import Any, Optional, Text, Union +from typing import IO, Any, Optional, Text, Union from xml.sax.xmlreader import XMLReader -def parse(file: str, parser: Optional[XMLReader] = ..., bufsize: Optional[int] = ...): ... +def parse(file: Union[str, IO[Any]], parser: Optional[XMLReader] = ..., bufsize: Optional[int] = ...): ... def parseString(string: Union[bytes, Text], parser: Optional[XMLReader] = ...): ... def __getattr__(name: str) -> Any: ... # incomplete diff --git a/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi b/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi index 0f269b4e88d3..de49ffcf1209 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementPath.pyi @@ -19,13 +19,13 @@ def prepare_predicate(next: _next, token: _token) -> _callback: ... ops: Dict[str, Callable[[_next, _token], _callback]] class _SelectorContext: - parent_map: Dict[Element, Element] + parent_map: Optional[Dict[Element, Element]] root: Element def __init__(self, root: Element) -> None: ... _T = TypeVar("_T") -def iterfind(elem: Element, path: str, namespaces: Optional[Dict[str, str]] = ...) -> List[Element]: ... +def iterfind(elem: Element, path: str, namespaces: Optional[Dict[str, str]] = ...) -> Generator[Element, None, None]: ... def find(elem: Element, path: str, namespaces: Optional[Dict[str, str]] = ...) -> Optional[Element]: ... def findall(elem: Element, path: str, namespaces: Optional[Dict[str, str]] = ...) -> List[Element]: ... def findtext( diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index b2e2edbe5536..ca4e3832f37e 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -131,7 +131,7 @@ class Element(MutableSequence[Element]): def iter(self, tag: Optional[_str_argument_type] = ...) -> Generator[Element, None, None]: ... def iterfind( self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... - ) -> List[Element]: ... + ) -> 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: ... @@ -192,7 +192,7 @@ class ElementTree: ) -> List[Element]: ... def iterfind( self, path: _str_argument_type, namespaces: Optional[Dict[_str_argument_type, _str_argument_type]] = ... - ) -> List[Element]: ... + ) -> Generator[Element, None, None]: ... if sys.version_info >= (3, 4): def write( self, @@ -308,6 +308,10 @@ else: def tostringlist(element: Element, encoding: Optional[str] = ..., method: Optional[str] = ...) -> List[bytes]: ... def dump(elem: Element) -> None: ... + +if sys.version_info >= (3, 9): + def indent(tree: Union[Element, ElementTree], space: str = ..., level: int = ...) -> None: ... + def parse(source: _file_or_filename, parser: Optional[XMLParser] = ...) -> ElementTree: ... def iterparse( source: _file_or_filename, events: Optional[Sequence[str]] = ..., parser: Optional[XMLParser] = ... diff --git a/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi b/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi index de0d1169a470..9dd6b75fd52f 100644 --- a/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi +++ b/mypy/typeshed/stdlib/xml/sax/xmlreader.pyi @@ -57,7 +57,6 @@ class AttributesImpl: def __len__(self): ... def __getitem__(self, name): ... def keys(self): ... - def has_key(self, name): ... def __contains__(self, name): ... def get(self, name, alternative=...): ... def copy(self): ... diff --git a/mypy/typeshed/stdlib/xmlrpc/client.pyi b/mypy/typeshed/stdlib/xmlrpc/client.pyi index 7bea294bbfab..b0c615063729 100644 --- a/mypy/typeshed/stdlib/xmlrpc/client.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/client.pyi @@ -13,12 +13,15 @@ class _SupportsTimeTuple(Protocol): def timetuple(self) -> time.struct_time: ... _DateTimeComparable = Union[DateTime, datetime, str, _SupportsTimeTuple] -_Marshallable = Union[None, bool, int, float, str, bytes, tuple, list, dict, datetime, DateTime, Binary] +_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 +MAXINT: int # undocumented +MININT: int # undocumented + PARSE_ERROR: int # undocumented SERVER_ERROR: int # undocumented APPLICATION_ERROR: int # undocumented @@ -47,9 +50,9 @@ class ResponseError(Error): ... class Fault(Error): - faultCode: str + faultCode: int faultString: str - def __init__(self, faultCode: str, faultString: str, **extra: Any) -> None: ... + def __init__(self, faultCode: int, faultString: str, **extra: Any) -> None: ... boolean = bool Boolean = bool diff --git a/mypy/typeshed/stdlib/xmlrpc/server.pyi b/mypy/typeshed/stdlib/xmlrpc/server.pyi index 8cdcf499ac2a..f6a097d91d06 100644 --- a/mypy/typeshed/stdlib/xmlrpc/server.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/server.pyi @@ -7,7 +7,7 @@ from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Patte from xmlrpc.client import Fault _Marshallable = Union[ - None, bool, int, float, str, bytes, tuple, list, dict, datetime + None, bool, int, float, str, bytes, Tuple[Any, ...], List[Any], Dict[Any, Any], datetime ] # TODO: Recursive type on tuple, list, dict # The dispatch accepts anywhere from 0 to N arguments, no easy way to allow this in mypy diff --git a/mypy/typeshed/stdlib/zipfile.pyi b/mypy/typeshed/stdlib/zipfile.pyi index 8c02e4a85972..941e79b968f0 100644 --- a/mypy/typeshed/stdlib/zipfile.pyi +++ b/mypy/typeshed/stdlib/zipfile.pyi @@ -59,6 +59,8 @@ class ZipExtFile(io.BufferedIOBase): decrypter: Optional[Callable[[Sequence[int]], bytes]] = ..., close_fileobj: bool = ..., ) -> None: ... + def read(self, n: Optional[int] = ...) -> bytes: ... + def readline(self, limit: int = ...) -> bytes: ... # type: ignore def __repr__(self) -> str: ... def peek(self, n: int = ...) -> bytes: ... def read1(self, n: Optional[int]) -> bytes: ... # type: ignore diff --git a/mypy/typeshed/stdlib/zlib.pyi b/mypy/typeshed/stdlib/zlib.pyi index 3675784675c6..81a9f87ce42e 100644 --- a/mypy/typeshed/stdlib/zlib.pyi +++ b/mypy/typeshed/stdlib/zlib.pyi @@ -1,6 +1,6 @@ import sys from array import array -from typing import Any, Union +from typing import Any, Optional, Union DEFLATED: int DEF_MEM_LEVEL: int @@ -12,9 +12,11 @@ Z_DEFAULT_COMPRESSION: int Z_DEFAULT_STRATEGY: int Z_FILTERED: int Z_FINISH: int +Z_FIXED: int Z_FULL_FLUSH: int Z_HUFFMAN_ONLY: int Z_NO_FLUSH: int +Z_RLE: int Z_SYNC_FLUSH: int if sys.version_info >= (3,): DEF_BUF_SIZE: int @@ -41,7 +43,12 @@ def compress(__data: bytes, level: int = ...) -> bytes: ... if sys.version_info >= (3,): def compressobj( - level: int = ..., method: int = ..., wbits: int = ..., memLevel: int = ..., strategy: int = ..., zdict: bytes = ... + level: int = ..., + method: int = ..., + wbits: int = ..., + memLevel: int = ..., + strategy: int = ..., + zdict: Optional[bytes] = ..., ) -> _Compress: ... else: From 82c95854ba2c59ab200dd39bb62d6e22b6f6fa34 Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Tue, 20 Apr 2021 22:39:13 -0700 Subject: [PATCH 2/2] fix test --- mypy/test/teststubtest.py | 1 - 1 file changed, 1 deletion(-) diff --git a/mypy/test/teststubtest.py b/mypy/test/teststubtest.py index bf830493c97c..6ef6badc4ae7 100644 --- a/mypy/test/teststubtest.py +++ b/mypy/test/teststubtest.py @@ -832,7 +832,6 @@ def test_get_typeshed_stdlib_modules(self) -> None: assert "os" in stdlib assert "os.path" in stdlib assert "mypy_extensions" not in stdlib - assert "typing_extensions" not in stdlib assert "asyncio" in stdlib assert ("dataclasses" in stdlib) == (sys.version_info >= (3, 7))