From e33da71ddfe9346fcb5e229728dd32230b27b892 Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Tue, 14 Jun 2022 13:15:04 -0700 Subject: [PATCH 1/2] Sync typeshed Source commit: https://github.com/python/typeshed/commit/91d6383d9d1ca38157ce46bb498a11347658db1d --- mypy/typeshed/stdlib/@python2/ssl.pyi | 7 +- mypy/typeshed/stdlib/VERSIONS | 1 + mypy/typeshed/stdlib/__future__.pyi | 40 +- mypy/typeshed/stdlib/_ast.pyi | 2 + mypy/typeshed/stdlib/_codecs.pyi | 63 +- mypy/typeshed/stdlib/_dummy_thread.pyi | 10 + mypy/typeshed/stdlib/_dummy_threading.pyi | 74 +-- mypy/typeshed/stdlib/_imp.pyi | 10 +- mypy/typeshed/stdlib/_pydecimal.pyi | 118 ++-- mypy/typeshed/stdlib/_typeshed/__init__.pyi | 22 +- mypy/typeshed/stdlib/_weakrefset.pyi | 7 +- mypy/typeshed/stdlib/argparse.pyi | 131 +++-- mypy/typeshed/stdlib/array.pyi | 20 +- mypy/typeshed/stdlib/ast.pyi | 3 + mypy/typeshed/stdlib/asyncio/__init__.pyi | 1 + mypy/typeshed/stdlib/asyncio/base_events.pyi | 147 ++++- mypy/typeshed/stdlib/asyncio/constants.pyi | 4 + mypy/typeshed/stdlib/asyncio/events.pyi | 202 ++++++- mypy/typeshed/stdlib/asyncio/exceptions.pyi | 32 +- mypy/typeshed/stdlib/asyncio/futures.pyi | 1 + mypy/typeshed/stdlib/asyncio/locks.pyi | 59 +- mypy/typeshed/stdlib/asyncio/mixins.pyi | 4 +- mypy/typeshed/stdlib/asyncio/protocols.pyi | 3 +- mypy/typeshed/stdlib/asyncio/queues.pyi | 6 +- mypy/typeshed/stdlib/asyncio/runners.pyi | 27 +- mypy/typeshed/stdlib/asyncio/sslproto.pyi | 74 ++- mypy/typeshed/stdlib/asyncio/streams.pyi | 5 + mypy/typeshed/stdlib/asyncio/taskgroups.pyi | 5 +- mypy/typeshed/stdlib/asyncio/tasks.pyi | 18 +- mypy/typeshed/stdlib/asyncio/timeouts.pyi | 19 + mypy/typeshed/stdlib/asyncio/trsock.pyi | 2 +- mypy/typeshed/stdlib/base64.pyi | 65 +-- mypy/typeshed/stdlib/bdb.pyi | 5 + mypy/typeshed/stdlib/binascii.pyi | 7 +- mypy/typeshed/stdlib/builtins.pyi | 213 +++++-- mypy/typeshed/stdlib/calendar.pyi | 88 +-- mypy/typeshed/stdlib/cgi.pyi | 50 +- mypy/typeshed/stdlib/codecs.pyi | 98 +--- mypy/typeshed/stdlib/collections/__init__.pyi | 45 +- .../stdlib/concurrent/futures/process.pyi | 48 +- mypy/typeshed/stdlib/contextlib.pyi | 80 +-- mypy/typeshed/stdlib/contextvars.pyi | 5 +- mypy/typeshed/stdlib/csv.pyi | 11 +- mypy/typeshed/stdlib/ctypes/__init__.pyi | 2 +- mypy/typeshed/stdlib/dataclasses.pyi | 67 ++- mypy/typeshed/stdlib/difflib.pyi | 11 +- mypy/typeshed/stdlib/dis.pyi | 28 +- .../stdlib/distutils/command/check.pyi | 3 +- mypy/typeshed/stdlib/distutils/filelist.pyi | 12 +- mypy/typeshed/stdlib/enum.pyi | 67 ++- mypy/typeshed/stdlib/filecmp.pyi | 14 +- mypy/typeshed/stdlib/fileinput.pyi | 240 +++++++- mypy/typeshed/stdlib/fractions.pyi | 7 +- mypy/typeshed/stdlib/ftplib.pyi | 2 +- mypy/typeshed/stdlib/functools.pyi | 69 +-- mypy/typeshed/stdlib/genericpath.pyi | 4 +- mypy/typeshed/stdlib/gettext.pyi | 141 ++--- mypy/typeshed/stdlib/graphlib.pyi | 7 +- mypy/typeshed/stdlib/hmac.pyi | 2 +- mypy/typeshed/stdlib/imaplib.pyi | 2 +- mypy/typeshed/stdlib/importlib/abc.pyi | 16 + .../stdlib/importlib/metadata/__init__.pyi | 41 +- .../stdlib/importlib/metadata/_meta.pyi | 6 +- mypy/typeshed/stdlib/importlib/resources.pyi | 42 +- mypy/typeshed/stdlib/io.pyi | 64 +-- mypy/typeshed/stdlib/itertools.pyi | 2 +- .../stdlib/lib2to3/pgen2/tokenize.pyi | 216 +++---- mypy/typeshed/stdlib/locale.pyi | 8 +- mypy/typeshed/stdlib/logging/__init__.pyi | 20 +- mypy/typeshed/stdlib/logging/handlers.pyi | 3 + mypy/typeshed/stdlib/macpath.pyi | 35 ++ mypy/typeshed/stdlib/macurl2path.pyi | 2 + mypy/typeshed/stdlib/mailbox.pyi | 7 +- mypy/typeshed/stdlib/mmap.pyi | 2 +- mypy/typeshed/stdlib/modulefinder.pyi | 13 +- .../stdlib/multiprocessing/__init__.pyi | 118 ++-- .../stdlib/multiprocessing/managers.pyi | 82 ++- .../stdlib/multiprocessing/shared_memory.pyi | 7 +- mypy/typeshed/stdlib/ntpath.pyi | 131 ++--- mypy/typeshed/stdlib/operator.pyi | 172 ++---- mypy/typeshed/stdlib/optparse.pyi | 5 +- mypy/typeshed/stdlib/os/__init__.pyi | 13 +- mypy/typeshed/stdlib/pdb.pyi | 6 +- mypy/typeshed/stdlib/pickle.pyi | 247 +++----- mypy/typeshed/stdlib/posixpath.pyi | 39 +- mypy/typeshed/stdlib/pydoc.pyi | 42 +- mypy/typeshed/stdlib/pyexpat/__init__.pyi | 3 + mypy/typeshed/stdlib/pyexpat/errors.pyi | 9 + mypy/typeshed/stdlib/random.pyi | 86 +-- mypy/typeshed/stdlib/re.pyi | 129 ++--- mypy/typeshed/stdlib/shutil.pyi | 12 +- mypy/typeshed/stdlib/smtplib.pyi | 49 +- mypy/typeshed/stdlib/socket.pyi | 64 ++- mypy/typeshed/stdlib/socketserver.pyi | 48 +- mypy/typeshed/stdlib/sqlite3/dbapi2.pyi | 18 +- mypy/typeshed/stdlib/sre_constants.pyi | 3 +- mypy/typeshed/stdlib/sre_parse.pyi | 8 +- mypy/typeshed/stdlib/ssl.pyi | 7 +- mypy/typeshed/stdlib/statistics.pyi | 76 +-- mypy/typeshed/stdlib/string.pyi | 3 + mypy/typeshed/stdlib/subprocess.pyi | 246 ++++---- mypy/typeshed/stdlib/symtable.pyi | 7 +- mypy/typeshed/stdlib/sys.pyi | 3 + mypy/typeshed/stdlib/tarfile.pyi | 4 +- mypy/typeshed/stdlib/tempfile.pyi | 130 +++-- mypy/typeshed/stdlib/termios.pyi | 3 + mypy/typeshed/stdlib/threading.pyi | 114 ++-- mypy/typeshed/stdlib/tkinter/__init__.pyi | 70 +-- mypy/typeshed/stdlib/tkinter/ttk.pyi | 82 +-- mypy/typeshed/stdlib/token.pyi | 351 +++--------- mypy/typeshed/stdlib/tokenize.pyi | 376 +++--------- mypy/typeshed/stdlib/traceback.pyi | 47 +- mypy/typeshed/stdlib/turtle.pyi | 21 +- mypy/typeshed/stdlib/types.pyi | 332 +++++------ mypy/typeshed/stdlib/typing.pyi | 540 +++--------------- mypy/typeshed/stdlib/typing_extensions.pyi | 4 +- mypy/typeshed/stdlib/unicodedata.pyi | 3 + mypy/typeshed/stdlib/unittest/__init__.pyi | 80 +-- mypy/typeshed/stdlib/unittest/async_case.pyi | 8 + mypy/typeshed/stdlib/unittest/case.pyi | 72 ++- mypy/typeshed/stdlib/unittest/mock.pyi | 8 +- mypy/typeshed/stdlib/urllib/parse.pyi | 3 +- mypy/typeshed/stdlib/urllib/request.pyi | 9 + .../typeshed/stdlib/xml/etree/ElementTree.pyi | 129 ++--- mypy/typeshed/stdlib/xml/sax/handler.pyi | 40 +- mypy/typeshed/stdlib/xmlrpc/server.pyi | 5 +- mypy/typeshed/stdlib/zipfile.pyi | 82 +-- .../stubs/mypy-extensions/mypy_extensions.pyi | 38 +- 128 files changed, 3473 insertions(+), 3698 deletions(-) create mode 100644 mypy/typeshed/stdlib/asyncio/timeouts.pyi diff --git a/mypy/typeshed/stdlib/@python2/ssl.pyi b/mypy/typeshed/stdlib/@python2/ssl.pyi index 2c6b32567249..edc22ff1515a 100644 --- a/mypy/typeshed/stdlib/@python2/ssl.pyi +++ b/mypy/typeshed/stdlib/@python2/ssl.pyi @@ -225,7 +225,12 @@ class SSLContext: def load_verify_locations( self, cafile: StrPath | None = ..., capath: StrPath | None = ..., cadata: Text | bytes | None = ... ) -> None: ... - def get_ca_certs(self, binary_form: bool = ...) -> list[_PeerCertRetDictType] | list[bytes]: ... + @overload + def get_ca_certs(self, binary_form: Literal[False] = ...) -> list[_PeerCertRetDictType]: ... + @overload + def get_ca_certs(self, binary_form: Literal[True]) -> list[bytes]: ... + @overload + def get_ca_certs(self, binary_form: bool = ...) -> Any: ... def set_default_verify_paths(self) -> None: ... def set_ciphers(self, __cipherlist: str) -> None: ... def set_alpn_protocols(self, alpn_protocols: Iterable[str]) -> None: ... diff --git a/mypy/typeshed/stdlib/VERSIONS b/mypy/typeshed/stdlib/VERSIONS index eefc7b895436..acf392d97816 100644 --- a/mypy/typeshed/stdlib/VERSIONS +++ b/mypy/typeshed/stdlib/VERSIONS @@ -70,6 +70,7 @@ asyncio.runners: 3.7- asyncio.staggered: 3.8- asyncio.taskgroups: 3.11- asyncio.threads: 3.9- +asyncio.timeouts: 3.11- asyncio.trsock: 3.8- asyncore: 2.7- atexit: 2.7- diff --git a/mypy/typeshed/stdlib/__future__.pyi b/mypy/typeshed/stdlib/__future__.pyi index 1a465c3e213d..52941a0c5229 100644 --- a/mypy/typeshed/stdlib/__future__.pyi +++ b/mypy/typeshed/stdlib/__future__.pyi @@ -21,30 +21,18 @@ if sys.version_info >= (3, 7): all_feature_names: list[str] # undocumented +__all__ = [ + "all_feature_names", + "absolute_import", + "division", + "generators", + "nested_scopes", + "print_function", + "unicode_literals", + "with_statement", + "barry_as_FLUFL", + "generator_stop", +] + if sys.version_info >= (3, 7): - __all__ = [ - "all_feature_names", - "absolute_import", - "division", - "generators", - "nested_scopes", - "print_function", - "unicode_literals", - "with_statement", - "barry_as_FLUFL", - "generator_stop", - "annotations", - ] -else: - __all__ = [ - "all_feature_names", - "absolute_import", - "division", - "generators", - "nested_scopes", - "print_function", - "unicode_literals", - "with_statement", - "barry_as_FLUFL", - "generator_stop", - ] + __all__ += ["annotations"] diff --git a/mypy/typeshed/stdlib/_ast.pyi b/mypy/typeshed/stdlib/_ast.pyi index 1305b0c94d9b..81cb9ffbf26e 100644 --- a/mypy/typeshed/stdlib/_ast.pyi +++ b/mypy/typeshed/stdlib/_ast.pyi @@ -415,6 +415,8 @@ class Tuple(expr): __match_args__ = ("elts", "ctx") elts: list[expr] ctx: expr_context + if sys.version_info >= (3, 9): + dims: list[expr] class expr_context(AST): ... diff --git a/mypy/typeshed/stdlib/_codecs.pyi b/mypy/typeshed/stdlib/_codecs.pyi index e335f6d5119a..8fabf94d827e 100644 --- a/mypy/typeshed/stdlib/_codecs.pyi +++ b/mypy/typeshed/stdlib/_codecs.pyi @@ -1,22 +1,71 @@ import codecs import sys from collections.abc import Callable -from typing import Any -from typing_extensions import TypeAlias +from typing import overload +from typing_extensions import Literal, TypeAlias # This type is not exposed; it is defined in unicodeobject.c class _EncodingMap: def size(self) -> int: ... _MapT: TypeAlias = dict[int, int] | _EncodingMap -_Handler: TypeAlias = Callable[[Exception], tuple[str, int]] +_Handler: TypeAlias = Callable[[UnicodeError], tuple[str | bytes, int]] +_SearchFunction: TypeAlias = Callable[[str], codecs.CodecInfo | None] + +def register(__search_function: _SearchFunction) -> None: ... + +if sys.version_info >= (3, 10): + def unregister(__search_function: _SearchFunction) -> None: ... -def register(__search_function: Callable[[str], Any]) -> None: ... def register_error(__errors: str, __handler: _Handler) -> None: ... -def lookup(__encoding: str) -> codecs.CodecInfo: ... def lookup_error(__name: str) -> _Handler: ... -def decode(obj: Any, encoding: str = ..., errors: str | None = ...) -> Any: ... -def encode(obj: Any, encoding: str = ..., errors: str | None = ...) -> Any: ... + +# The type ignore on `encode` and `decode` is to avoid issues with overlapping overloads, for more details, see #300 +# https://docs.python.org/3/library/codecs.html#binary-transforms +_BytesToBytesEncoding: TypeAlias = Literal[ + "base64", + "base_64", + "base64_codec", + "bz2", + "bz2_codec", + "hex", + "hex_codec", + "quopri", + "quotedprintable", + "quoted_printable", + "quopri_codec", + "uu", + "uu_codec", + "zip", + "zlib", + "zlib_codec", +] +# https://docs.python.org/3/library/codecs.html#text-transforms +_StrToStrEncoding: TypeAlias = Literal["rot13", "rot_13"] + +@overload +def encode(obj: bytes, encoding: _BytesToBytesEncoding, errors: str = ...) -> bytes: ... +@overload +def encode(obj: str, encoding: _StrToStrEncoding, errors: str = ...) -> str: ... # type: ignore[misc] +@overload +def encode(obj: str, encoding: str = ..., errors: str = ...) -> bytes: ... +@overload +def decode(obj: bytes, encoding: _BytesToBytesEncoding, errors: str = ...) -> bytes: ... # type: ignore[misc] +@overload +def decode(obj: str, encoding: _StrToStrEncoding, errors: str = ...) -> str: ... + +# these are documented as text encodings but in practice they also accept str as input +@overload +def decode( + obj: str, encoding: Literal["unicode_escape", "unicode-escape", "raw_unicode_escape", "raw-unicode-escape"], errors: str = ... +) -> str: ... + +# hex is officially documented as a bytes to bytes encoding, but it appears to also work with str +@overload +def decode(obj: str, encoding: Literal["hex", "hex_codec"], errors: str = ...) -> bytes: ... +@overload +def decode(obj: bytes, encoding: str = ..., errors: str = ...) -> str: ... +def lookup(__encoding: str) -> codecs.CodecInfo: ... def charmap_build(__map: str) -> _MapT: ... def ascii_decode(__data: bytes, __errors: str | None = ...) -> tuple[str, int]: ... def ascii_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... diff --git a/mypy/typeshed/stdlib/_dummy_thread.pyi b/mypy/typeshed/stdlib/_dummy_thread.pyi index f257b758eeab..4bcf84964add 100644 --- a/mypy/typeshed/stdlib/_dummy_thread.pyi +++ b/mypy/typeshed/stdlib/_dummy_thread.pyi @@ -1,7 +1,13 @@ +import sys from collections.abc import Callable from types import TracebackType from typing import Any, NoReturn +__all__ = ["error", "start_new_thread", "exit", "get_ident", "allocate_lock", "interrupt_main", "LockType"] + +if sys.version_info >= (3, 7): + __all__ += ["RLock"] + TIMEOUT_MAX: int error = RuntimeError @@ -20,4 +26,8 @@ class LockType: def release(self) -> bool: ... def locked(self) -> bool: ... +if sys.version_info >= (3, 7): + class RLock(LockType): + def release(self) -> None: ... # type: ignore[override] + def interrupt_main() -> None: ... diff --git a/mypy/typeshed/stdlib/_dummy_threading.pyi b/mypy/typeshed/stdlib/_dummy_threading.pyi index 2daceaedd4ad..6f888b3dda70 100644 --- a/mypy/typeshed/stdlib/_dummy_threading.pyi +++ b/mypy/typeshed/stdlib/_dummy_threading.pyi @@ -10,56 +10,32 @@ _TF: TypeAlias = Callable[[FrameType, str, Any], Callable[..., Any] | None] _PF: TypeAlias = Callable[[FrameType, str, Any], None] _T = TypeVar("_T") +__all__ = [ + "get_ident", + "active_count", + "Condition", + "current_thread", + "enumerate", + "main_thread", + "TIMEOUT_MAX", + "Event", + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Thread", + "Barrier", + "BrokenBarrierError", + "Timer", + "ThreadError", + "setprofile", + "settrace", + "local", + "stack_size", +] + if sys.version_info >= (3, 8): - __all__ = [ - "get_ident", - "active_count", - "Condition", - "current_thread", - "enumerate", - "main_thread", - "TIMEOUT_MAX", - "Event", - "Lock", - "RLock", - "Semaphore", - "BoundedSemaphore", - "Thread", - "Barrier", - "BrokenBarrierError", - "Timer", - "ThreadError", - "setprofile", - "settrace", - "local", - "stack_size", - "excepthook", - "ExceptHookArgs", - ] -else: - __all__ = [ - "get_ident", - "active_count", - "Condition", - "current_thread", - "enumerate", - "main_thread", - "TIMEOUT_MAX", - "Event", - "Lock", - "RLock", - "Semaphore", - "BoundedSemaphore", - "Thread", - "Barrier", - "BrokenBarrierError", - "Timer", - "ThreadError", - "setprofile", - "settrace", - "local", - "stack_size", - ] + __all__ += ["ExceptHookArgs", "excepthook"] def active_count() -> int: ... def current_thread() -> Thread: ... diff --git a/mypy/typeshed/stdlib/_imp.pyi b/mypy/typeshed/stdlib/_imp.pyi index e2bbb9385ceb..856188dfbcd2 100644 --- a/mypy/typeshed/stdlib/_imp.pyi +++ b/mypy/typeshed/stdlib/_imp.pyi @@ -1,10 +1,12 @@ import sys import types +from _typeshed import ReadableBuffer from importlib.machinery import ModuleSpec from typing import Any if sys.version_info >= (3, 7): check_hash_based_pycs: str + def source_hash(key: int, source: ReadableBuffer) -> bytes: ... def create_builtin(__spec: ModuleSpec) -> types.ModuleType: ... def create_dynamic(__spec: ModuleSpec, __file: Any = ...) -> types.ModuleType: ... @@ -12,10 +14,16 @@ def acquire_lock() -> None: ... def exec_builtin(__mod: types.ModuleType) -> int: ... def exec_dynamic(__mod: types.ModuleType) -> int: ... def extension_suffixes() -> list[str]: ... -def get_frozen_object(__name: str) -> types.CodeType: ... def init_frozen(__name: str) -> types.ModuleType: ... def is_builtin(__name: str) -> int: ... def is_frozen(__name: str) -> bool: ... def is_frozen_package(__name: str) -> bool: ... def lock_held() -> bool: ... def release_lock() -> None: ... + +if sys.version_info >= (3, 11): + def find_frozen(__name: str, *, withdata: bool = ...) -> tuple[memoryview | None, bool, str | None] | None: ... + def get_frozen_object(__name: str, __data: ReadableBuffer | None = ...) -> types.CodeType: ... + +else: + def get_frozen_object(__name: str) -> types.CodeType: ... diff --git a/mypy/typeshed/stdlib/_pydecimal.pyi b/mypy/typeshed/stdlib/_pydecimal.pyi index 90dbef1dc2e2..0d639bc164d4 100644 --- a/mypy/typeshed/stdlib/_pydecimal.pyi +++ b/mypy/typeshed/stdlib/_pydecimal.pyi @@ -4,82 +4,44 @@ import sys # However, in all likelihood, the differences are inconsequential from _decimal import * +__all__ = [ + "Decimal", + "Context", + "DecimalTuple", + "DefaultContext", + "BasicContext", + "ExtendedContext", + "DecimalException", + "Clamped", + "InvalidOperation", + "DivisionByZero", + "Inexact", + "Rounded", + "Subnormal", + "Overflow", + "Underflow", + "FloatOperation", + "DivisionImpossible", + "InvalidContext", + "ConversionSyntax", + "DivisionUndefined", + "ROUND_DOWN", + "ROUND_HALF_UP", + "ROUND_HALF_EVEN", + "ROUND_CEILING", + "ROUND_FLOOR", + "ROUND_UP", + "ROUND_HALF_DOWN", + "ROUND_05UP", + "setcontext", + "getcontext", + "localcontext", + "MAX_PREC", + "MAX_EMAX", + "MIN_EMIN", + "MIN_ETINY", + "HAVE_THREADS", +] + if sys.version_info >= (3, 7): - __all__ = [ - "Decimal", - "Context", - "DecimalTuple", - "DefaultContext", - "BasicContext", - "ExtendedContext", - "DecimalException", - "Clamped", - "InvalidOperation", - "DivisionByZero", - "Inexact", - "Rounded", - "Subnormal", - "Overflow", - "Underflow", - "FloatOperation", - "DivisionImpossible", - "InvalidContext", - "ConversionSyntax", - "DivisionUndefined", - "ROUND_DOWN", - "ROUND_HALF_UP", - "ROUND_HALF_EVEN", - "ROUND_CEILING", - "ROUND_FLOOR", - "ROUND_UP", - "ROUND_HALF_DOWN", - "ROUND_05UP", - "setcontext", - "getcontext", - "localcontext", - "MAX_PREC", - "MAX_EMAX", - "MIN_EMIN", - "MIN_ETINY", - "HAVE_THREADS", - "HAVE_CONTEXTVAR", - ] -else: - __all__ = [ - "Decimal", - "Context", - "DecimalTuple", - "DefaultContext", - "BasicContext", - "ExtendedContext", - "DecimalException", - "Clamped", - "InvalidOperation", - "DivisionByZero", - "Inexact", - "Rounded", - "Subnormal", - "Overflow", - "Underflow", - "FloatOperation", - "DivisionImpossible", - "InvalidContext", - "ConversionSyntax", - "DivisionUndefined", - "ROUND_DOWN", - "ROUND_HALF_UP", - "ROUND_HALF_EVEN", - "ROUND_CEILING", - "ROUND_FLOOR", - "ROUND_UP", - "ROUND_HALF_DOWN", - "ROUND_05UP", - "setcontext", - "getcontext", - "localcontext", - "MAX_PREC", - "MAX_EMAX", - "MIN_EMIN", - "MIN_ETINY", - "HAVE_THREADS", - ] + __all__ += ["HAVE_CONTEXTVAR"] diff --git a/mypy/typeshed/stdlib/_typeshed/__init__.pyi b/mypy/typeshed/stdlib/_typeshed/__init__.pyi index d5e0c691e8c0..162c40522224 100644 --- a/mypy/typeshed/stdlib/_typeshed/__init__.pyi +++ b/mypy/typeshed/stdlib/_typeshed/__init__.pyi @@ -10,8 +10,8 @@ import sys from collections.abc import Awaitable, Container, Iterable, Set as AbstractSet from os import PathLike from types import TracebackType -from typing import Any, Generic, Protocol, TypeVar, Union -from typing_extensions import Final, Literal, TypeAlias, final +from typing import Any, AnyStr, Generic, Protocol, TypeVar, Union +from typing_extensions import Final, Literal, LiteralString, TypeAlias, final _KT = TypeVar("_KT") _KT_co = TypeVar("_KT_co", covariant=True) @@ -26,6 +26,9 @@ _T_contra = TypeVar("_T_contra", contravariant=True) # def __enter__(self: Self) -> Self: ... Self = TypeVar("Self") # noqa: Y001 +# covariant version of typing.AnyStr, useful for protocols +AnyStr_co = TypeVar("AnyStr_co", str, bytes, covariant=True) # noqa: Y001 + # For partially known annotations. Usually, fields where type annotations # haven't been added are left unannotated, but in some situations this # isn't possible or a type is already partially known. In cases like these, @@ -66,8 +69,14 @@ SupportsRichComparisonT = TypeVar("SupportsRichComparisonT", bound=SupportsRichC # Dunder protocols -class SupportsAdd(Protocol): - def __add__(self, __x: Any) -> Any: ... +class SupportsAdd(Protocol[_T_contra, _T_co]): + def __add__(self, __x: _T_contra) -> _T_co: ... + +class SupportsRAdd(Protocol[_T_contra, _T_co]): + def __radd__(self, __x: _T_contra) -> _T_co: ... + +class SupportsSub(Protocol[_T_contra, _T_co]): + def __sub__(self, __x: _T_contra) -> _T_co: ... class SupportsDivMod(Protocol[_T_contra, _T_co]): def __divmod__(self, __other: _T_contra) -> _T_co: ... @@ -112,9 +121,9 @@ class SupportsItemAccess(SupportsGetItem[_KT_contra, _VT], Protocol[_KT_contra, def __setitem__(self, __k: _KT_contra, __v: _VT) -> None: ... def __delitem__(self, __v: _KT_contra) -> None: ... -# These aliases are simple strings in Python 2. StrPath: TypeAlias = str | PathLike[str] # stable BytesPath: TypeAlias = bytes | PathLike[bytes] # stable +GenericPath: TypeAlias = AnyStr | PathLike[AnyStr] StrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes] # stable OpenTextModeUpdating: TypeAlias = Literal[ @@ -248,3 +257,6 @@ class structseq(Generic[_T_co]): # but only has any meaning if you supply it a dict where the keys are strings. # https://github.com/python/typeshed/pull/6560#discussion_r767149830 def __new__(cls: type[Self], sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> Self: ... + +# Superset of typing.AnyStr that also inclues LiteralString +AnyOrLiteralStr = TypeVar("AnyOrLiteralStr", str, bytes, LiteralString) # noqa: Y001 diff --git a/mypy/typeshed/stdlib/_weakrefset.pyi b/mypy/typeshed/stdlib/_weakrefset.pyi index 382dbdeb6c8a..9e9269758b00 100644 --- a/mypy/typeshed/stdlib/_weakrefset.pyi +++ b/mypy/typeshed/stdlib/_weakrefset.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Self from collections.abc import Iterable, Iterator, MutableSet -from typing import Any, Generic, TypeVar +from typing import Any, Generic, TypeVar, overload if sys.version_info >= (3, 9): from types import GenericAlias @@ -12,7 +12,10 @@ _S = TypeVar("_S") _T = TypeVar("_T") class WeakSet(MutableSet[_T], Generic[_T]): - def __init__(self, data: Iterable[_T] | None = ...) -> None: ... + @overload + def __init__(self, data: None = ...) -> None: ... + @overload + def __init__(self, data: Iterable[_T]) -> None: ... def add(self, item: _T) -> None: ... def clear(self) -> None: ... def discard(self, item: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi index 759027d3a890..4f6cb6720988 100644 --- a/mypy/typeshed/stdlib/argparse.pyi +++ b/mypy/typeshed/stdlib/argparse.pyi @@ -3,47 +3,28 @@ from collections.abc import Callable, Generator, Iterable, Sequence from typing import IO, Any, Generic, NewType, NoReturn, Pattern, Protocol, TypeVar, overload from typing_extensions import Literal, TypeAlias +__all__ = [ + "ArgumentParser", + "ArgumentError", + "ArgumentTypeError", + "FileType", + "HelpFormatter", + "ArgumentDefaultsHelpFormatter", + "RawDescriptionHelpFormatter", + "RawTextHelpFormatter", + "MetavarTypeHelpFormatter", + "Namespace", + "Action", + "ONE_OR_MORE", + "OPTIONAL", + "PARSER", + "REMAINDER", + "SUPPRESS", + "ZERO_OR_MORE", +] + if sys.version_info >= (3, 9): - __all__ = [ - "ArgumentParser", - "ArgumentError", - "ArgumentTypeError", - "BooleanOptionalAction", - "FileType", - "HelpFormatter", - "ArgumentDefaultsHelpFormatter", - "RawDescriptionHelpFormatter", - "RawTextHelpFormatter", - "MetavarTypeHelpFormatter", - "Namespace", - "Action", - "ONE_OR_MORE", - "OPTIONAL", - "PARSER", - "REMAINDER", - "SUPPRESS", - "ZERO_OR_MORE", - ] -else: - __all__ = [ - "ArgumentParser", - "ArgumentError", - "ArgumentTypeError", - "FileType", - "HelpFormatter", - "ArgumentDefaultsHelpFormatter", - "RawDescriptionHelpFormatter", - "RawTextHelpFormatter", - "MetavarTypeHelpFormatter", - "Namespace", - "Action", - "ONE_OR_MORE", - "OPTIONAL", - "PARSER", - "REMAINDER", - "SUPPRESS", - "ZERO_OR_MORE", - ] + __all__ += ["BooleanOptionalAction"] _T = TypeVar("_T") _ActionT = TypeVar("_ActionT", bound=Action) @@ -212,7 +193,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): title: str = ..., description: str | None = ..., prog: str = ..., - parser_class: type[_ArgumentParserT] = ..., + parser_class: type[_ArgumentParserT], action: type[Action] = ..., option_string: str = ..., dest: str | None = ..., @@ -241,7 +222,7 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): title: str = ..., description: str | None = ..., prog: str = ..., - parser_class: type[_ArgumentParserT] = ..., + parser_class: type[_ArgumentParserT], action: type[Action] = ..., option_string: str = ..., dest: str | None = ..., @@ -309,7 +290,7 @@ class HelpFormatter: def format_help(self) -> str: ... def _join_parts(self, part_strings: Iterable[str]) -> str: ... def _format_usage( - self, usage: str, actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: str | None + self, usage: str | None, actions: Iterable[Action], groups: Iterable[_ArgumentGroup], prefix: str | None ) -> str: ... def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_ArgumentGroup]) -> str: ... def _format_text(self, text: str) -> str: ... @@ -409,16 +390,28 @@ class _StoreAction(Action): ... # undocumented class _StoreConstAction(Action): - def __init__( - self, - option_strings: Sequence[str], - dest: str, - const: Any, - default: Any = ..., - required: bool = ..., - help: str | None = ..., - metavar: str | tuple[str, ...] | None = ..., - ) -> None: ... + if sys.version_info >= (3, 11): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any | None = ..., + default: Any = ..., + required: bool = ..., + help: str | None = ..., + metavar: str | tuple[str, ...] | None = ..., + ) -> None: ... + else: + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any, + default: Any = ..., + required: bool = ..., + help: str | None = ..., + metavar: str | tuple[str, ...] | None = ..., + ) -> None: ... # undocumented class _StoreTrueAction(_StoreConstAction): @@ -437,16 +430,28 @@ class _AppendAction(Action): ... # undocumented class _AppendConstAction(Action): - def __init__( - self, - option_strings: Sequence[str], - dest: str, - const: Any, - default: Any = ..., - required: bool = ..., - help: str | None = ..., - metavar: str | tuple[str, ...] | None = ..., - ) -> None: ... + if sys.version_info >= (3, 11): + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any | None = ..., + default: Any = ..., + required: bool = ..., + help: str | None = ..., + metavar: str | tuple[str, ...] | None = ..., + ) -> None: ... + else: + def __init__( + self, + option_strings: Sequence[str], + dest: str, + const: Any, + default: Any = ..., + required: bool = ..., + help: str | None = ..., + metavar: str | tuple[str, ...] | None = ..., + ) -> None: ... # undocumented class _CountAction(Action): diff --git a/mypy/typeshed/stdlib/array.pyi b/mypy/typeshed/stdlib/array.pyi index d69f02d338cf..4797bd067008 100644 --- a/mypy/typeshed/stdlib/array.pyi +++ b/mypy/typeshed/stdlib/array.pyi @@ -1,9 +1,9 @@ import sys -from _typeshed import Self +from _typeshed import ReadableBuffer, Self, SupportsRead, SupportsWrite from collections.abc import Iterable # pytype crashes if array inherits from collections.abc.MutableSequence instead of typing.MutableSequence -from typing import Any, BinaryIO, Generic, MutableSequence, TypeVar, overload # noqa: Y027 +from typing import Any, Generic, MutableSequence, TypeVar, overload # noqa: Y027 from typing_extensions import Literal, SupportsIndex, TypeAlias _IntTypeCode: TypeAlias = Literal["b", "B", "h", "H", "i", "I", "l", "L", "q", "Q"] @@ -21,20 +21,22 @@ class array(MutableSequence[_T], Generic[_T]): @property def itemsize(self) -> int: ... @overload - def __init__(self: array[int], __typecode: _IntTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... + def __init__(self: array[int], __typecode: _IntTypeCode, __initializer: bytes | Iterable[int] = ...) -> None: ... @overload - def __init__(self: array[float], __typecode: _FloatTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... + def __init__(self: array[float], __typecode: _FloatTypeCode, __initializer: bytes | Iterable[float] = ...) -> None: ... @overload - def __init__(self: array[str], __typecode: _UnicodeTypeCode, __initializer: bytes | Iterable[_T] = ...) -> None: ... + def __init__(self: array[str], __typecode: _UnicodeTypeCode, __initializer: bytes | Iterable[str] = ...) -> None: ... @overload - def __init__(self, typecode: str, __initializer: bytes | Iterable[_T] = ...) -> None: ... + def __init__(self, __typecode: str, __initializer: Iterable[_T]) -> None: ... + @overload + def __init__(self, __typecode: str, __initializer: bytes = ...) -> None: ... def append(self, __v: _T) -> None: ... def buffer_info(self) -> tuple[int, int]: ... def byteswap(self) -> None: ... def count(self, __v: _T) -> int: ... def extend(self, __bb: Iterable[_T]) -> None: ... - def frombytes(self, __buffer: bytes) -> None: ... - def fromfile(self, __f: BinaryIO, __n: int) -> None: ... + def frombytes(self, __buffer: ReadableBuffer) -> None: ... + def fromfile(self, __f: SupportsRead[bytes], __n: int) -> None: ... def fromlist(self, __list: list[_T]) -> None: ... def fromunicode(self, __ustr: str) -> None: ... if sys.version_info >= (3, 10): @@ -47,7 +49,7 @@ class array(MutableSequence[_T], Generic[_T]): def remove(self, __v: _T) -> None: ... def reverse(self) -> None: ... def tobytes(self) -> bytes: ... - def tofile(self, __f: BinaryIO) -> None: ... + def tofile(self, __f: SupportsWrite[bytes]) -> None: ... def tolist(self) -> list[_T]: ... def tounicode(self) -> str: ... if sys.version_info < (3, 9): diff --git a/mypy/typeshed/stdlib/ast.pyi b/mypy/typeshed/stdlib/ast.pyi index 199e4f2acb68..3a54d158affd 100644 --- a/mypy/typeshed/stdlib/ast.pyi +++ b/mypy/typeshed/stdlib/ast.pyi @@ -259,3 +259,6 @@ if sys.version_info >= (3, 8): def get_source_segment(source: str, node: AST, *, padded: bool = ...) -> str | None: ... def walk(node: AST) -> Iterator[AST]: ... + +if sys.version_info >= (3, 9): + def main() -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/__init__.pyi b/mypy/typeshed/stdlib/asyncio/__init__.pyi index 2f4823b22b24..24a86caed66e 100644 --- a/mypy/typeshed/stdlib/asyncio/__init__.pyi +++ b/mypy/typeshed/stdlib/asyncio/__init__.pyi @@ -24,6 +24,7 @@ if sys.version_info >= (3, 9): if sys.version_info >= (3, 11): from .taskgroups import * + from .timeouts import * if sys.platform == "win32": from .windows_events import * diff --git a/mypy/typeshed/stdlib/asyncio/base_events.pyi b/mypy/typeshed/stdlib/asyncio/base_events.pyi index 7742651fea2a..310a9f585591 100644 --- a/mypy/typeshed/stdlib/asyncio/base_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_events.pyi @@ -1,6 +1,6 @@ import ssl import sys -from _typeshed import FileDescriptorLike +from _typeshed import FileDescriptorLike, WriteableBuffer from asyncio.events import AbstractEventLoop, AbstractServer, Handle, TimerHandle from asyncio.futures import Future from asyncio.protocols import BaseProtocol @@ -29,7 +29,18 @@ _ProtocolFactory: TypeAlias = Callable[[], BaseProtocol] _SSLContext: TypeAlias = bool | None | ssl.SSLContext class Server(AbstractServer): - if sys.version_info >= (3, 7): + if sys.version_info >= (3, 11): + def __init__( + self, + loop: AbstractEventLoop, + sockets: Iterable[socket], + protocol_factory: _ProtocolFactory, + ssl_context: _SSLContext, + backlog: int, + ssl_handshake_timeout: float | None, + ssl_shutdown_timeout: float | None = ..., + ) -> None: ... + elif sys.version_info >= (3, 7): def __init__( self, loop: AbstractEventLoop, @@ -39,12 +50,13 @@ class Server(AbstractServer): backlog: int, ssl_handshake_timeout: float | None, ) -> None: ... + else: + def __init__(self, loop: AbstractEventLoop, sockets: list[socket]) -> None: ... + if sys.version_info >= (3, 7): def get_loop(self) -> AbstractEventLoop: ... def is_serving(self) -> bool: ... async def start_serving(self) -> None: ... async def serve_forever(self) -> None: ... - else: - def __init__(self, loop: AbstractEventLoop, sockets: list[socket]) -> None: ... if sys.version_info >= (3, 8): @property def sockets(self) -> tuple[socket, ...]: ... @@ -86,7 +98,11 @@ class BaseEventLoop(AbstractEventLoop): # Future methods def create_future(self) -> Future[Any]: ... # Tasks methods - if sys.version_info >= (3, 8): + if sys.version_info >= (3, 11): + def create_task( + self, coro: Coroutine[Any, Any, _T] | Generator[Any, None, _T], *, name: object = ..., context: Context | None = ... + ) -> Task[_T]: ... + elif sys.version_info >= (3, 8): def create_task(self, coro: Coroutine[Any, Any, _T] | Generator[Any, None, _T], *, name: object = ...) -> Task[_T]: ... else: def create_task(self, coro: Coroutine[Any, Any, _T] | Generator[Any, None, _T]) -> Task[_T]: ... @@ -113,7 +129,46 @@ class BaseEventLoop(AbstractEventLoop): flags: int = ..., ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ... async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = ...) -> tuple[str, str]: ... - if sys.version_info >= (3, 8): + if sys.version_info >= (3, 11): + @overload + async def create_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + host: str = ..., + port: int = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: None = ..., + local_addr: tuple[str, int] | None = ..., + server_hostname: str | None = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., + happy_eyeballs_delay: float | None = ..., + interleave: int | None = ..., + ) -> tuple[BaseTransport, _ProtocolT]: ... + @overload + async def create_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + host: None = ..., + port: None = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: socket, + local_addr: None = ..., + server_hostname: str | None = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., + happy_eyeballs_delay: float | None = ..., + interleave: int | None = ..., + ) -> tuple[BaseTransport, _ProtocolT]: ... + elif sys.version_info >= (3, 8): @overload async def create_connection( self, @@ -214,10 +269,7 @@ class BaseEventLoop(AbstractEventLoop): local_addr: None = ..., server_hostname: str | None = ..., ) -> tuple[BaseTransport, _ProtocolT]: ... - if sys.version_info >= (3, 7): - async def sock_sendfile( - self, sock: socket, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool | None = ... - ) -> int: ... + if sys.version_info >= (3, 11): @overload async def create_server( self, @@ -233,6 +285,7 @@ class BaseEventLoop(AbstractEventLoop): reuse_address: bool | None = ..., reuse_port: bool | None = ..., ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., start_serving: bool = ..., ) -> Server: ... @overload @@ -250,8 +303,20 @@ class BaseEventLoop(AbstractEventLoop): reuse_address: bool | None = ..., reuse_port: bool | None = ..., ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., start_serving: bool = ..., ) -> Server: ... + async def start_tls( + self, + transport: BaseTransport, + protocol: BaseProtocol, + sslcontext: ssl.SSLContext, + *, + server_side: bool = ..., + server_hostname: str | None = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., + ) -> BaseTransport: ... async def connect_accepted_socket( self, protocol_factory: Callable[[], _ProtocolT], @@ -259,10 +324,43 @@ class BaseEventLoop(AbstractEventLoop): *, ssl: _SSLContext = ..., ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., ) -> tuple[BaseTransport, _ProtocolT]: ... - async def sendfile( - self, transport: BaseTransport, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool = ... - ) -> int: ... + elif sys.version_info >= (3, 7): + @overload + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: str | Sequence[str] | None = ..., + port: int = ..., + *, + family: int = ..., + flags: int = ..., + sock: None = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + reuse_address: bool | None = ..., + reuse_port: bool | None = ..., + ssl_handshake_timeout: float | None = ..., + start_serving: bool = ..., + ) -> Server: ... + @overload + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = ..., + port: None = ..., + *, + family: int = ..., + flags: int = ..., + sock: socket = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + reuse_address: bool | None = ..., + reuse_port: bool | None = ..., + ssl_handshake_timeout: float | None = ..., + start_serving: bool = ..., + ) -> Server: ... async def start_tls( self, transport: BaseTransport, @@ -273,6 +371,14 @@ class BaseEventLoop(AbstractEventLoop): server_hostname: str | None = ..., ssl_handshake_timeout: float | None = ..., ) -> BaseTransport: ... + async def connect_accepted_socket( + self, + protocol_factory: Callable[[], _ProtocolT], + sock: socket, + *, + ssl: _SSLContext = ..., + ssl_handshake_timeout: float | None = ..., + ) -> tuple[BaseTransport, _ProtocolT]: ... else: @overload async def create_server( @@ -307,6 +413,13 @@ class BaseEventLoop(AbstractEventLoop): async def connect_accepted_socket( self, protocol_factory: Callable[[], _ProtocolT], sock: socket, *, ssl: _SSLContext = ... ) -> tuple[BaseTransport, _ProtocolT]: ... + if sys.version_info >= (3, 7): + async def sock_sendfile( + self, sock: socket, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool | None = ... + ) -> int: ... + async def sendfile( + self, transport: BaseTransport, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool = ... + ) -> int: ... if sys.version_info >= (3, 11): async def create_datagram_endpoint( # type: ignore[override] self, @@ -378,10 +491,12 @@ class BaseEventLoop(AbstractEventLoop): def remove_reader(self, fd: FileDescriptorLike) -> bool: ... def add_writer(self, fd: FileDescriptorLike, callback: Callable[..., Any], *args: Any) -> None: ... def remove_writer(self, fd: FileDescriptorLike) -> bool: ... + # The sock_* methods (and probably some others) are not actually implemented on + # BaseEventLoop, only on subclasses. We list them here for now for convenience. # Completion based I/O methods returning Futures prior to 3.7 if sys.version_info >= (3, 7): async def sock_recv(self, sock: socket, nbytes: int) -> bytes: ... - async def sock_recv_into(self, sock: socket, buf: bytearray) -> int: ... + async def sock_recv_into(self, sock: socket, buf: WriteableBuffer) -> int: ... async def sock_sendall(self, sock: socket, data: bytes) -> None: ... async def sock_connect(self, sock: socket, address: _Address) -> None: ... async def sock_accept(self, sock: socket) -> tuple[socket, _RetAddress]: ... @@ -390,6 +505,10 @@ class BaseEventLoop(AbstractEventLoop): def sock_sendall(self, sock: socket, data: bytes) -> Future[None]: ... def sock_connect(self, sock: socket, address: _Address) -> Future[None]: ... def sock_accept(self, sock: socket) -> Future[tuple[socket, _RetAddress]]: ... + if sys.version_info >= (3, 11): + async def sock_recvfrom(self, sock: socket, bufsize: int) -> bytes: ... + async def sock_recvfrom_into(self, sock: socket, buf: WriteableBuffer, nbytes: int = ...) -> int: ... + async def sock_sendto(self, sock: socket, data: bytes, address: _Address) -> None: ... # Signal handling. def add_signal_handler(self, sig: int, callback: Callable[..., Any], *args: Any) -> None: ... def remove_signal_handler(self, sig: int) -> bool: ... diff --git a/mypy/typeshed/stdlib/asyncio/constants.pyi b/mypy/typeshed/stdlib/asyncio/constants.pyi index 230cf4faf483..1fa643c7414b 100644 --- a/mypy/typeshed/stdlib/asyncio/constants.pyi +++ b/mypy/typeshed/stdlib/asyncio/constants.pyi @@ -8,6 +8,10 @@ DEBUG_STACK_DEPTH: Literal[10] if sys.version_info >= (3, 7): SSL_HANDSHAKE_TIMEOUT: float SENDFILE_FALLBACK_READBUFFER_SIZE: Literal[262144] +if sys.version_info >= (3, 11): + SSL_SHUTDOWN_TIMEOUT: float + FLOW_CONTROL_HIGH_WATER_SSL_READ: Literal[256] + FLOW_CONTROL_HIGH_WATER_SSL_WRITE: Literal[512] class _SendfileMode(enum.Enum): UNSUPPORTED: int diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index ae566234160b..8396f0957a1e 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -1,6 +1,6 @@ import ssl import sys -from _typeshed import FileDescriptorLike, Self +from _typeshed import FileDescriptorLike, Self, WriteableBuffer from abc import ABCMeta, abstractmethod from collections.abc import Awaitable, Callable, Coroutine, Generator, Sequence from socket import AddressFamily, SocketKind, _Address, _RetAddress, socket @@ -184,7 +184,16 @@ class AbstractEventLoop: @abstractmethod def create_future(self) -> Future[Any]: ... # Tasks methods - if sys.version_info >= (3, 8): + if sys.version_info >= (3, 11): + @abstractmethod + def create_task( + self, + coro: Coroutine[Any, Any, _T] | Generator[Any, None, _T], + *, + name: str | None = ..., + context: Context | None = ..., + ) -> Task[_T]: ... + elif sys.version_info >= (3, 8): @abstractmethod def create_task( self, coro: Coroutine[Any, Any, _T] | Generator[Any, None, _T], *, name: str | None = ... @@ -223,7 +232,48 @@ class AbstractEventLoop: ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ... @abstractmethod async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = ...) -> tuple[str, str]: ... - if sys.version_info >= (3, 8): + if sys.version_info >= (3, 11): + @overload + @abstractmethod + async def create_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + host: str = ..., + port: int = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: None = ..., + local_addr: tuple[str, int] | None = ..., + server_hostname: str | None = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., + happy_eyeballs_delay: float | None = ..., + interleave: int | None = ..., + ) -> tuple[BaseTransport, _ProtocolT]: ... + @overload + @abstractmethod + async def create_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + host: None = ..., + port: None = ..., + *, + ssl: _SSLContext = ..., + family: int = ..., + proto: int = ..., + flags: int = ..., + sock: socket, + local_addr: None = ..., + server_hostname: str | None = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., + happy_eyeballs_delay: float | None = ..., + interleave: int | None = ..., + ) -> tuple[BaseTransport, _ProtocolT]: ... + elif sys.version_info >= (3, 8): @overload @abstractmethod async def create_connection( @@ -330,11 +380,7 @@ class AbstractEventLoop: local_addr: None = ..., server_hostname: str | None = ..., ) -> tuple[BaseTransport, _ProtocolT]: ... - if sys.version_info >= (3, 7): - @abstractmethod - async def sock_sendfile( - self, sock: socket, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool | None = ... - ) -> int: ... + if sys.version_info >= (3, 11): @overload @abstractmethod async def create_server( @@ -351,6 +397,7 @@ class AbstractEventLoop: reuse_address: bool | None = ..., reuse_port: bool | None = ..., ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., start_serving: bool = ..., ) -> Server: ... @overload @@ -369,18 +416,21 @@ class AbstractEventLoop: reuse_address: bool | None = ..., reuse_port: bool | None = ..., ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., start_serving: bool = ..., ) -> Server: ... - async def create_unix_connection( + @abstractmethod + async def start_tls( self, - protocol_factory: Callable[[], _ProtocolT], - path: str | None = ..., + transport: BaseTransport, + protocol: BaseProtocol, + sslcontext: ssl.SSLContext, *, - ssl: _SSLContext = ..., - sock: socket | None = ..., + server_side: bool = ..., server_hostname: str | None = ..., ssl_handshake_timeout: float | None = ..., - ) -> tuple[BaseTransport, _ProtocolT]: ... + ssl_shutdown_timeout: float | None = ..., + ) -> BaseTransport: ... async def create_unix_server( self, protocol_factory: _ProtocolFactory, @@ -390,12 +440,46 @@ class AbstractEventLoop: backlog: int = ..., ssl: _SSLContext = ..., ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., start_serving: bool = ..., ) -> Server: ... + elif sys.version_info >= (3, 7): + @overload @abstractmethod - async def sendfile( - self, transport: BaseTransport, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool = ... - ) -> int: ... + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: str | Sequence[str] | None = ..., + port: int = ..., + *, + family: int = ..., + flags: int = ..., + sock: None = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + reuse_address: bool | None = ..., + reuse_port: bool | None = ..., + ssl_handshake_timeout: float | None = ..., + start_serving: bool = ..., + ) -> Server: ... + @overload + @abstractmethod + async def create_server( + self, + protocol_factory: _ProtocolFactory, + host: None = ..., + port: None = ..., + *, + family: int = ..., + flags: int = ..., + sock: socket = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + reuse_address: bool | None = ..., + reuse_port: bool | None = ..., + ssl_handshake_timeout: float | None = ..., + start_serving: bool = ..., + ) -> Server: ... @abstractmethod async def start_tls( self, @@ -407,6 +491,17 @@ class AbstractEventLoop: server_hostname: str | None = ..., ssl_handshake_timeout: float | None = ..., ) -> BaseTransport: ... + async def create_unix_server( + self, + protocol_factory: _ProtocolFactory, + path: str | None = ..., + *, + sock: socket | None = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + ssl_handshake_timeout: float | None = ..., + start_serving: bool = ..., + ) -> Server: ... else: @overload @abstractmethod @@ -440,24 +535,76 @@ class AbstractEventLoop: reuse_address: bool | None = ..., reuse_port: bool | None = ..., ) -> Server: ... + async def create_unix_server( + self, + protocol_factory: _ProtocolFactory, + path: str, + *, + sock: socket | None = ..., + backlog: int = ..., + ssl: _SSLContext = ..., + ) -> Server: ... + if sys.version_info >= (3, 11): + async def connect_accepted_socket( + self, + protocol_factory: Callable[[], _ProtocolT], + sock: socket, + *, + ssl: _SSLContext = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., + ) -> tuple[BaseTransport, _ProtocolT]: ... + elif sys.version_info >= (3, 10): + async def connect_accepted_socket( + self, + protocol_factory: Callable[[], _ProtocolT], + sock: socket, + *, + ssl: _SSLContext = ..., + ssl_handshake_timeout: float | None = ..., + ) -> tuple[BaseTransport, _ProtocolT]: ... + if sys.version_info >= (3, 11): async def create_unix_connection( self, protocol_factory: Callable[[], _ProtocolT], - path: str, + path: str | None = ..., *, ssl: _SSLContext = ..., sock: socket | None = ..., server_hostname: str | None = ..., + ssl_handshake_timeout: float | None = ..., + ssl_shutdown_timeout: float | None = ..., ) -> tuple[BaseTransport, _ProtocolT]: ... - async def create_unix_server( + elif sys.version_info >= (3, 7): + async def create_unix_connection( self, - protocol_factory: _ProtocolFactory, - path: str, + protocol_factory: Callable[[], _ProtocolT], + path: str | None = ..., *, + ssl: _SSLContext = ..., sock: socket | None = ..., - backlog: int = ..., + server_hostname: str | None = ..., + ssl_handshake_timeout: float | None = ..., + ) -> tuple[BaseTransport, _ProtocolT]: ... + else: + async def create_unix_connection( + self, + protocol_factory: Callable[[], _ProtocolT], + path: str, + *, ssl: _SSLContext = ..., - ) -> Server: ... + sock: socket | None = ..., + server_hostname: str | None = ..., + ) -> tuple[BaseTransport, _ProtocolT]: ... + if sys.version_info >= (3, 7): + @abstractmethod + async def sock_sendfile( + self, sock: socket, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool | None = ... + ) -> int: ... + @abstractmethod + async def sendfile( + self, transport: BaseTransport, file: IO[bytes], offset: int = ..., count: int | None = ..., *, fallback: bool = ... + ) -> int: ... @abstractmethod async def create_datagram_endpoint( @@ -529,7 +676,7 @@ class AbstractEventLoop: @abstractmethod async def sock_recv(self, sock: socket, nbytes: int) -> bytes: ... @abstractmethod - async def sock_recv_into(self, sock: socket, buf: bytearray) -> int: ... + async def sock_recv_into(self, sock: socket, buf: WriteableBuffer) -> int: ... @abstractmethod async def sock_sendall(self, sock: socket, data: bytes) -> None: ... @abstractmethod @@ -545,6 +692,13 @@ class AbstractEventLoop: def sock_connect(self, sock: socket, address: _Address) -> Future[None]: ... @abstractmethod def sock_accept(self, sock: socket) -> Future[tuple[socket, _RetAddress]]: ... + if sys.version_info >= (3, 11): + @abstractmethod + async def sock_recvfrom(self, sock: socket, bufsize: int) -> bytes: ... + @abstractmethod + async def sock_recvfrom_into(self, sock: socket, buf: WriteableBuffer, nbytes: int = ...) -> int: ... + @abstractmethod + async def sock_sendto(self, sock: socket, data: bytes, address: _Address) -> None: ... # Signal handling. @abstractmethod def add_signal_handler(self, sig: int, callback: Callable[..., Any], *args: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/exceptions.pyi b/mypy/typeshed/stdlib/asyncio/exceptions.pyi index a1bc2c16ab1f..075fbb805bb9 100644 --- a/mypy/typeshed/stdlib/asyncio/exceptions.pyi +++ b/mypy/typeshed/stdlib/asyncio/exceptions.pyi @@ -1,11 +1,24 @@ -__all__ = ( - "CancelledError", - "InvalidStateError", - "TimeoutError", - "IncompleteReadError", - "LimitOverrunError", - "SendfileNotAvailableError", -) +import sys + +if sys.version_info >= (3, 11): + __all__ = ( + "BrokenBarrierError", + "CancelledError", + "InvalidStateError", + "TimeoutError", + "IncompleteReadError", + "LimitOverrunError", + "SendfileNotAvailableError", + ) +else: + __all__ = ( + "CancelledError", + "InvalidStateError", + "TimeoutError", + "IncompleteReadError", + "LimitOverrunError", + "SendfileNotAvailableError", + ) class CancelledError(BaseException): ... class TimeoutError(Exception): ... @@ -20,3 +33,6 @@ class IncompleteReadError(EOFError): class LimitOverrunError(Exception): consumed: int def __init__(self, message: str, consumed: int) -> None: ... + +if sys.version_info >= (3, 11): + class BrokenBarrierError(RuntimeError): ... diff --git a/mypy/typeshed/stdlib/asyncio/futures.pyi b/mypy/typeshed/stdlib/asyncio/futures.pyi index 692d263f673b..21bfe86e44c6 100644 --- a/mypy/typeshed/stdlib/asyncio/futures.pyi +++ b/mypy/typeshed/stdlib/asyncio/futures.pyi @@ -55,6 +55,7 @@ class Future(Awaitable[_T], Iterable[_T]): def __del__(self) -> None: ... if sys.version_info >= (3, 7): def get_loop(self) -> AbstractEventLoop: ... + @property def _callbacks(self: Self) -> list[tuple[Callable[[Self], Any], Context]]: ... def add_done_callback(self: Self, __fn: Callable[[Self], Any], *, context: Context | None = ...) -> None: ... else: diff --git a/mypy/typeshed/stdlib/asyncio/locks.pyi b/mypy/typeshed/stdlib/asyncio/locks.pyi index 2758e0c46919..269602c7bc66 100644 --- a/mypy/typeshed/stdlib/asyncio/locks.pyi +++ b/mypy/typeshed/stdlib/asyncio/locks.pyi @@ -1,4 +1,6 @@ +import enum import sys +from _typeshed import Self from collections import deque from collections.abc import Callable, Generator from types import TracebackType @@ -8,7 +10,12 @@ from typing_extensions import Literal from .events import AbstractEventLoop from .futures import Future -if sys.version_info >= (3, 7): +if sys.version_info >= (3, 11): + from .mixins import _LoopBoundMixin + +if sys.version_info >= (3, 11): + __all__ = ("Lock", "Event", "Condition", "Semaphore", "BoundedSemaphore", "Barrier") +elif sys.version_info >= (3, 7): __all__ = ("Lock", "Event", "Condition", "Semaphore", "BoundedSemaphore") else: __all__ = ["Lock", "Event", "Condition", "Semaphore", "BoundedSemaphore"] @@ -40,20 +47,32 @@ else: ) -> None: ... class Lock(_ContextManagerMixin): - def __init__(self, *, loop: AbstractEventLoop | None = ...) -> None: ... + if sys.version_info >= (3, 11): + def __init__(self) -> None: ... + else: + def __init__(self, *, loop: AbstractEventLoop | None = ...) -> None: ... + def locked(self) -> bool: ... async def acquire(self) -> Literal[True]: ... def release(self) -> None: ... class Event: - def __init__(self, *, loop: AbstractEventLoop | None = ...) -> None: ... + if sys.version_info >= (3, 11): + def __init__(self) -> None: ... + else: + def __init__(self, *, loop: AbstractEventLoop | None = ...) -> None: ... + def is_set(self) -> bool: ... def set(self) -> None: ... def clear(self) -> None: ... async def wait(self) -> Literal[True]: ... class Condition(_ContextManagerMixin): - def __init__(self, lock: Lock | None = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... + if sys.version_info >= (3, 11): + def __init__(self, lock: Lock | None = ...) -> None: ... + else: + def __init__(self, lock: Lock | None = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... + def locked(self) -> bool: ... async def acquire(self) -> Literal[True]: ... def release(self) -> None: ... @@ -65,11 +84,39 @@ class Condition(_ContextManagerMixin): class Semaphore(_ContextManagerMixin): _value: int _waiters: deque[Future[Any]] - def __init__(self, value: int = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... + if sys.version_info >= (3, 11): + def __init__(self, value: int = ...) -> None: ... + else: + def __init__(self, value: int = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... + def locked(self) -> bool: ... async def acquire(self) -> Literal[True]: ... def release(self) -> None: ... def _wake_up_next(self) -> None: ... class BoundedSemaphore(Semaphore): - def __init__(self, value: int = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... + if sys.version_info >= (3, 11): + def __init__(self, value: int = ...) -> None: ... + else: + def __init__(self, value: int = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... + +if sys.version_info >= (3, 11): + class _BarrierState(enum.Enum): # undocumented + FILLING: str + DRAINING: str + RESETTING: str + BROKEN: str + + class Barrier(_LoopBoundMixin): + def __init__(self, parties: int) -> None: ... + async def __aenter__(self: Self) -> Self: ... + async def __aexit__(self, *args: object) -> None: ... + async def wait(self) -> int: ... + async def abort(self) -> None: ... + async def reset(self) -> None: ... + @property + def parties(self) -> int: ... + @property + def n_waiting(self) -> int: ... + @property + def broken(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/asyncio/mixins.pyi b/mypy/typeshed/stdlib/asyncio/mixins.pyi index 4c11865c8968..3e04f2b37518 100644 --- a/mypy/typeshed/stdlib/asyncio/mixins.pyi +++ b/mypy/typeshed/stdlib/asyncio/mixins.pyi @@ -1,7 +1,9 @@ +import sys import threading from typing import NoReturn _global_lock: threading.Lock class _LoopBoundMixin: - def __init__(self, *, loop: NoReturn = ...) -> None: ... + if sys.version_info < (3, 11): + def __init__(self, *, loop: NoReturn = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/protocols.pyi b/mypy/typeshed/stdlib/asyncio/protocols.pyi index 7b5169702dba..e2fc118947bc 100644 --- a/mypy/typeshed/stdlib/asyncio/protocols.pyi +++ b/mypy/typeshed/stdlib/asyncio/protocols.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import ReadableBuffer from asyncio import transports from typing import Any @@ -19,7 +20,7 @@ class Protocol(BaseProtocol): if sys.version_info >= (3, 7): class BufferedProtocol(BaseProtocol): - def get_buffer(self, sizehint: int) -> bytearray: ... + def get_buffer(self, sizehint: int) -> ReadableBuffer: ... def buffer_updated(self, nbytes: int) -> None: ... def eof_received(self) -> bool | None: ... diff --git a/mypy/typeshed/stdlib/asyncio/queues.pyi b/mypy/typeshed/stdlib/asyncio/queues.pyi index 93ea9d9fc6fe..0e1a0b2808df 100644 --- a/mypy/typeshed/stdlib/asyncio/queues.pyi +++ b/mypy/typeshed/stdlib/asyncio/queues.pyi @@ -16,7 +16,11 @@ class QueueFull(Exception): ... _T = TypeVar("_T") class Queue(Generic[_T]): - def __init__(self, maxsize: int = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... + if sys.version_info >= (3, 11): + def __init__(self, maxsize: int = ...) -> None: ... + else: + def __init__(self, maxsize: int = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... + def _init(self, maxsize: int) -> None: ... def _get(self) -> _T: ... def _put(self, item: _T) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/runners.pyi b/mypy/typeshed/stdlib/asyncio/runners.pyi index 32cd839f2f79..49d236bbee9e 100644 --- a/mypy/typeshed/stdlib/asyncio/runners.pyi +++ b/mypy/typeshed/stdlib/asyncio/runners.pyi @@ -1,11 +1,28 @@ import sys -from collections.abc import Awaitable -from typing import TypeVar +from _typeshed import Self +from collections.abc import Callable, Coroutine +from contextvars import Context +from typing import Any, TypeVar -__all__ = ("run",) +from .events import AbstractEventLoop + +if sys.version_info >= (3, 11): + __all__ = ("Runner", "run") +else: + __all__ = ("run",) _T = TypeVar("_T") + +if sys.version_info >= (3, 11): + class Runner: + def __init__(self, *, debug: bool | None = ..., loop_factory: Callable[[], AbstractEventLoop] | None = ...) -> None: ... + def __enter__(self: Self) -> Self: ... + def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> None: ... + def close(self) -> None: ... + def get_loop(self) -> AbstractEventLoop: ... + def run(self, coro: Coroutine[Any, Any, _T], *, context: Context | None = ...) -> _T: ... + if sys.version_info >= (3, 8): - def run(main: Awaitable[_T], *, debug: bool | None = ...) -> _T: ... + def run(main: Coroutine[Any, Any, _T], *, debug: bool | None = ...) -> _T: ... else: - def run(main: Awaitable[_T], *, debug: bool = ...) -> _T: ... + def run(main: Coroutine[Any, Any, _T], *, debug: bool = ...) -> _T: ... diff --git a/mypy/typeshed/stdlib/asyncio/sslproto.pyi b/mypy/typeshed/stdlib/asyncio/sslproto.pyi index 619e329bfb43..77807743f749 100644 --- a/mypy/typeshed/stdlib/asyncio/sslproto.pyi +++ b/mypy/typeshed/stdlib/asyncio/sslproto.pyi @@ -2,17 +2,36 @@ import ssl import sys from collections import deque from collections.abc import Callable +from enum import Enum from typing import Any, ClassVar -from typing_extensions import Literal +from typing_extensions import Literal, TypeAlias from . import constants, events, futures, protocols, transports def _create_transport_context(server_side: bool, server_hostname: str | None) -> ssl.SSLContext: ... -_UNWRAPPED: Literal["UNWRAPPED"] -_DO_HANDSHAKE: Literal["DO_HANDSHAKE"] -_WRAPPED: Literal["WRAPPED"] -_SHUTDOWN: Literal["SHUTDOWN"] +if sys.version_info >= (3, 11): + SSLAgainErrors: tuple[type[ssl.SSLWantReadError], type[ssl.SSLSyscallError]] + + class SSLProtocolState(Enum): + UNWRAPPED: str + DO_HANDSHAKE: str + WRAPPED: str + FLUSHING: str + SHUTDOWN: str + + class AppProtocolState(Enum): + STATE_INIT: str + STATE_CON_MADE: str + STATE_EOF: str + STATE_CON_LOST: str + def add_flowcontrol_defaults(high: int | None, low: int | None, kb: int) -> tuple[int, int]: ... + +else: + _UNWRAPPED: Literal["UNWRAPPED"] + _DO_HANDSHAKE: Literal["DO_HANDSHAKE"] + _WRAPPED: Literal["WRAPPED"] + _SHUTDOWN: Literal["SHUTDOWN"] class _SSLPipe: @@ -70,8 +89,20 @@ class _SSLProtocolTransport(transports._FlowControlMixin, transports.Transport): def write(self, data: bytes) -> None: ... def can_write_eof(self) -> Literal[False]: ... def abort(self) -> None: ... + if sys.version_info >= (3, 11): + def get_write_buffer_limits(self) -> tuple[int, int]: ... + def get_read_buffer_limits(self) -> tuple[int, int]: ... + def set_read_buffer_limits(self, high: int | None = ..., low: int | None = ...) -> None: ... + def get_read_buffer_size(self) -> int: ... -class SSLProtocol(protocols.Protocol): +if sys.version_info >= (3, 11): + _SSLProtocolBase: TypeAlias = protocols.BufferedProtocol +else: + _SSLProtocolBase: TypeAlias = protocols.Protocol + +class SSLProtocol(_SSLProtocolBase): + if sys.version_info >= (3, 11): + max_size: ClassVar[int] _server_side: bool _server_hostname: str | None @@ -92,7 +123,20 @@ class SSLProtocol(protocols.Protocol): _app_protocol: protocols.BaseProtocol _app_protocol_is_buffer: bool - if sys.version_info >= (3, 7): + if sys.version_info >= (3, 11): + def __init__( + self, + loop: events.AbstractEventLoop, + app_protocol: protocols.BaseProtocol, + sslcontext: ssl.SSLContext, + waiter: futures.Future[Any], + server_side: bool = ..., + server_hostname: str | None = ..., + call_connection_made: bool = ..., + ssl_handshake_timeout: int | None = ..., + ssl_shutdown_timeout: float | None = ..., + ) -> None: ... + elif sys.version_info >= (3, 7): def __init__( self, loop: events.AbstractEventLoop, @@ -123,17 +167,25 @@ class SSLProtocol(protocols.Protocol): def connection_lost(self, exc: BaseException | None) -> None: ... def pause_writing(self) -> None: ... def resume_writing(self) -> None: ... - def data_received(self, data: bytes) -> None: ... def eof_received(self) -> None: ... def _get_extra_info(self, name: str, default: Any | None = ...) -> Any: ... def _start_shutdown(self) -> None: ... - def _write_appdata(self, data: bytes) -> None: ... + if sys.version_info >= (3, 11): + def _write_appdata(self, list_of_data: list[bytes]) -> None: ... + else: + def _write_appdata(self, data: bytes) -> None: ... + def _start_handshake(self) -> None: ... if sys.version_info >= (3, 7): def _check_handshake_timeout(self) -> None: ... def _on_handshake_complete(self, handshake_exc: BaseException | None) -> None: ... - def _process_write_backlog(self) -> None: ... def _fatal_error(self, exc: BaseException, message: str = ...) -> None: ... - def _finalize(self) -> None: ... def _abort(self) -> None: ... + if sys.version_info >= (3, 11): + def buffer_updated(self, nbytes: int) -> None: ... + def get_buffer(self, n: int) -> memoryview: ... + else: + def _finalize(self) -> None: ... + def _process_write_backlog(self) -> None: ... + def data_received(self, data: bytes) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/streams.pyi b/mypy/typeshed/stdlib/asyncio/streams.pyi index 14a6d2c4d8fe..0f24d01d50cf 100644 --- a/mypy/typeshed/stdlib/asyncio/streams.pyi +++ b/mypy/typeshed/stdlib/asyncio/streams.pyi @@ -1,3 +1,4 @@ +import ssl import sys from _typeshed import Self, StrPath from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Sequence @@ -179,6 +180,10 @@ class StreamWriter: def get_extra_info(self, name: str, default: Any = ...) -> Any: ... async def drain(self) -> None: ... + if sys.version_info >= (3, 11): + async def start_tls( + self, sslcontext: ssl.SSLContext, *, server_hostname: str | None = ..., ssl_handshake_timeout: float | None = ... + ) -> None: ... class StreamReader(AsyncIterator[bytes]): def __init__(self, limit: int = ..., loop: events.AbstractEventLoop | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/taskgroups.pyi b/mypy/typeshed/stdlib/asyncio/taskgroups.pyi index 58e3d41e53f1..9b2f15506c50 100644 --- a/mypy/typeshed/stdlib/asyncio/taskgroups.pyi +++ b/mypy/typeshed/stdlib/asyncio/taskgroups.pyi @@ -2,6 +2,7 @@ from _typeshed import Self from collections.abc import Coroutine, Generator +from contextvars import Context from types import TracebackType from typing import Any, TypeVar @@ -15,4 +16,6 @@ class TaskGroup: def __init__(self) -> None: ... async def __aenter__(self: Self) -> Self: ... async def __aexit__(self, et: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ... - def create_task(self, coro: Generator[Any, None, _T] | Coroutine[Any, Any, _T], *, name: str | None = ...) -> Task[_T]: ... + def create_task( + self, coro: Generator[Any, None, _T] | Coroutine[Any, Any, _T], *, name: str | None = ..., context: Context | None = ... + ) -> Task[_T]: ... diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index 4a8e565afb2f..d7119b0400ba 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -10,6 +10,8 @@ from .futures import Future if sys.version_info >= (3, 9): from types import GenericAlias +if sys.version_info >= (3, 11): + from contextvars import Context if sys.version_info >= (3, 7): __all__ = ( @@ -268,7 +270,10 @@ def run_coroutine_threadsafe(coro: _FutureT[_T], loop: AbstractEventLoop) -> con if sys.version_info >= (3, 10): def shield(arg: _FutureT[_T]) -> Future[_T]: ... - async def sleep(delay: float, result: _T = ...) -> _T: ... + @overload + async def sleep(delay: float) -> None: ... + @overload + async def sleep(delay: float, result: _T) -> _T: ... @overload async def wait(fs: Iterable[_FT], *, timeout: float | None = ..., return_when: str = ...) -> tuple[set[_FT], set[_FT]]: ... # type: ignore[misc] @overload @@ -279,7 +284,10 @@ if sys.version_info >= (3, 10): else: def shield(arg: _FutureT[_T], *, loop: AbstractEventLoop | None = ...) -> Future[_T]: ... - async def sleep(delay: float, result: _T = ..., *, loop: AbstractEventLoop | None = ...) -> _T: ... + @overload + async def sleep(delay: float, *, loop: AbstractEventLoop | None = ...) -> None: ... + @overload + async def sleep(delay: float, result: _T, *, loop: AbstractEventLoop | None = ...) -> _T: ... @overload async def wait( # type: ignore[misc] fs: Iterable[_FT], *, loop: AbstractEventLoop | None = ..., timeout: float | None = ..., return_when: str = ... @@ -329,7 +337,11 @@ class Task(Future[_T], Generic[_T]): if sys.version_info >= (3, 7): def all_tasks(loop: AbstractEventLoop | None = ...) -> set[Task[Any]]: ... - if sys.version_info >= (3, 8): + if sys.version_info >= (3, 11): + def create_task( + coro: Generator[Any, None, _T] | Coroutine[Any, Any, _T], *, name: str | None = ..., context: Context | None = ... + ) -> Task[_T]: ... + elif sys.version_info >= (3, 8): def create_task(coro: Generator[Any, None, _T] | Coroutine[Any, Any, _T], *, name: str | None = ...) -> Task[_T]: ... else: def create_task(coro: Generator[Any, None, _T] | Coroutine[Any, Any, _T]) -> Task[_T]: ... diff --git a/mypy/typeshed/stdlib/asyncio/timeouts.pyi b/mypy/typeshed/stdlib/asyncio/timeouts.pyi new file mode 100644 index 000000000000..be516b5851d1 --- /dev/null +++ b/mypy/typeshed/stdlib/asyncio/timeouts.pyi @@ -0,0 +1,19 @@ +from _typeshed import Self +from types import TracebackType +from typing_extensions import final + +__all__ = ("Timeout", "timeout", "timeout_at") + +@final +class Timeout: + def __init__(self, when: float | None) -> None: ... + def when(self) -> float | None: ... + def reschedule(self, when: float | None) -> None: ... + def expired(self) -> bool: ... + async def __aenter__(self: Self) -> Self: ... + async def __aexit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + +def timeout(delay: float | None) -> Timeout: ... +def timeout_at(when: float | None) -> Timeout: ... diff --git a/mypy/typeshed/stdlib/asyncio/trsock.pyi b/mypy/typeshed/stdlib/asyncio/trsock.pyi index 20df2a78a5ab..b8972e43d255 100644 --- a/mypy/typeshed/stdlib/asyncio/trsock.pyi +++ b/mypy/typeshed/stdlib/asyncio/trsock.pyi @@ -14,7 +14,6 @@ _CMSG: TypeAlias = tuple[int, int, bytes] class TransportSocket: def __init__(self, sock: socket.socket) -> None: ... - def _na(self, what: str) -> None: ... @property def family(self) -> int: ... @property @@ -41,6 +40,7 @@ class TransportSocket: def gettimeout(self) -> float | None: ... def setblocking(self, flag: bool) -> None: ... if sys.version_info < (3, 11): + def _na(self, what: str) -> None: ... def accept(self) -> tuple[socket.socket, _RetAddress]: ... def connect(self, address: _Address | bytes) -> None: ... def connect_ex(self, address: _Address | bytes) -> int: ... diff --git a/mypy/typeshed/stdlib/base64.pyi b/mypy/typeshed/stdlib/base64.pyi index ceed7d018d82..c2ec85cac40a 100644 --- a/mypy/typeshed/stdlib/base64.pyi +++ b/mypy/typeshed/stdlib/base64.pyi @@ -2,50 +2,29 @@ import sys from _typeshed import ReadableBuffer from typing import IO +__all__ = [ + "encode", + "decode", + "encodebytes", + "decodebytes", + "b64encode", + "b64decode", + "b32encode", + "b32decode", + "b16encode", + "b16decode", + "b85encode", + "b85decode", + "a85encode", + "a85decode", + "standard_b64encode", + "standard_b64decode", + "urlsafe_b64encode", + "urlsafe_b64decode", +] + if sys.version_info >= (3, 10): - __all__ = [ - "encode", - "decode", - "encodebytes", - "decodebytes", - "b64encode", - "b64decode", - "b32encode", - "b32decode", - "b32hexencode", - "b32hexdecode", - "b16encode", - "b16decode", - "b85encode", - "b85decode", - "a85encode", - "a85decode", - "standard_b64encode", - "standard_b64decode", - "urlsafe_b64encode", - "urlsafe_b64decode", - ] -else: - __all__ = [ - "encode", - "decode", - "encodebytes", - "decodebytes", - "b64encode", - "b64decode", - "b32encode", - "b32decode", - "b16encode", - "b16decode", - "b85encode", - "b85decode", - "a85encode", - "a85decode", - "standard_b64encode", - "standard_b64decode", - "urlsafe_b64encode", - "urlsafe_b64decode", - ] + __all__ += ["b32hexencode", "b32hexdecode"] def b64encode(s: ReadableBuffer, altchars: ReadableBuffer | None = ...) -> bytes: ... def b64decode(s: str | ReadableBuffer, altchars: ReadableBuffer | None = ..., validate: bool = ...) -> bytes: ... diff --git a/mypy/typeshed/stdlib/bdb.pyi b/mypy/typeshed/stdlib/bdb.pyi index bbd0f20af6c8..f4d1875efb69 100644 --- a/mypy/typeshed/stdlib/bdb.pyi +++ b/mypy/typeshed/stdlib/bdb.pyi @@ -1,3 +1,4 @@ +import sys from _typeshed import ExcInfo from collections.abc import Callable, Iterable, Mapping from types import CodeType, FrameType, TracebackType @@ -86,6 +87,10 @@ class Breakpoint: def __init__( self, file: str, line: int, temporary: bool = ..., cond: str | None = ..., funcname: str | None = ... ) -> None: ... + if sys.version_info >= (3, 11): + @staticmethod + def clearBreakpoints() -> None: ... + def deleteMe(self) -> None: ... def enable(self) -> None: ... def disable(self) -> None: ... diff --git a/mypy/typeshed/stdlib/binascii.pyi b/mypy/typeshed/stdlib/binascii.pyi index 53f72ad6a88f..0656794d39d9 100644 --- a/mypy/typeshed/stdlib/binascii.pyi +++ b/mypy/typeshed/stdlib/binascii.pyi @@ -14,7 +14,12 @@ if sys.version_info >= (3, 7): else: def b2a_uu(__data: ReadableBuffer) -> bytes: ... -def a2b_base64(__data: _AsciiBuffer) -> bytes: ... +if sys.version_info >= (3, 11): + def a2b_base64(__data: _AsciiBuffer, *, strict_mode: bool = ...) -> bytes: ... + +else: + def a2b_base64(__data: _AsciiBuffer) -> bytes: ... + def b2a_base64(__data: ReadableBuffer, *, newline: bool = ...) -> bytes: ... def a2b_qp(data: _AsciiBuffer, header: bool = ...) -> bytes: ... def b2a_qp(data: ReadableBuffer, quotetabs: bool = ..., istext: bool = ..., header: bool = ...) -> bytes: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index d3d34c72fcfc..577d5fd99e36 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -3,6 +3,7 @@ import types from _ast import AST from _collections_abc import dict_items, dict_keys, dict_values from _typeshed import ( + AnyStr_co, OpenBinaryMode, OpenBinaryModeReading, OpenBinaryModeUpdating, @@ -19,6 +20,7 @@ from _typeshed import ( SupportsKeysAndGetItem, SupportsLenAndGetItem, SupportsNext, + SupportsRAdd, SupportsRDivMod, SupportsRichComparison, SupportsRichComparisonT, @@ -52,7 +54,7 @@ from typing import ( # noqa: Y027 TypeVar, overload, ) -from typing_extensions import Literal, SupportsIndex, TypeAlias, TypeGuard, final +from typing_extensions import Literal, LiteralString, SupportsIndex, TypeAlias, TypeGuard, final if sys.version_info >= (3, 9): from types import GenericAlias @@ -398,21 +400,39 @@ class str(Sequence[str]): def __new__(cls: type[Self], object: object = ...) -> Self: ... @overload def __new__(cls: type[Self], object: ReadableBuffer, encoding: str = ..., errors: str = ...) -> Self: ... - def capitalize(self) -> str: ... - def casefold(self) -> str: ... - def center(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... + @overload + def capitalize(self: LiteralString) -> LiteralString: ... + @overload + def capitalize(self) -> str: ... # type: ignore[misc] + @overload + def casefold(self: LiteralString) -> LiteralString: ... + @overload + def casefold(self) -> str: ... # type: ignore[misc] + @overload + def center(self: LiteralString, __width: SupportsIndex, __fillchar: LiteralString = ...) -> LiteralString: ... + @overload + def center(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... # type: ignore[misc] def count(self, x: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def encode(self, encoding: str = ..., errors: str = ...) -> bytes: ... def endswith( self, __suffix: str | tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> bool: ... if sys.version_info >= (3, 8): - def expandtabs(self, tabsize: SupportsIndex = ...) -> str: ... + @overload + def expandtabs(self: LiteralString, tabsize: SupportsIndex = ...) -> LiteralString: ... + @overload + def expandtabs(self, tabsize: SupportsIndex = ...) -> str: ... # type: ignore[misc] else: - def expandtabs(self, tabsize: int = ...) -> str: ... + @overload + def expandtabs(self: LiteralString, tabsize: int = ...) -> LiteralString: ... + @overload + def expandtabs(self, tabsize: int = ...) -> str: ... # type: ignore[misc] def find(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... - def format(self, *args: object, **kwargs: object) -> str: ... + @overload + def format(self: LiteralString, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... + @overload + def format(self, *args: object, **kwargs: object) -> str: ... # type: ignore[misc] def format_map(self, map: _FormatMapMapping) -> str: ... def index(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def isalnum(self) -> bool: ... @@ -429,40 +449,102 @@ class str(Sequence[str]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - def join(self, __iterable: Iterable[str]) -> str: ... - def ljust(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... - def lower(self) -> str: ... - def lstrip(self, __chars: str | None = ...) -> str: ... - def partition(self, __sep: str) -> tuple[str, str, str]: ... - def replace(self, __old: str, __new: str, __count: SupportsIndex = ...) -> str: ... + @overload + def join(self: LiteralString, __iterable: Iterable[LiteralString]) -> LiteralString: ... + @overload + def join(self, __iterable: Iterable[str]) -> str: ... # type: ignore[misc] + @overload + def ljust(self: LiteralString, __width: SupportsIndex, __fillchar: LiteralString = ...) -> LiteralString: ... + @overload + def ljust(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... # type: ignore[misc] + @overload + def lower(self: LiteralString) -> LiteralString: ... + @overload + def lower(self) -> str: ... # type: ignore[misc] + @overload + def lstrip(self: LiteralString, __chars: LiteralString | None = ...) -> LiteralString: ... + @overload + def lstrip(self, __chars: str | None = ...) -> str: ... # type: ignore[misc] + @overload + def partition(self: LiteralString, __sep: LiteralString) -> tuple[LiteralString, LiteralString, LiteralString]: ... + @overload + def partition(self, __sep: str) -> tuple[str, str, str]: ... # type: ignore[misc] + @overload + def replace( + self: LiteralString, __old: LiteralString, __new: LiteralString, __count: SupportsIndex = ... + ) -> LiteralString: ... + @overload + def replace(self, __old: str, __new: str, __count: SupportsIndex = ...) -> str: ... # type: ignore[misc] if sys.version_info >= (3, 9): - def removeprefix(self, __prefix: str) -> str: ... - def removesuffix(self, __suffix: str) -> str: ... + @overload + def removeprefix(self: LiteralString, __prefix: LiteralString) -> LiteralString: ... + @overload + def removeprefix(self, __prefix: str) -> str: ... # type: ignore[misc] + @overload + def removesuffix(self: LiteralString, __suffix: LiteralString) -> LiteralString: ... + @overload + def removesuffix(self, __suffix: str) -> str: ... # type: ignore[misc] def rfind(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def rindex(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... - def rjust(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... - def rpartition(self, __sep: str) -> tuple[str, str, str]: ... - def rsplit(self, sep: str | None = ..., maxsplit: SupportsIndex = ...) -> list[str]: ... - def rstrip(self, __chars: str | None = ...) -> str: ... - def split(self, sep: str | None = ..., maxsplit: SupportsIndex = ...) -> list[str]: ... - def splitlines(self, keepends: bool = ...) -> list[str]: ... + @overload + def rjust(self: LiteralString, __width: SupportsIndex, __fillchar: LiteralString = ...) -> LiteralString: ... + @overload + def rjust(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... # type: ignore[misc] + @overload + def rpartition(self: LiteralString, __sep: LiteralString) -> tuple[LiteralString, LiteralString, LiteralString]: ... + @overload + def rpartition(self, __sep: str) -> tuple[str, str, str]: ... # type: ignore[misc] + @overload + def rsplit(self: LiteralString, sep: LiteralString | None = ..., maxsplit: SupportsIndex = ...) -> list[LiteralString]: ... + @overload + def rsplit(self, sep: str | None = ..., maxsplit: SupportsIndex = ...) -> list[str]: ... # type: ignore[misc] + @overload + def rstrip(self: LiteralString, __chars: LiteralString | None = ...) -> LiteralString: ... + @overload + def rstrip(self, __chars: str | None = ...) -> str: ... # type: ignore[misc] + @overload + def split(self: LiteralString, sep: LiteralString | None = ..., maxsplit: SupportsIndex = ...) -> list[LiteralString]: ... + @overload + def split(self, sep: str | None = ..., maxsplit: SupportsIndex = ...) -> list[str]: ... # type: ignore[misc] + @overload + def splitlines(self: LiteralString, keepends: bool = ...) -> list[LiteralString]: ... + @overload + def splitlines(self, keepends: bool = ...) -> list[str]: ... # type: ignore[misc] def startswith( self, __prefix: str | tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> bool: ... - def strip(self, __chars: str | None = ...) -> str: ... - def swapcase(self) -> str: ... - def title(self) -> str: ... + @overload + def strip(self: LiteralString, __chars: LiteralString | None = ...) -> LiteralString: ... + @overload + def strip(self, __chars: str | None = ...) -> str: ... # type: ignore[misc] + @overload + def swapcase(self: LiteralString) -> LiteralString: ... + @overload + def swapcase(self) -> str: ... # type: ignore[misc] + @overload + def title(self: LiteralString) -> LiteralString: ... + @overload + def title(self) -> str: ... # type: ignore[misc] def translate(self, __table: Mapping[int, int | str | None] | Sequence[int | str | None]) -> str: ... - def upper(self) -> str: ... - def zfill(self, __width: SupportsIndex) -> str: ... + @overload + def upper(self: LiteralString) -> LiteralString: ... + @overload + def upper(self) -> str: ... # type: ignore[misc] + @overload + def zfill(self: LiteralString, __width: SupportsIndex) -> LiteralString: ... + @overload + def zfill(self, __width: SupportsIndex) -> str: ... # type: ignore[misc] @staticmethod @overload def maketrans(__x: dict[int, _T] | dict[str, _T] | dict[str | int, _T]) -> dict[int, _T]: ... @staticmethod @overload def maketrans(__x: str, __y: str, __z: str | None = ...) -> dict[int, int | None]: ... - def __add__(self, __s: str) -> str: ... + @overload + def __add__(self: LiteralString, __s: LiteralString) -> LiteralString: ... + @overload + def __add__(self, __s: str) -> str: ... # type: ignore[misc] # Incompatible with Sequence.__contains__ def __contains__(self, __o: str) -> bool: ... # type: ignore[override] def __eq__(self, __x: object) -> bool: ... @@ -470,14 +552,26 @@ class str(Sequence[str]): def __getitem__(self, __i: SupportsIndex | slice) -> str: ... def __gt__(self, __x: str) -> bool: ... def __hash__(self) -> int: ... - def __iter__(self) -> Iterator[str]: ... + @overload + def __iter__(self: LiteralString) -> Iterator[LiteralString]: ... + @overload + def __iter__(self) -> Iterator[str]: ... # type: ignore[misc] def __le__(self, __x: str) -> bool: ... def __len__(self) -> int: ... def __lt__(self, __x: str) -> bool: ... - def __mod__(self, __x: Any) -> str: ... - def __mul__(self, __n: SupportsIndex) -> str: ... + @overload + def __mod__(self: LiteralString, __x: LiteralString | tuple[LiteralString, ...]) -> LiteralString: ... + @overload + def __mod__(self, __x: Any) -> str: ... # type: ignore[misc] + @overload + def __mul__(self: LiteralString, __n: SupportsIndex) -> LiteralString: ... + @overload + def __mul__(self, __n: SupportsIndex) -> str: ... # type: ignore[misc] def __ne__(self, __x: object) -> bool: ... - def __rmul__(self, __n: SupportsIndex) -> str: ... + @overload + def __rmul__(self: LiteralString, __n: SupportsIndex) -> LiteralString: ... + @overload + def __rmul__(self, __n: SupportsIndex) -> str: ... # type: ignore[misc] def __getnewargs__(self) -> tuple[str]: ... class bytes(ByteString): @@ -871,11 +965,16 @@ class list(MutableSequence[_T], Generic[_T]): def extend(self, __iterable: Iterable[_T]) -> None: ... def pop(self, __index: SupportsIndex = ...) -> _T: ... # Signature of `list.index` should be kept in line with `collections.UserList.index()` + # and multiprocessing.managers.ListProxy.index() def index(self, __value: _T, __start: SupportsIndex = ..., __stop: SupportsIndex = ...) -> int: ... def count(self, __value: _T) -> int: ... def insert(self, __index: SupportsIndex, __object: _T) -> None: ... def remove(self, __value: _T) -> None: ... # Signature of `list.sort` should be kept inline with `collections.UserList.sort()` + # and multiprocessing.managers.ListProxy.sort() + # + # Use list[SupportsRichComparisonT] for the first overload rather than [SupportsRichComparison] + # to work around invariance @overload def sort(self: list[SupportsRichComparisonT], *, key: None = ..., reverse: bool = ...) -> None: ... @overload @@ -908,8 +1007,9 @@ class list(MutableSequence[_T], Generic[_T]): class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): # __init__ should be kept roughly in line with `collections.UserDict.__init__`, which has similar semantics + # Also multiprocessing.managers.SyncManager.dict() @overload - def __init__(self: dict[_KT, _VT]) -> None: ... + def __init__(self) -> None: ... @overload def __init__(self: dict[str, _VT], **kwargs: _VT) -> None: ... @overload @@ -962,7 +1062,10 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): def __ior__(self: Self, __value: Iterable[tuple[_KT, _VT]]) -> Self: ... class set(MutableSet[_T], Generic[_T]): - def __init__(self, __iterable: Iterable[_T] = ...) -> None: ... + @overload + def __init__(self) -> None: ... + @overload + def __init__(self, __iterable: Iterable[_T]) -> None: ... def add(self, __element: _T) -> None: ... def copy(self) -> set[_T]: ... def difference(self, *s: Iterable[Any]) -> set[_T]: ... @@ -998,7 +1101,10 @@ class set(MutableSet[_T], Generic[_T]): def __class_getitem__(cls, __item: Any) -> GenericAlias: ... class frozenset(AbstractSet[_T_co], Generic[_T_co]): - def __init__(self, __iterable: Iterable[_T_co] = ...) -> None: ... + @overload + def __new__(cls: type[Self]) -> Self: ... + @overload + def __new__(cls: type[Self], __iterable: Iterable[_T_co]) -> Self: ... def copy(self) -> frozenset[_T_co]: ... def difference(self, *s: Iterable[object]) -> frozenset[_T_co]: ... def intersection(self, *s: Iterable[object]) -> frozenset[_T_co]: ... @@ -1092,10 +1198,8 @@ def chr(__i: int) -> str: ... # We define this here instead of using os.PathLike to avoid import cycle issues. # See https://github.com/python/typeshed/pull/991#issuecomment-288160993 -_AnyStr_co = TypeVar("_AnyStr_co", str, bytes, covariant=True) - -class _PathLike(Protocol[_AnyStr_co]): - def __fspath__(self) -> _AnyStr_co: ... +class _PathLike(Protocol[AnyStr_co]): + def __fspath__(self) -> AnyStr_co: ... if sys.version_info >= (3, 10): def aiter(__async_iterable: SupportsAiter[_SupportsAnextT]) -> _SupportsAnextT: ... @@ -1534,19 +1638,35 @@ def sorted( @overload def sorted(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> list[_T]: ... -_SumT = TypeVar("_SumT", bound=SupportsAdd) -_SumS = TypeVar("_SumS", bound=SupportsAdd) +_AddableT1 = TypeVar("_AddableT1", bound=SupportsAdd[Any, Any]) +_AddableT2 = TypeVar("_AddableT2", bound=SupportsAdd[Any, Any]) + +class _SupportsSumWithNoDefaultGiven(SupportsAdd[Any, Any], SupportsRAdd[int, Any], Protocol): ... + +_SupportsSumNoDefaultT = TypeVar("_SupportsSumNoDefaultT", bound=_SupportsSumWithNoDefaultGiven) + +# In general, the return type of `x + x` is *not* guaranteed to be the same type as x. +# However, we can't express that in the stub for `sum()` +# without creating many false-positive errors (see #7578). +# Instead, we special-case the most common example of this: bool. +if sys.version_info >= (3, 8): + @overload + def sum(__iterable: Iterable[bool], start: int = ...) -> int: ... # type: ignore[misc] + +else: + @overload + def sum(__iterable: Iterable[bool], __start: int = ...) -> int: ... # type: ignore[misc] @overload -def sum(__iterable: Iterable[_SumT]) -> _SumT | Literal[0]: ... +def sum(__iterable: Iterable[_SupportsSumNoDefaultT]) -> _SupportsSumNoDefaultT | Literal[0]: ... if sys.version_info >= (3, 8): @overload - def sum(__iterable: Iterable[_SumT], start: _SumS) -> _SumT | _SumS: ... + def sum(__iterable: Iterable[_AddableT1], start: _AddableT2) -> _AddableT1 | _AddableT2: ... else: @overload - def sum(__iterable: Iterable[_SumT], __start: _SumS) -> _SumT | _SumS: ... + def sum(__iterable: Iterable[_AddableT1], __start: _AddableT2) -> _AddableT1 | _AddableT2: ... # The argument to `vars()` has to have a `__dict__` attribute, so can't be annotated with `object` # (A "SupportsDunderDict" protocol doesn't work) @@ -1654,10 +1774,13 @@ class BaseException: __context__: BaseException | None __suppress_context__: bool __traceback__: TracebackType | None - if sys.version_info >= (3, 11): - __note__: str | None def __init__(self, *args: object) -> None: ... + def __setstate__(self, __state: dict[str, Any] | None) -> None: ... def with_traceback(self: Self, __tb: TracebackType | None) -> Self: ... + if sys.version_info >= (3, 11): + # only present after add_note() is called + __notes__: list[str] + def add_note(self, __note: str) -> None: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ... diff --git a/mypy/typeshed/stdlib/calendar.pyi b/mypy/typeshed/stdlib/calendar.pyi index c7e0a6b4606f..00b7054ba60a 100644 --- a/mypy/typeshed/stdlib/calendar.pyi +++ b/mypy/typeshed/stdlib/calendar.pyi @@ -4,67 +4,35 @@ from collections.abc import Iterable, Sequence from time import struct_time from typing_extensions import Literal, TypeAlias +__all__ = [ + "IllegalMonthError", + "IllegalWeekdayError", + "setfirstweekday", + "firstweekday", + "isleap", + "leapdays", + "weekday", + "monthrange", + "monthcalendar", + "prmonth", + "month", + "prcal", + "calendar", + "timegm", + "month_name", + "month_abbr", + "day_name", + "day_abbr", + "Calendar", + "TextCalendar", + "HTMLCalendar", + "LocaleTextCalendar", + "LocaleHTMLCalendar", + "weekheader", +] + if sys.version_info >= (3, 10): - __all__ = [ - "IllegalMonthError", - "IllegalWeekdayError", - "setfirstweekday", - "firstweekday", - "isleap", - "leapdays", - "weekday", - "monthrange", - "monthcalendar", - "prmonth", - "month", - "prcal", - "calendar", - "timegm", - "month_name", - "month_abbr", - "day_name", - "day_abbr", - "Calendar", - "TextCalendar", - "HTMLCalendar", - "LocaleTextCalendar", - "LocaleHTMLCalendar", - "weekheader", - "FRIDAY", - "MONDAY", - "SATURDAY", - "SUNDAY", - "THURSDAY", - "TUESDAY", - "WEDNESDAY", - ] -else: - __all__ = [ - "IllegalMonthError", - "IllegalWeekdayError", - "setfirstweekday", - "firstweekday", - "isleap", - "leapdays", - "weekday", - "monthrange", - "monthcalendar", - "prmonth", - "month", - "prcal", - "calendar", - "timegm", - "month_name", - "month_abbr", - "day_name", - "day_abbr", - "Calendar", - "TextCalendar", - "HTMLCalendar", - "LocaleTextCalendar", - "LocaleHTMLCalendar", - "weekheader", - ] + __all__ += ["FRIDAY", "MONDAY", "SATURDAY", "SUNDAY", "THURSDAY", "TUESDAY", "WEDNESDAY"] _LocaleType: TypeAlias = tuple[str | None, str | None] diff --git a/mypy/typeshed/stdlib/cgi.pyi b/mypy/typeshed/stdlib/cgi.pyi index 5e7bebc2a7f8..59c0a27067f1 100644 --- a/mypy/typeshed/stdlib/cgi.pyi +++ b/mypy/typeshed/stdlib/cgi.pyi @@ -5,39 +5,23 @@ from collections.abc import Iterable, Iterator, Mapping from types import TracebackType from typing import IO, Any, Protocol -if sys.version_info >= (3, 8): - __all__ = [ - "MiniFieldStorage", - "FieldStorage", - "parse", - "parse_multipart", - "parse_header", - "test", - "print_exception", - "print_environ", - "print_form", - "print_directory", - "print_arguments", - "print_environ_usage", - ] -else: - __all__ = [ - "MiniFieldStorage", - "FieldStorage", - "parse", - "parse_qs", - "parse_qsl", - "parse_multipart", - "parse_header", - "test", - "print_exception", - "print_environ", - "print_form", - "print_directory", - "print_arguments", - "print_environ_usage", - "escape", - ] +__all__ = [ + "MiniFieldStorage", + "FieldStorage", + "parse", + "parse_multipart", + "parse_header", + "test", + "print_exception", + "print_environ", + "print_form", + "print_directory", + "print_arguments", + "print_environ_usage", +] + +if sys.version_info < (3, 8): + __all__ += ["parse_qs", "parse_qsl", "escape"] def parse( fp: IO[Any] | None = ..., diff --git a/mypy/typeshed/stdlib/codecs.pyi b/mypy/typeshed/stdlib/codecs.pyi index bba7703c7d33..64d1c93ba3a3 100644 --- a/mypy/typeshed/stdlib/codecs.pyi +++ b/mypy/typeshed/stdlib/codecs.pyi @@ -1,10 +1,11 @@ -import sys import types from _typeshed import Self from abc import abstractmethod -from collections.abc import Callable, Generator, Iterable, Iterator -from typing import IO, Any, BinaryIO, Protocol, TextIO, overload -from typing_extensions import Literal, TypeAlias +from collections.abc import Callable, Generator, Iterable +from typing import Any, BinaryIO, Protocol, TextIO +from typing_extensions import Literal + +from _codecs import * __all__ = [ "register", @@ -58,6 +59,18 @@ BOM32_LE: Literal[b"\xff\xfe"] BOM64_BE: Literal[b"\x00\x00\xfe\xff"] BOM64_LE: Literal[b"\xff\xfe\x00\x00"] +class _WritableStream(Protocol): + def write(self, __data: bytes) -> object: ... + def seek(self, __offset: int, __whence: int) -> object: ... + def close(self) -> object: ... + +class _ReadableStream(Protocol): + def read(self, __size: int = ...) -> bytes: ... + def seek(self, __offset: int, __whence: int) -> object: ... + def close(self) -> object: ... + +class _Stream(_WritableStream, _ReadableStream, Protocol): ... + # TODO: this only satisfies the most common interface, where # bytes is the raw form and str is the cooked form. # In the long run, both should become template parameters maybe? @@ -71,10 +84,10 @@ class _Decoder(Protocol): def __call__(self, input: bytes, errors: str = ...) -> tuple[str, int]: ... # signature of Codec().decode class _StreamReader(Protocol): - def __call__(self, stream: IO[bytes], errors: str = ...) -> StreamReader: ... + def __call__(self, stream: _ReadableStream, errors: str = ...) -> StreamReader: ... class _StreamWriter(Protocol): - def __call__(self, stream: IO[bytes], errors: str = ...) -> StreamWriter: ... + def __call__(self, stream: _WritableStream, errors: str = ...) -> StreamWriter: ... class _IncrementalEncoder(Protocol): def __call__(self, errors: str = ...) -> IncrementalEncoder: ... @@ -82,49 +95,6 @@ class _IncrementalEncoder(Protocol): class _IncrementalDecoder(Protocol): def __call__(self, errors: str = ...) -> IncrementalDecoder: ... -# The type ignore on `encode` and `decode` is to avoid issues with overlapping overloads, for more details, see #300 -# https://docs.python.org/3/library/codecs.html#binary-transforms -_BytesToBytesEncoding: TypeAlias = Literal[ - "base64", - "base_64", - "base64_codec", - "bz2", - "bz2_codec", - "hex", - "hex_codec", - "quopri", - "quotedprintable", - "quoted_printable", - "quopri_codec", - "uu", - "uu_codec", - "zip", - "zlib", - "zlib_codec", -] -# https://docs.python.org/3/library/codecs.html#text-transforms -_StrToStrEncoding: TypeAlias = Literal["rot13", "rot_13"] - -@overload -def encode(obj: bytes, encoding: _BytesToBytesEncoding, errors: str = ...) -> bytes: ... -@overload -def encode(obj: str, encoding: _StrToStrEncoding, errors: str = ...) -> str: ... # type: ignore[misc] -@overload -def encode(obj: str, encoding: str = ..., errors: str = ...) -> bytes: ... -@overload -def decode(obj: bytes, encoding: _BytesToBytesEncoding, errors: str = ...) -> bytes: ... # type: ignore[misc] -@overload -def decode(obj: str, encoding: _StrToStrEncoding, errors: str = ...) -> str: ... - -# hex is officially documented as a bytes to bytes encoding, but it appears to also work with str -@overload -def decode(obj: str, encoding: Literal["hex", "hex_codec"], errors: str = ...) -> bytes: ... -@overload -def decode(obj: bytes, encoding: str = ..., errors: str = ...) -> str: ... -def lookup(__encoding: str) -> CodecInfo: ... -def utf_16_be_decode(__data: bytes, __errors: str | None = ..., __final: bool = ...) -> tuple[str, int]: ... # undocumented -def utf_16_be_encode(__str: str, __errors: str | None = ...) -> tuple[bytes, int]: ... # undocumented - class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]): @property def encode(self) -> _Encoder: ... @@ -158,17 +128,13 @@ def getincrementalencoder(encoding: str) -> _IncrementalEncoder: ... def getincrementaldecoder(encoding: str) -> _IncrementalDecoder: ... def getreader(encoding: str) -> _StreamReader: ... def getwriter(encoding: str) -> _StreamWriter: ... -def register(__search_function: Callable[[str], CodecInfo | None]) -> None: ... def open( filename: str, mode: str = ..., encoding: str | None = ..., errors: str = ..., buffering: int = ... ) -> StreamReaderWriter: ... -def EncodedFile(file: IO[bytes], data_encoding: str, file_encoding: str | None = ..., errors: str = ...) -> StreamRecoder: ... +def EncodedFile(file: _Stream, data_encoding: str, file_encoding: str | None = ..., errors: str = ...) -> StreamRecoder: ... def iterencode(iterator: Iterable[str], encoding: str, errors: str = ...) -> Generator[bytes, None, None]: ... def iterdecode(iterator: Iterable[bytes], encoding: str, errors: str = ...) -> Generator[str, None, None]: ... -if sys.version_info >= (3, 10): - def unregister(__search_function: Callable[[str], CodecInfo | None]) -> None: ... - BOM: Literal[b"\xff\xfe", b"\xfe\xff"] # depends on `sys.byteorder` BOM_BE: Literal[b"\xfe\xff"] BOM_LE: Literal[b"\xff\xfe"] @@ -180,11 +146,6 @@ BOM_UTF32: Literal[b"\xff\xfe\x00\x00", b"\x00\x00\xfe\xff"] # depends on `sys. BOM_UTF32_BE: Literal[b"\x00\x00\xfe\xff"] BOM_UTF32_LE: Literal[b"\xff\xfe\x00\x00"] -# It is expected that different actions be taken depending on which of the -# three subclasses of `UnicodeError` is actually ...ed. However, the Union -# is still needed for at least one of the cases. -def register_error(__errors: str, __handler: Callable[[UnicodeError], tuple[str | bytes, int]]) -> None: ... -def lookup_error(__name: str) -> Callable[[UnicodeError], tuple[str | bytes, int]]: ... def strict_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... def replace_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... def ignore_errors(exception: UnicodeError) -> tuple[str | bytes, int]: ... @@ -235,8 +196,9 @@ class BufferedIncrementalDecoder(IncrementalDecoder): # TODO: it is not possible to specify the requirement that all other # attributes and methods are passed-through from the stream. class StreamWriter(Codec): + stream: _WritableStream errors: str - def __init__(self, stream: IO[bytes], errors: str = ...) -> None: ... + def __init__(self, stream: _WritableStream, errors: str = ...) -> None: ... def write(self, object: str) -> None: ... def writelines(self, list: Iterable[str]) -> None: ... def reset(self) -> None: ... @@ -244,9 +206,10 @@ class StreamWriter(Codec): def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ... def __getattr__(self, name: str, getattr: Callable[[str], Any] = ...) -> Any: ... -class StreamReader(Codec, Iterator[str]): +class StreamReader(Codec): + stream: _ReadableStream errors: str - def __init__(self, stream: IO[bytes], errors: str = ...) -> None: ... + def __init__(self, stream: _ReadableStream, errors: str = ...) -> None: ... def read(self, size: int = ..., chars: int = ..., firstline: bool = ...) -> str: ... def readline(self, size: int | None = ..., keepends: bool = ...) -> str: ... def readlines(self, sizehint: int | None = ..., keepends: bool = ...) -> list[str]: ... @@ -260,7 +223,8 @@ class StreamReader(Codec, Iterator[str]): # Doesn't actually inherit from TextIO, but wraps a BinaryIO to provide text reading and writing # and delegates attributes to the underlying binary stream with __getattr__. class StreamReaderWriter(TextIO): - def __init__(self, stream: IO[bytes], Reader: _StreamReader, Writer: _StreamWriter, errors: str = ...) -> None: ... + stream: _Stream + def __init__(self, stream: _Stream, Reader: _StreamReader, Writer: _StreamWriter, errors: str = ...) -> None: ... def read(self, size: int = ...) -> str: ... def readline(self, size: int | None = ...) -> str: ... def readlines(self, sizehint: int | None = ...) -> list[str]: ... @@ -287,13 +251,7 @@ class StreamReaderWriter(TextIO): class StreamRecoder(BinaryIO): def __init__( - self, - stream: IO[bytes], - encode: _Encoder, - decode: _Decoder, - Reader: _StreamReader, - Writer: _StreamWriter, - errors: str = ..., + self, stream: _Stream, encode: _Encoder, decode: _Decoder, Reader: _StreamReader, Writer: _StreamWriter, errors: str = ... ) -> None: ... def read(self, size: int = ...) -> bytes: ... def readline(self, size: int | None = ...) -> bytes: ... diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index 2e88c0d8f474..5fff9f48c489 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -14,6 +14,35 @@ else: __all__ = ["ChainMap", "Counter", "OrderedDict", "UserDict", "UserList", "UserString", "defaultdict", "deque", "namedtuple"] +if sys.version_info < (3, 7): + __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", + ] + _S = TypeVar("_S") _T = TypeVar("_T") _T1 = TypeVar("_T1") @@ -43,7 +72,7 @@ class UserDict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): data: dict[_KT, _VT] # __init__ should be kept roughly in line with `dict.__init__`, which has the same semantics @overload - def __init__(self: UserDict[_KT, _VT], __dict: None = ...) -> None: ... + def __init__(self, __dict: None = ...) -> None: ... @overload def __init__(self: UserDict[str, _VT], __dict: None = ..., **kwargs: _VT) -> None: ... @overload @@ -82,7 +111,10 @@ class UserDict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): class UserList(MutableSequence[_T]): data: list[_T] - def __init__(self, initlist: Iterable[_T] | None = ...) -> None: ... + @overload + def __init__(self, initlist: None = ...) -> None: ... + @overload + def __init__(self, initlist: Iterable[_T]) -> None: ... def __lt__(self, other: list[_T] | UserList[_T]) -> bool: ... def __le__(self, other: list[_T] | UserList[_T]) -> bool: ... def __gt__(self, other: list[_T] | UserList[_T]) -> bool: ... @@ -214,7 +246,10 @@ class UserString(Sequence[UserString]): class deque(MutableSequence[_T], Generic[_T]): @property def maxlen(self) -> int | None: ... - def __init__(self, iterable: Iterable[_T] = ..., maxlen: int | None = ...) -> None: ... + @overload + def __init__(self, *, maxlen: int | None = ...) -> None: ... + @overload + def __init__(self, iterable: Iterable[_T], maxlen: int | None = ...) -> None: ... def append(self, __x: _T) -> None: ... def appendleft(self, __x: _T) -> None: ... def copy(self: Self) -> Self: ... @@ -248,7 +283,7 @@ class deque(MutableSequence[_T], Generic[_T]): class Counter(dict[_T, int], Generic[_T]): @overload - def __init__(self: Counter[_T], __iterable: None = ...) -> None: ... + def __init__(self, __iterable: None = ...) -> None: ... @overload def __init__(self: Counter[str], __iterable: None = ..., **kwargs: int) -> None: ... @overload @@ -340,7 +375,7 @@ class OrderedDict(dict[_KT, _VT], Reversible[_KT], Generic[_KT, _VT]): class defaultdict(dict[_KT, _VT], Generic[_KT, _VT]): default_factory: Callable[[], _VT] | None @overload - def __init__(self: defaultdict[_KT, _VT]) -> None: ... + def __init__(self) -> None: ... @overload def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/concurrent/futures/process.pyi b/mypy/typeshed/stdlib/concurrent/futures/process.pyi index 4cfa8276897f..1dd2ee0a6105 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/process.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/process.pyi @@ -53,7 +53,13 @@ class _ResultItem: work_id: int exception: Exception result: Any - def __init__(self, work_id: int, exception: Exception | None = ..., result: Any | None = ...) -> None: ... + if sys.version_info >= (3, 11): + exit_pid: int | None + def __init__( + self, work_id: int, exception: Exception | None = ..., result: Any | None = ..., exit_pid: int | None = ... + ) -> None: ... + else: + def __init__(self, work_id: int, exception: Exception | None = ..., result: Any | None = ...) -> None: ... class _CallItem: work_id: int @@ -86,11 +92,31 @@ if sys.version_info >= (3, 7): def _get_chunks(*iterables: Any, chunksize: int) -> Generator[tuple[Any, ...], None, None]: ... def _process_chunk(fn: Callable[..., Any], chunk: tuple[Any, None, None]) -> Generator[Any, None, None]: ... -def _sendback_result( - result_queue: SimpleQueue[_WorkItem[Any]], work_id: int, result: Any | None = ..., exception: Exception | None = ... -) -> None: ... -if sys.version_info >= (3, 7): +if sys.version_info >= (3, 11): + def _sendback_result( + result_queue: SimpleQueue[_WorkItem[Any]], + work_id: int, + result: Any | None = ..., + exception: Exception | None = ..., + exit_pid: int | None = ..., + ) -> None: ... + +else: + def _sendback_result( + result_queue: SimpleQueue[_WorkItem[Any]], work_id: int, result: Any | None = ..., exception: Exception | None = ... + ) -> None: ... + +if sys.version_info >= (3, 11): + def _process_worker( + call_queue: Queue[_CallItem], + result_queue: SimpleQueue[_ResultItem], + initializer: Callable[..., None] | None, + initargs: tuple[Any, ...], + max_tasks: int | None = ..., + ) -> None: ... + +elif sys.version_info >= (3, 7): def _process_worker( call_queue: Queue[_CallItem], result_queue: SimpleQueue[_ResultItem], @@ -153,7 +179,17 @@ class ProcessPoolExecutor(Executor): _executor_manager_thread_wakeup: _ThreadWakeup _result_queue: SimpleQueue[Any] _work_ids: Queue[Any] - if sys.version_info >= (3, 7): + if sys.version_info >= (3, 11): + def __init__( + self, + max_workers: int | None = ..., + mp_context: BaseContext | None = ..., + initializer: Callable[..., None] | None = ..., + initargs: tuple[Any, ...] = ..., + *, + max_tasks_per_child: int | None = ..., + ) -> None: ... + elif sys.version_info >= (3, 7): def __init__( self, max_workers: int | None = ..., diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index 1b6ee4298174..81213b954093 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -5,65 +5,25 @@ from types import TracebackType from typing import IO, Any, ContextManager, Generic, Protocol, TypeVar, overload # noqa: Y027 from typing_extensions import ParamSpec, TypeAlias +__all__ = [ + "contextmanager", + "closing", + "AbstractContextManager", + "ContextDecorator", + "ExitStack", + "redirect_stdout", + "redirect_stderr", + "suppress", +] + +if sys.version_info >= (3, 7): + __all__ += ["AbstractAsyncContextManager", "AsyncExitStack", "asynccontextmanager", "nullcontext"] + +if sys.version_info >= (3, 10): + __all__ += ["aclosing"] + if sys.version_info >= (3, 11): - __all__ = [ - "asynccontextmanager", - "contextmanager", - "closing", - "nullcontext", - "AbstractContextManager", - "AbstractAsyncContextManager", - "AsyncExitStack", - "ContextDecorator", - "ExitStack", - "redirect_stdout", - "redirect_stderr", - "suppress", - "aclosing", - "chdir", - ] -elif sys.version_info >= (3, 10): - __all__ = [ - "asynccontextmanager", - "contextmanager", - "closing", - "nullcontext", - "AbstractContextManager", - "AbstractAsyncContextManager", - "AsyncExitStack", - "ContextDecorator", - "ExitStack", - "redirect_stdout", - "redirect_stderr", - "suppress", - "aclosing", - ] -elif sys.version_info >= (3, 7): - __all__ = [ - "asynccontextmanager", - "contextmanager", - "closing", - "nullcontext", - "AbstractContextManager", - "AbstractAsyncContextManager", - "AsyncExitStack", - "ContextDecorator", - "ExitStack", - "redirect_stdout", - "redirect_stderr", - "suppress", - ] -else: - __all__ = [ - "contextmanager", - "closing", - "AbstractContextManager", - "ContextDecorator", - "ExitStack", - "redirect_stdout", - "redirect_stderr", - "suppress", - ] + __all__ += ["chdir"] AbstractContextManager = ContextManager if sys.version_info >= (3, 7): @@ -163,7 +123,7 @@ class _RedirectStream(AbstractContextManager[_T_io]): class redirect_stdout(_RedirectStream[_T_io]): ... class redirect_stderr(_RedirectStream[_T_io]): ... -class ExitStack(AbstractContextManager[ExitStack]): +class ExitStack: def __init__(self) -> None: ... def enter_context(self, cm: AbstractContextManager[_T]) -> _T: ... def push(self, exit: _CM_EF) -> _CM_EF: ... @@ -179,7 +139,7 @@ if sys.version_info >= (3, 7): _ExitCoroFunc: TypeAlias = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], Awaitable[bool]] _ACM_EF = TypeVar("_ACM_EF", bound=AbstractAsyncContextManager[Any] | _ExitCoroFunc) - class AsyncExitStack(AbstractAsyncContextManager[AsyncExitStack]): + class AsyncExitStack: def __init__(self) -> None: ... def enter_context(self, cm: AbstractContextManager[_T]) -> _T: ... async def enter_async_context(self, cm: AbstractAsyncContextManager[_T]) -> _T: ... diff --git a/mypy/typeshed/stdlib/contextvars.pyi b/mypy/typeshed/stdlib/contextvars.pyi index 341cd8491caf..266d96bce6ff 100644 --- a/mypy/typeshed/stdlib/contextvars.pyi +++ b/mypy/typeshed/stdlib/contextvars.pyi @@ -14,7 +14,10 @@ _P = ParamSpec("_P") @final class ContextVar(Generic[_T]): - def __init__(self, name: str, *, default: _T = ...) -> None: ... + @overload + def __init__(self, name: str) -> None: ... + @overload + def __init__(self, name: str, *, default: _T) -> None: ... @property def name(self) -> str: ... @overload diff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi index de69c71ad941..e9552c759c16 100644 --- a/mypy/typeshed/stdlib/csv.pyi +++ b/mypy/typeshed/stdlib/csv.pyi @@ -31,6 +31,9 @@ if sys.version_info >= (3, 8): else: from collections import OrderedDict as _DictReadMapping +if sys.version_info >= (3, 12): + from types import GenericAlias + __all__ = [ "QUOTE_MINIMAL", "QUOTE_ALL", @@ -76,7 +79,7 @@ class unix_dialect(Dialect): lineterminator: str quoting: _QuotingType -class DictReader(Generic[_T], Iterator[_DictReadMapping[_T, str]]): +class DictReader(Generic[_T], Iterator[_DictReadMapping[_T | Any, str | Any]]): fieldnames: Sequence[_T] | None restkey: str | None restval: str | None @@ -120,7 +123,9 @@ class DictReader(Generic[_T], Iterator[_DictReadMapping[_T, str]]): strict: bool = ..., ) -> None: ... def __iter__(self: Self) -> Self: ... - def __next__(self) -> _DictReadMapping[_T, str]: ... + def __next__(self) -> _DictReadMapping[_T | Any, str | Any]: ... + if sys.version_info >= (3, 12): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... class DictWriter(Generic[_T]): fieldnames: Collection[_T] @@ -151,6 +156,8 @@ class DictWriter(Generic[_T]): def writerow(self, rowdict: Mapping[_T, Any]) -> Any: ... def writerows(self, rowdicts: Iterable[Mapping[_T, Any]]) -> None: ... + if sys.version_info >= (3, 12): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... class Sniffer: preferred: list[str] diff --git a/mypy/typeshed/stdlib/ctypes/__init__.pyi b/mypy/typeshed/stdlib/ctypes/__init__.pyi index 53a382ec0e71..ee26cbddefe4 100644 --- a/mypy/typeshed/stdlib/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/ctypes/__init__.pyi @@ -164,7 +164,7 @@ def POINTER(type: type[_CT]) -> type[pointer[_CT]]: ... class pointer(Generic[_CT], _PointerLike, _CData): _type_: type[_CT] contents: _CT - def __init__(self, arg: _CT = ...) -> None: ... + def __init__(self, arg: _CT) -> None: ... @overload def __getitem__(self, __i: int) -> _CT: ... @overload diff --git a/mypy/typeshed/stdlib/dataclasses.pyi b/mypy/typeshed/stdlib/dataclasses.pyi index 1cbf998dd303..04ae771fc064 100644 --- a/mypy/typeshed/stdlib/dataclasses.pyi +++ b/mypy/typeshed/stdlib/dataclasses.pyi @@ -12,37 +12,23 @@ if sys.version_info >= (3, 9): _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) +__all__ = [ + "dataclass", + "field", + "Field", + "FrozenInstanceError", + "InitVar", + "MISSING", + "fields", + "asdict", + "astuple", + "make_dataclass", + "replace", + "is_dataclass", +] + if sys.version_info >= (3, 10): - __all__ = [ - "dataclass", - "field", - "Field", - "FrozenInstanceError", - "InitVar", - "KW_ONLY", - "MISSING", - "fields", - "asdict", - "astuple", - "make_dataclass", - "replace", - "is_dataclass", - ] -else: - __all__ = [ - "dataclass", - "field", - "Field", - "FrozenInstanceError", - "InitVar", - "MISSING", - "fields", - "asdict", - "astuple", - "make_dataclass", - "replace", - "is_dataclass", - ] + __all__ += ["KW_ONLY"] # define _MISSING_TYPE as an enum within the type stubs, # even though that is not really its type at runtime @@ -240,7 +226,26 @@ class InitVar(Generic[_T]): @overload def __class_getitem__(cls, type: Any) -> InitVar[Any]: ... -if sys.version_info >= (3, 10): +if sys.version_info >= (3, 11): + def make_dataclass( + cls_name: str, + fields: Iterable[str | tuple[str, type] | tuple[str, type, Any]], + *, + bases: tuple[type, ...] = ..., + namespace: dict[str, Any] | None = ..., + init: bool = ..., + repr: bool = ..., + eq: bool = ..., + order: bool = ..., + unsafe_hash: bool = ..., + frozen: bool = ..., + match_args: bool = ..., + kw_only: bool = ..., + slots: bool = ..., + weakref_slot: bool = ..., + ) -> type: ... + +elif sys.version_info >= (3, 10): def make_dataclass( cls_name: str, fields: Iterable[str | tuple[str, type] | tuple[str, type, Any]], diff --git a/mypy/typeshed/stdlib/difflib.pyi b/mypy/typeshed/stdlib/difflib.pyi index 87e3768034bf..854a53d433ae 100644 --- a/mypy/typeshed/stdlib/difflib.pyi +++ b/mypy/typeshed/stdlib/difflib.pyi @@ -28,8 +28,17 @@ class Match(NamedTuple): size: int class SequenceMatcher(Generic[_T]): + @overload + def __init__(self, isjunk: Callable[[_T], bool] | None, a: Sequence[_T], b: Sequence[_T], autojunk: bool = ...) -> None: ... + @overload + def __init__(self, *, a: Sequence[_T], b: Sequence[_T], autojunk: bool = ...) -> None: ... + @overload def __init__( - self, isjunk: Callable[[_T], bool] | None = ..., a: Sequence[_T] = ..., b: Sequence[_T] = ..., autojunk: bool = ... + self: SequenceMatcher[str], + isjunk: Callable[[str], bool] | None = ..., + a: Sequence[str] = ..., + b: Sequence[str] = ..., + autojunk: bool = ..., ) -> None: ... def set_seqs(self, a: Sequence[_T], b: Sequence[_T]) -> None: ... def set_seq1(self, a: Sequence[_T]) -> None: ... diff --git a/mypy/typeshed/stdlib/dis.pyi b/mypy/typeshed/stdlib/dis.pyi index 9a99d4498668..0b78e17b360b 100644 --- a/mypy/typeshed/stdlib/dis.pyi +++ b/mypy/typeshed/stdlib/dis.pyi @@ -80,9 +80,12 @@ class Bytecode: first_line: int | None = ..., current_offset: int | None = ..., show_caches: bool = ..., + adaptive: bool = ..., ) -> None: ... @classmethod - def from_traceback(cls: type[Self], tb: types.TracebackType, *, show_caches: bool = ...) -> Self: ... + def from_traceback( + cls: type[Self], tb: types.TracebackType, *, show_caches: bool = ..., adaptive: bool = ... + ) -> Self: ... else: def __init__( self, x: _HaveCodeOrStringType, *, first_line: int | None = ..., current_offset: int | None = ... @@ -103,7 +106,12 @@ def code_info(x: _HaveCodeOrStringType) -> str: ... if sys.version_info >= (3, 11): def dis( - x: _HaveCodeOrStringType | None = ..., *, file: IO[str] | None = ..., depth: int | None = ..., show_caches: bool = ... + x: _HaveCodeOrStringType | None = ..., + *, + file: IO[str] | None = ..., + depth: int | None = ..., + show_caches: bool = ..., + adaptive: bool = ..., ) -> None: ... elif sys.version_info >= (3, 7): @@ -113,10 +121,18 @@ else: def dis(x: _HaveCodeOrStringType | None = ..., *, file: IO[str] | None = ...) -> None: ... if sys.version_info >= (3, 11): - def disassemble(co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ..., show_caches: bool = ...) -> None: ... - def disco(co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ..., show_caches: bool = ...) -> None: ... - def distb(tb: types.TracebackType | None = ..., *, file: IO[str] | None = ..., show_caches: bool = ...) -> None: ... - def get_instructions(x: _HaveCodeType, *, first_line: int | None = ..., show_caches: bool = ...) -> Iterator[Instruction]: ... + def disassemble( + co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ..., show_caches: bool = ..., adaptive: bool = ... + ) -> None: ... + def disco( + co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ..., show_caches: bool = ..., adaptive: bool = ... + ) -> None: ... + def distb( + tb: types.TracebackType | None = ..., *, file: IO[str] | None = ..., show_caches: bool = ..., adaptive: bool = ... + ) -> None: ... + def get_instructions( + x: _HaveCodeType, *, first_line: int | None = ..., show_caches: bool = ..., adaptive: bool = ... + ) -> Iterator[Instruction]: ... else: def disassemble(co: _HaveCodeType, lasti: int = ..., *, file: IO[str] | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/distutils/command/check.pyi b/mypy/typeshed/stdlib/distutils/command/check.pyi index 36895d2c16f1..cdbe40fff71d 100644 --- a/mypy/typeshed/stdlib/distutils/command/check.pyi +++ b/mypy/typeshed/stdlib/distutils/command/check.pyi @@ -1,8 +1,9 @@ from typing import Any +from typing_extensions import TypeAlias from ..cmd import Command -_Reporter = Any # really docutils.utils.Reporter +_Reporter: TypeAlias = Any # really docutils.utils.Reporter # Only defined if docutils is installed. class SilentReporter(_Reporter): diff --git a/mypy/typeshed/stdlib/distutils/filelist.pyi b/mypy/typeshed/stdlib/distutils/filelist.pyi index 361cb13f0c47..d8b87e251509 100644 --- a/mypy/typeshed/stdlib/distutils/filelist.pyi +++ b/mypy/typeshed/stdlib/distutils/filelist.pyi @@ -17,34 +17,34 @@ class FileList: def process_template_line(self, line: str) -> None: ... @overload def include_pattern( - self, pattern: str, anchor: int | bool = ..., prefix: str | None = ..., is_regex: Literal[0, False] = ... + self, pattern: str, anchor: bool | Literal[0, 1] = ..., prefix: str | None = ..., is_regex: Literal[0, False] = ... ) -> bool: ... @overload def include_pattern(self, pattern: str | Pattern[str], *, is_regex: Literal[True, 1] = ...) -> bool: ... @overload def include_pattern( - self, pattern: str | Pattern[str], anchor: int | bool = ..., prefix: str | None = ..., is_regex: int | bool = ... + self, pattern: str | Pattern[str], anchor: bool | Literal[0, 1] = ..., prefix: str | None = ..., is_regex: int = ... ) -> bool: ... @overload def exclude_pattern( - self, pattern: str, anchor: int | bool = ..., prefix: str | None = ..., is_regex: Literal[0, False] = ... + self, pattern: str, anchor: bool | Literal[0, 1] = ..., prefix: str | None = ..., is_regex: Literal[0, False] = ... ) -> bool: ... @overload def exclude_pattern(self, pattern: str | Pattern[str], *, is_regex: Literal[True, 1] = ...) -> bool: ... @overload def exclude_pattern( - self, pattern: str | Pattern[str], anchor: int | bool = ..., prefix: str | None = ..., is_regex: int | bool = ... + self, pattern: str | Pattern[str], anchor: bool | Literal[0, 1] = ..., prefix: str | None = ..., is_regex: int = ... ) -> bool: ... def findall(dir: str = ...) -> list[str]: ... def glob_to_re(pattern: str) -> str: ... @overload def translate_pattern( - pattern: str, anchor: int | bool = ..., prefix: str | None = ..., is_regex: Literal[False, 0] = ... + pattern: str, anchor: bool | Literal[0, 1] = ..., prefix: str | None = ..., is_regex: Literal[False, 0] = ... ) -> Pattern[str]: ... @overload def translate_pattern(pattern: str | Pattern[str], *, is_regex: Literal[True, 1] = ...) -> Pattern[str]: ... @overload def translate_pattern( - pattern: str | Pattern[str], anchor: int | bool = ..., prefix: str | None = ..., is_regex: int | bool = ... + pattern: str | Pattern[str], anchor: bool | Literal[0, 1] = ..., prefix: str | None = ..., is_regex: int = ... ) -> Pattern[str]: ... diff --git a/mypy/typeshed/stdlib/enum.pyi b/mypy/typeshed/stdlib/enum.pyi index 9ebeba37ab71..6063dc47b004 100644 --- a/mypy/typeshed/stdlib/enum.pyi +++ b/mypy/typeshed/stdlib/enum.pyi @@ -1,44 +1,37 @@ import sys import types -from _typeshed import Self +from _typeshed import Self, SupportsKeysAndGetItem from abc import ABCMeta from builtins import property as _builtins_property from collections.abc import Iterable, Iterator, Mapping from typing import Any, Generic, TypeVar, overload from typing_extensions import Literal, TypeAlias +__all__ = ["EnumMeta", "Enum", "IntEnum", "Flag", "IntFlag", "auto", "unique"] + if sys.version_info >= (3, 11): - __all__ = [ - "EnumType", - "EnumMeta", - "Enum", - "IntEnum", - "StrEnum", - "Flag", - "IntFlag", - "ReprEnum", - "auto", - "unique", - "property", - "verify", - "member", - "nonmember", - "FlagBoundary", - "STRICT", + __all__ += [ "CONFORM", + "CONTINUOUS", "EJECT", - "KEEP", - "global_flag_repr", - "global_enum_repr", - "global_str", - "global_enum", "EnumCheck", - "CONTINUOUS", + "EnumType", + "FlagBoundary", + "KEEP", "NAMED_FLAGS", + "ReprEnum", + "STRICT", + "StrEnum", "UNIQUE", + "global_enum", + "global_enum_repr", + "global_flag_repr", + "global_str", + "member", + "nonmember", + "property", + "verify", ] -else: - __all__ = ["EnumMeta", "Enum", "IntEnum", "Flag", "IntFlag", "auto", "unique"] _EnumMemberT = TypeVar("_EnumMemberT") _EnumerationT = TypeVar("_EnumerationT", bound=type[Enum]) @@ -68,6 +61,16 @@ if sys.version_info >= (3, 11): class _EnumDict(dict[str, Any]): def __init__(self) -> None: ... def __setitem__(self, key: str, value: Any) -> None: ... + if sys.version_info >= (3, 11): + # See comment above `typing.MutableMapping.update` + # for why overloads are preferable to a Union here + # + # Unlike with MutableMapping.update(), the first argument is required, + # hence the type: ignore + @overload # type: ignore[override] + def update(self, members: SupportsKeysAndGetItem[str, Any], **more_members: Any) -> None: ... + @overload + def update(self, members: Iterable[tuple[str, Any]], **more_members: Any) -> None: ... # Note: EnumMeta actually subclasses type directly, not ABCMeta. # This is a temporary workaround to allow multiple creation of enums with builtins @@ -213,15 +216,21 @@ class Flag(Enum): def __and__(self: Self, other: Self) -> Self: ... def __xor__(self: Self, other: Self) -> Self: ... def __invert__(self: Self) -> Self: ... + if sys.version_info >= (3, 11): + def __iter__(self: Self) -> Iterator[Self]: ... + def __len__(self) -> int: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ class IntFlag(int, Flag): def __new__(cls: type[Self], value: int) -> Self: ... def __or__(self: Self, other: int) -> Self: ... def __and__(self: Self, other: int) -> Self: ... def __xor__(self: Self, other: int) -> Self: ... - def __ror__(self: Self, other: int) -> Self: ... - def __rand__(self: Self, other: int) -> Self: ... - def __rxor__(self: Self, other: int) -> Self: ... + __ror__ = __or__ + __rand__ = __and__ + __rxor__ = __xor__ if sys.version_info >= (3, 11): class StrEnum(str, ReprEnum): diff --git a/mypy/typeshed/stdlib/filecmp.pyi b/mypy/typeshed/stdlib/filecmp.pyi index a6747dd504a3..dd4a0628b026 100644 --- a/mypy/typeshed/stdlib/filecmp.pyi +++ b/mypy/typeshed/stdlib/filecmp.pyi @@ -1,7 +1,6 @@ import sys -from _typeshed import StrOrBytesPath +from _typeshed import GenericPath, StrOrBytesPath from collections.abc import Callable, Iterable, Sequence -from os import PathLike from typing import Any, AnyStr, Generic from typing_extensions import Literal @@ -13,19 +12,16 @@ __all__ = ["clear_cache", "cmp", "dircmp", "cmpfiles", "DEFAULT_IGNORES"] DEFAULT_IGNORES: list[str] BUFSIZE: Literal[8192] -def cmp(f1: StrOrBytesPath, f2: StrOrBytesPath, shallow: int | bool = ...) -> bool: ... +def cmp(f1: StrOrBytesPath, f2: StrOrBytesPath, shallow: bool | Literal[0, 1] = ...) -> bool: ... def cmpfiles( - a: AnyStr | PathLike[AnyStr], - b: AnyStr | PathLike[AnyStr], - common: Iterable[AnyStr | PathLike[AnyStr]], - shallow: int | bool = ..., + a: GenericPath[AnyStr], b: GenericPath[AnyStr], common: Iterable[GenericPath[AnyStr]], shallow: bool | Literal[0, 1] = ... ) -> tuple[list[AnyStr], list[AnyStr], list[AnyStr]]: ... class dircmp(Generic[AnyStr]): def __init__( self, - a: AnyStr | PathLike[AnyStr], - b: AnyStr | PathLike[AnyStr], + a: GenericPath[AnyStr], + b: GenericPath[AnyStr], ignore: Sequence[AnyStr] | None = ..., hide: Sequence[AnyStr] | None = ..., ) -> None: ... diff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi index 0ef8c14ddaac..e0babbcd40cc 100644 --- a/mypy/typeshed/stdlib/fileinput.pyi +++ b/mypy/typeshed/stdlib/fileinput.pyi @@ -1,8 +1,12 @@ import sys -from _typeshed import Self, StrOrBytesPath +from _typeshed import AnyStr_co, Self, StrOrBytesPath from collections.abc import Callable, Iterable, Iterator from types import TracebackType -from typing import IO, Any, AnyStr, Generic +from typing import IO, Any, AnyStr, Generic, Protocol, overload +from typing_extensions import Literal, TypeAlias + +if sys.version_info >= (3, 9): + from types import GenericAlias __all__ = [ "input", @@ -19,40 +23,131 @@ __all__ = [ "hook_encoded", ] -if sys.version_info >= (3, 9): - from types import GenericAlias +if sys.version_info >= (3, 11): + _TextMode: TypeAlias = Literal["r"] +else: + _TextMode: TypeAlias = Literal["r", "rU", "U"] + +class _HasReadlineAndFileno(Protocol[AnyStr_co]): + def readline(self) -> AnyStr_co: ... + def fileno(self) -> int: ... if sys.version_info >= (3, 10): + # encoding and errors are added + @overload def input( files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., inplace: bool = ..., backup: str = ..., *, - mode: str = ..., - openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., + mode: _TextMode = ..., + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = ..., encoding: str | None = ..., errors: str | None = ..., - ) -> FileInput[AnyStr]: ... + ) -> FileInput[str]: ... + @overload + def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., + inplace: bool = ..., + backup: str = ..., + *, + mode: Literal["rb"], + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = ..., + encoding: None = ..., + errors: None = ..., + ) -> FileInput[bytes]: ... + @overload + def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., + inplace: bool = ..., + backup: str = ..., + *, + mode: str, + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = ..., + encoding: str | None = ..., + errors: str | None = ..., + ) -> FileInput[Any]: ... elif sys.version_info >= (3, 8): + # bufsize is dropped and mode and openhook become keyword-only + @overload + def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., + inplace: bool = ..., + backup: str = ..., + *, + mode: _TextMode = ..., + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = ..., + ) -> FileInput[str]: ... + @overload def input( files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., inplace: bool = ..., backup: str = ..., *, - mode: str = ..., - openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., - ) -> FileInput[AnyStr]: ... + mode: Literal["rb"], + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = ..., + ) -> FileInput[bytes]: ... + @overload + def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., + inplace: bool = ..., + backup: str = ..., + *, + mode: str, + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = ..., + ) -> FileInput[Any]: ... else: + @overload + def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., + inplace: bool = ..., + backup: str = ..., + bufsize: int = ..., + mode: _TextMode = ..., + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = ..., + ) -> FileInput[str]: ... + # Because mode isn't keyword-only here yet, we need two overloads each for + # the bytes case and the fallback case. + @overload + def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., + inplace: bool = ..., + backup: str = ..., + bufsize: int = ..., + *, + mode: Literal["rb"], + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = ..., + ) -> FileInput[bytes]: ... + @overload + def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None, + inplace: bool, + backup: str, + bufsize: int, + mode: Literal["rb"], + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = ..., + ) -> FileInput[bytes]: ... + @overload def input( files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., inplace: bool = ..., backup: str = ..., bufsize: int = ..., - mode: str = ..., - openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., - ) -> FileInput[AnyStr]: ... + *, + mode: str, + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = ..., + ) -> FileInput[Any]: ... + @overload + def input( + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None, + inplace: bool, + backup: str, + bufsize: int, + mode: str, + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = ..., + ) -> FileInput[Any]: ... def close() -> None: ... def nextfile() -> None: ... @@ -65,36 +160,131 @@ def isstdin() -> bool: ... class FileInput(Iterator[AnyStr], Generic[AnyStr]): if sys.version_info >= (3, 10): + # encoding and errors are added + @overload def __init__( - self, - files: None | StrOrBytesPath | Iterable[StrOrBytesPath] = ..., + self: FileInput[str], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., inplace: bool = ..., backup: str = ..., *, - mode: str = ..., - openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., + mode: _TextMode = ..., + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = ..., encoding: str | None = ..., errors: str | None = ..., ) -> None: ... + @overload + def __init__( + self: FileInput[bytes], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., + inplace: bool = ..., + backup: str = ..., + *, + mode: Literal["rb"], + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = ..., + encoding: None = ..., + errors: None = ..., + ) -> None: ... + @overload + def __init__( + self: FileInput[Any], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., + inplace: bool = ..., + backup: str = ..., + *, + mode: str, + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = ..., + encoding: str | None = ..., + errors: str | None = ..., + ) -> None: ... + elif sys.version_info >= (3, 8): + # bufsize is dropped and mode and openhook become keyword-only + @overload + def __init__( + self: FileInput[str], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., + inplace: bool = ..., + backup: str = ..., + *, + mode: _TextMode = ..., + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = ..., + ) -> None: ... + @overload + def __init__( + self: FileInput[bytes], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., + inplace: bool = ..., + backup: str = ..., + *, + mode: Literal["rb"], + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = ..., + ) -> None: ... + @overload def __init__( - self, - files: None | StrOrBytesPath | Iterable[StrOrBytesPath] = ..., + self: FileInput[Any], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., inplace: bool = ..., backup: str = ..., *, - mode: str = ..., - openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., + mode: str, + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = ..., ) -> None: ... + else: + @overload def __init__( - self, - files: None | StrOrBytesPath | Iterable[StrOrBytesPath] = ..., + self: FileInput[str], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., inplace: bool = ..., backup: str = ..., bufsize: int = ..., - mode: str = ..., - openhook: Callable[[StrOrBytesPath, str], IO[AnyStr]] = ..., + mode: _TextMode = ..., + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = ..., + ) -> None: ... + # Because mode isn't keyword-only here yet, we need two overloads each for + # the bytes case and the fallback case. + @overload + def __init__( + self: FileInput[bytes], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., + inplace: bool = ..., + backup: str = ..., + bufsize: int = ..., + *, + mode: Literal["rb"], + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = ..., + ) -> None: ... + @overload + def __init__( + self: FileInput[bytes], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None, + inplace: bool, + backup: str, + bufsize: int, + mode: Literal["rb"], + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = ..., + ) -> None: ... + @overload + def __init__( + self: FileInput[Any], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = ..., + inplace: bool = ..., + backup: str = ..., + bufsize: int = ..., + *, + mode: str, + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = ..., + ) -> None: ... + @overload + def __init__( + self: FileInput[Any], + files: StrOrBytesPath | Iterable[StrOrBytesPath] | None, + inplace: bool, + backup: str, + bufsize: int, + mode: str, + openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = ..., ) -> None: ... def __del__(self) -> None: ... diff --git a/mypy/typeshed/stdlib/fractions.pyi b/mypy/typeshed/stdlib/fractions.pyi index 0d787a011f5b..fb64c659224a 100644 --- a/mypy/typeshed/stdlib/fractions.pyi +++ b/mypy/typeshed/stdlib/fractions.pyi @@ -1,9 +1,10 @@ import sys from _typeshed import Self +from collections.abc import Callable from decimal import Decimal from numbers import Integral, Rational, Real from typing import Any, overload -from typing_extensions import Literal, TypeAlias +from typing_extensions import Literal, SupportsIndex, TypeAlias _ComparableNum: TypeAlias = int | float | Decimal | Real @@ -118,7 +119,7 @@ class Fraction(Rational): @overload def __pow__(self, b: complex) -> complex: ... @overload - def __rpow__(self, a: int | float | Fraction) -> float: ... + def __rpow__(self, a: float | Fraction) -> float: ... @overload def __rpow__(self, a: complex) -> complex: ... def __pos__(self) -> Fraction: ... @@ -141,7 +142,7 @@ class Fraction(Rational): def __copy__(self: Self) -> Self: ... def __deepcopy__(self: Self, memo: Any) -> Self: ... if sys.version_info >= (3, 11): - def __int__(self) -> int: ... + def __int__(self, _index: Callable[[SupportsIndex], int] = ...) -> int: ... # Not actually defined within fractions.py, but provides more useful # overrides @property diff --git a/mypy/typeshed/stdlib/ftplib.pyi b/mypy/typeshed/stdlib/ftplib.pyi index 925ad5884700..49c680a6f0c7 100644 --- a/mypy/typeshed/stdlib/ftplib.pyi +++ b/mypy/typeshed/stdlib/ftplib.pyi @@ -70,7 +70,7 @@ class FTP: def getwelcome(self) -> str: ... def set_debuglevel(self, level: int) -> None: ... def debug(self, level: int) -> None: ... - def set_pasv(self, val: bool | int) -> None: ... + def set_pasv(self, val: bool | Literal[0, 1]) -> None: ... def sanitize(self, s: str) -> str: ... def putline(self, line: str) -> None: ... def putcmd(self, line: str) -> None: ... diff --git a/mypy/typeshed/stdlib/functools.pyi b/mypy/typeshed/stdlib/functools.pyi index 44feeed63f6a..3003ef061a84 100644 --- a/mypy/typeshed/stdlib/functools.pyi +++ b/mypy/typeshed/stdlib/functools.pyi @@ -1,6 +1,6 @@ import sys import types -from _typeshed import Self, SupportsAllComparisons, SupportsItems +from _typeshed import IdentityFunction, Self, SupportsAllComparisons, SupportsItems from collections.abc import Callable, Hashable, Iterable, Sequence, Sized from typing import Any, Generic, NamedTuple, TypeVar, overload from typing_extensions import Literal, TypeAlias, final @@ -8,52 +8,25 @@ from typing_extensions import Literal, TypeAlias, final if sys.version_info >= (3, 9): from types import GenericAlias - __all__ = [ - "update_wrapper", - "wraps", - "WRAPPER_ASSIGNMENTS", - "WRAPPER_UPDATES", - "total_ordering", - "cache", - "cmp_to_key", - "lru_cache", - "reduce", - "partial", - "partialmethod", - "singledispatch", - "singledispatchmethod", - "cached_property", - ] -elif sys.version_info >= (3, 8): - __all__ = [ - "update_wrapper", - "wraps", - "WRAPPER_ASSIGNMENTS", - "WRAPPER_UPDATES", - "total_ordering", - "cmp_to_key", - "lru_cache", - "reduce", - "partial", - "partialmethod", - "singledispatch", - "singledispatchmethod", - "cached_property", - ] -else: - __all__ = [ - "update_wrapper", - "wraps", - "WRAPPER_ASSIGNMENTS", - "WRAPPER_UPDATES", - "total_ordering", - "cmp_to_key", - "lru_cache", - "reduce", - "partial", - "partialmethod", - "singledispatch", - ] +__all__ = [ + "update_wrapper", + "wraps", + "WRAPPER_ASSIGNMENTS", + "WRAPPER_UPDATES", + "total_ordering", + "cmp_to_key", + "lru_cache", + "reduce", + "partial", + "partialmethod", + "singledispatch", +] + +if sys.version_info >= (3, 8): + __all__ += ["cached_property", "singledispatchmethod"] + +if sys.version_info >= (3, 9): + __all__ += ["cache"] _AnyCallable: TypeAlias = Callable[..., Any] @@ -95,7 +68,7 @@ WRAPPER_ASSIGNMENTS: tuple[ WRAPPER_UPDATES: tuple[Literal["__dict__"]] def update_wrapper(wrapper: _T, wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> _T: ... -def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ... +def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> IdentityFunction: ... def total_ordering(cls: type[_T]) -> type[_T]: ... def cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsAllComparisons]: ... diff --git a/mypy/typeshed/stdlib/genericpath.pyi b/mypy/typeshed/stdlib/genericpath.pyi index 984d0c3cf51e..911d582fd538 100644 --- a/mypy/typeshed/stdlib/genericpath.pyi +++ b/mypy/typeshed/stdlib/genericpath.pyi @@ -2,7 +2,7 @@ import os from _typeshed import BytesPath, StrOrBytesPath, StrPath, SupportsRichComparisonT from collections.abc import Sequence from typing import overload -from typing_extensions import Literal +from typing_extensions import Literal, LiteralString __all__ = [ "commonprefix", @@ -22,6 +22,8 @@ __all__ = [ # Iterable[T], so that list[T] | Literal[""] could be used as a return # type. But because this only works when T is str, we need Sequence[T] instead. @overload +def commonprefix(m: Sequence[LiteralString]) -> LiteralString: ... +@overload def commonprefix(m: Sequence[StrPath]) -> str: ... @overload def commonprefix(m: Sequence[BytesPath]) -> bytes | Literal[""]: ... diff --git a/mypy/typeshed/stdlib/gettext.pyi b/mypy/typeshed/stdlib/gettext.pyi index 829ade96cb40..3c07abeb2d8a 100644 --- a/mypy/typeshed/stdlib/gettext.pyi +++ b/mypy/typeshed/stdlib/gettext.pyi @@ -1,72 +1,30 @@ +import io import sys from _typeshed import StrPath -from collections.abc import Container, Iterable, Sequence +from collections.abc import Callable, Container, Iterable, Sequence from typing import Any, Protocol, TypeVar, overload from typing_extensions import Final, Literal -if sys.version_info >= (3, 11): - __all__ = [ - "NullTranslations", - "GNUTranslations", - "Catalog", - "bindtextdomain", - "find", - "translation", - "install", - "textdomain", - "dgettext", - "dngettext", - "gettext", - "ngettext", - "pgettext", - "dpgettext", - "npgettext", - "dnpgettext", - ] -elif sys.version_info >= (3, 8): - __all__ = [ - "NullTranslations", - "GNUTranslations", - "Catalog", - "find", - "translation", - "install", - "textdomain", - "bindtextdomain", - "bind_textdomain_codeset", - "dgettext", - "dngettext", - "gettext", - "lgettext", - "ldgettext", - "ldngettext", - "lngettext", - "ngettext", - "pgettext", - "dpgettext", - "npgettext", - "dnpgettext", - ] -else: - __all__ = [ - "NullTranslations", - "GNUTranslations", - "Catalog", - "find", - "translation", - "install", - "textdomain", - "bindtextdomain", - "bind_textdomain_codeset", - "dgettext", - "dngettext", - "gettext", - "lgettext", - "ldgettext", - "ldngettext", - "lngettext", - "ngettext", - ] +__all__ = [ + "NullTranslations", + "GNUTranslations", + "Catalog", + "find", + "translation", + "install", + "textdomain", + "bindtextdomain", + "dgettext", + "dngettext", + "gettext", + "ngettext", +] + +if sys.version_info < (3, 11): + __all__ += ["bind_textdomain_codeset", "ldgettext", "ldngettext", "lgettext", "lngettext"] + +if sys.version_info >= (3, 8): + __all__ += ["dnpgettext", "dpgettext", "npgettext", "pgettext"] class _TranslationsReader(Protocol): def read(self) -> bytes: ... @@ -78,9 +36,7 @@ class NullTranslations: def _parse(self, fp: _TranslationsReader) -> None: ... def add_fallback(self, fallback: NullTranslations) -> None: ... def gettext(self, message: str) -> str: ... - def lgettext(self, message: str) -> str: ... def ngettext(self, msgid1: str, msgid2: str, n: int) -> str: ... - def lngettext(self, msgid1: str, msgid2: str, n: int) -> str: ... if sys.version_info >= (3, 8): def pgettext(self, context: str, message: str) -> str: ... def npgettext(self, context: str, msgid1: str, msgid2: str, n: int) -> str: ... @@ -90,6 +46,8 @@ class NullTranslations: if sys.version_info < (3, 11): def output_charset(self) -> str | None: ... def set_output_charset(self, charset: str) -> None: ... + def lgettext(self, message: str) -> str: ... + def lngettext(self, msgid1: str, msgid2: str, n: int) -> str: ... def install(self, names: Container[str] | None = ...) -> None: ... @@ -110,7 +68,7 @@ def find( @overload def find(domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., all: bool = ...) -> Any: ... -_T = TypeVar("_T") +_NullTranslationsT = TypeVar("_NullTranslationsT", bound=NullTranslations) if sys.version_info >= (3, 11): @overload @@ -119,25 +77,34 @@ if sys.version_info >= (3, 11): localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., class_: None = ..., - fallback: bool = ..., - ) -> NullTranslations: ... + fallback: Literal[False] = ..., + ) -> GNUTranslations: ... @overload def translation( domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., - class_: type[_T] = ..., + *, + class_: Callable[[io.BufferedReader], _NullTranslationsT], + fallback: Literal[False] = ..., + ) -> _NullTranslationsT: ... + @overload + def translation( + domain: str, + localedir: StrPath | None, + languages: Iterable[str] | None, + class_: Callable[[io.BufferedReader], _NullTranslationsT], fallback: Literal[False] = ..., - ) -> _T: ... + ) -> _NullTranslationsT: ... @overload def translation( domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., - class_: type[Any] = ..., - fallback: Literal[True] = ..., - ) -> Any: ... - def install(domain: str, localedir: StrPath | None = ..., names: Container[str] | None = ...) -> None: ... + class_: Callable[[io.BufferedReader], NullTranslations] | None = ..., + fallback: bool = ..., + ) -> NullTranslations: ... + def install(domain: str, localedir: StrPath | None = ..., *, names: Container[str] | None = ...) -> None: ... else: @overload @@ -146,27 +113,37 @@ else: localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., class_: None = ..., - fallback: bool = ..., + fallback: Literal[False] = ..., codeset: str | None = ..., - ) -> NullTranslations: ... + ) -> GNUTranslations: ... @overload def translation( domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., - class_: type[_T] = ..., + *, + class_: Callable[[io.BufferedReader], _NullTranslationsT], + fallback: Literal[False] = ..., + codeset: str | None = ..., + ) -> _NullTranslationsT: ... + @overload + def translation( + domain: str, + localedir: StrPath | None, + languages: Iterable[str] | None, + class_: Callable[[io.BufferedReader], _NullTranslationsT], fallback: Literal[False] = ..., codeset: str | None = ..., - ) -> _T: ... + ) -> _NullTranslationsT: ... @overload def translation( domain: str, localedir: StrPath | None = ..., languages: Iterable[str] | None = ..., - class_: type[Any] = ..., - fallback: Literal[True] = ..., + class_: Callable[[io.BufferedReader], NullTranslations] | None = ..., + fallback: bool = ..., codeset: str | None = ..., - ) -> Any: ... + ) -> NullTranslations: ... def install( domain: str, localedir: StrPath | None = ..., codeset: str | None = ..., names: Container[str] | None = ... ) -> None: ... diff --git a/mypy/typeshed/stdlib/graphlib.pyi b/mypy/typeshed/stdlib/graphlib.pyi index 2fca402bf906..4c6959decc4b 100644 --- a/mypy/typeshed/stdlib/graphlib.pyi +++ b/mypy/typeshed/stdlib/graphlib.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import SupportsItems from collections.abc import Iterable -from typing import Any, Generic, TypeVar +from typing import Any, Generic, TypeVar, overload __all__ = ["TopologicalSorter", "CycleError"] @@ -11,7 +11,10 @@ if sys.version_info >= (3, 11): from types import GenericAlias class TopologicalSorter(Generic[_T]): - def __init__(self, graph: SupportsItems[_T, Iterable[_T]] | None = ...) -> None: ... + @overload + def __init__(self, graph: None = ...) -> None: ... + @overload + def __init__(self, graph: SupportsItems[_T, Iterable[_T]]) -> None: ... def add(self, node: _T, *predecessors: _T) -> None: ... def prepare(self) -> None: ... def is_active(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/hmac.pyi b/mypy/typeshed/stdlib/hmac.pyi index 858e46a71b68..a7bf15493f0b 100644 --- a/mypy/typeshed/stdlib/hmac.pyi +++ b/mypy/typeshed/stdlib/hmac.pyi @@ -42,4 +42,4 @@ def compare_digest(__a: ReadableBuffer, __b: ReadableBuffer) -> bool: ... def compare_digest(__a: AnyStr, __b: AnyStr) -> bool: ... if sys.version_info >= (3, 7): - def digest(key: bytes, msg: ReadableBuffer, digest: str) -> bytes: ... + def digest(key: bytes, msg: ReadableBuffer, digest: _DigestMod) -> bytes: ... diff --git a/mypy/typeshed/stdlib/imaplib.pyi b/mypy/typeshed/stdlib/imaplib.pyi index eef1c1957769..b082100774c0 100644 --- a/mypy/typeshed/stdlib/imaplib.pyi +++ b/mypy/typeshed/stdlib/imaplib.pyi @@ -169,7 +169,7 @@ class _Authenticator: def encode(self, inp: bytes) -> str: ... def decode(self, inp: str) -> bytes: ... -def Internaldate2tuple(resp: str) -> time.struct_time: ... +def Internaldate2tuple(resp: bytes) -> time.struct_time: ... def Int2AP(num: int) -> str: ... def ParseFlags(resp: str) -> tuple[str, ...]: ... def Time2Internaldate(date_time: float | time.struct_time | str) -> str: ... diff --git a/mypy/typeshed/stdlib/importlib/abc.pyi b/mypy/typeshed/stdlib/importlib/abc.pyi index 63fd02f7b3d5..805910329b64 100644 --- a/mypy/typeshed/stdlib/importlib/abc.pyi +++ b/mypy/typeshed/stdlib/importlib/abc.pyi @@ -16,6 +16,22 @@ from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWra from typing import IO, Any, BinaryIO, NoReturn, Protocol, overload, runtime_checkable from typing_extensions import Literal, TypeAlias +if sys.version_info >= (3, 11): + __all__ = [ + "Loader", + "Finder", + "MetaPathFinder", + "PathEntryFinder", + "ResourceLoader", + "InspectLoader", + "ExecutionLoader", + "FileLoader", + "SourceLoader", + "ResourceReader", + "Traversable", + "TraversableResources", + ] + _Path: TypeAlias = bytes | str class Finder(metaclass=ABCMeta): ... diff --git a/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi index 1f32f0770b37..6466ce0a23ac 100644 --- a/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata/__init__.pyi @@ -9,34 +9,21 @@ from os import PathLike from pathlib import Path from typing import Any, ClassVar, NamedTuple, Pattern, overload +__all__ = [ + "Distribution", + "DistributionFinder", + "PackageNotFoundError", + "distribution", + "distributions", + "entry_points", + "files", + "metadata", + "requires", + "version", +] + if sys.version_info >= (3, 10): - __all__ = [ - "Distribution", - "DistributionFinder", - "PackageMetadata", - "PackageNotFoundError", - "distribution", - "distributions", - "entry_points", - "files", - "metadata", - "packages_distributions", - "requires", - "version", - ] -else: - __all__ = [ - "Distribution", - "DistributionFinder", - "PackageNotFoundError", - "distribution", - "distributions", - "entry_points", - "files", - "metadata", - "requires", - "version", - ] + __all__ += ["PackageMetadata", "packages_distributions"] if sys.version_info >= (3, 10): from importlib.metadata._meta import PackageMetadata as PackageMetadata diff --git a/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi b/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi index a1101df0d5ce..6a7cd858c80b 100644 --- a/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi @@ -1,3 +1,4 @@ +import sys from collections.abc import Iterator from typing import Any, Protocol, TypeVar @@ -14,6 +15,9 @@ class PackageMetadata(Protocol): class SimplePath(Protocol): def joinpath(self) -> SimplePath: ... - def __div__(self) -> SimplePath: ... def parent(self) -> SimplePath: ... def read_text(self) -> str: ... + if sys.version_info >= (3, 11): + def __truediv__(self) -> SimplePath: ... + else: + def __div__(self) -> SimplePath: ... diff --git a/mypy/typeshed/stdlib/importlib/resources.pyi b/mypy/typeshed/stdlib/importlib/resources.pyi index 04d7e8dcc967..28ca107f4195 100644 --- a/mypy/typeshed/stdlib/importlib/resources.pyi +++ b/mypy/typeshed/stdlib/importlib/resources.pyi @@ -7,40 +7,20 @@ from types import ModuleType from typing import Any, BinaryIO, TextIO from typing_extensions import TypeAlias +__all__ = ["Package", "Resource", "contents", "is_resource", "open_binary", "open_text", "path", "read_binary", "read_text"] + +if sys.version_info >= (3, 9): + __all__ += ["as_file", "files"] + if sys.version_info >= (3, 10): - __all__ = [ - "Package", - "Resource", - "ResourceReader", - "as_file", - "contents", - "files", - "is_resource", - "open_binary", - "open_text", - "path", - "read_binary", - "read_text", - ] -elif sys.version_info >= (3, 9): - __all__ = [ - "Package", - "Resource", - "as_file", - "contents", - "files", - "is_resource", - "open_binary", - "open_text", - "path", - "read_binary", - "read_text", - ] -else: - __all__ = ["Package", "Resource", "contents", "is_resource", "open_binary", "open_text", "path", "read_binary", "read_text"] + __all__ += ["ResourceReader"] Package: TypeAlias = str | ModuleType -Resource: TypeAlias = str | os.PathLike[Any] + +if sys.version_info >= (3, 11): + Resource: TypeAlias = str +else: + Resource: TypeAlias = str | os.PathLike[Any] def open_binary(package: Package, resource: Resource) -> BinaryIO: ... def open_text(package: Package, resource: Resource, encoding: str = ..., errors: str = ...) -> TextIO: ... diff --git a/mypy/typeshed/stdlib/io.pyi b/mypy/typeshed/stdlib/io.pyi index 327fd0d94a4d..0670b65fe359 100644 --- a/mypy/typeshed/stdlib/io.pyi +++ b/mypy/typeshed/stdlib/io.pyi @@ -8,49 +8,29 @@ from types import TracebackType from typing import IO, Any, BinaryIO, TextIO from typing_extensions import Literal +__all__ = [ + "BlockingIOError", + "open", + "IOBase", + "RawIOBase", + "FileIO", + "BytesIO", + "StringIO", + "BufferedIOBase", + "BufferedReader", + "BufferedWriter", + "BufferedRWPair", + "BufferedRandom", + "TextIOBase", + "TextIOWrapper", + "UnsupportedOperation", + "SEEK_SET", + "SEEK_CUR", + "SEEK_END", +] + if sys.version_info >= (3, 8): - __all__ = [ - "BlockingIOError", - "open", - "open_code", - "IOBase", - "RawIOBase", - "FileIO", - "BytesIO", - "StringIO", - "BufferedIOBase", - "BufferedReader", - "BufferedWriter", - "BufferedRWPair", - "BufferedRandom", - "TextIOBase", - "TextIOWrapper", - "UnsupportedOperation", - "SEEK_SET", - "SEEK_CUR", - "SEEK_END", - ] -else: - __all__ = [ - "BlockingIOError", - "open", - "IOBase", - "RawIOBase", - "FileIO", - "BytesIO", - "StringIO", - "BufferedIOBase", - "BufferedReader", - "BufferedWriter", - "BufferedRWPair", - "BufferedRandom", - "TextIOBase", - "TextIOWrapper", - "UnsupportedOperation", - "SEEK_SET", - "SEEK_CUR", - "SEEK_END", - ] + __all__ += ["open_code"] DEFAULT_BUFFER_SIZE: Literal[8192] diff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi index 43a0e8038d69..7299ee8200db 100644 --- a/mypy/typeshed/stdlib/itertools.pyi +++ b/mypy/typeshed/stdlib/itertools.pyi @@ -18,7 +18,7 @@ _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") _T6 = TypeVar("_T6") -_Step: TypeAlias = int | float | SupportsFloat | SupportsInt | SupportsIndex | SupportsComplex +_Step: TypeAlias = SupportsFloat | SupportsInt | SupportsIndex | SupportsComplex _Predicate: TypeAlias = Callable[[_T], object] diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi index a998ad5fe49e..34df53994c92 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi @@ -3,149 +3,79 @@ from collections.abc import Callable, Iterable, Iterator from lib2to3.pgen2.token import * from typing_extensions import TypeAlias -if sys.version_info >= (3, 8): - __all__ = [ - "AMPER", - "AMPEREQUAL", - "ASYNC", - "AT", - "ATEQUAL", - "AWAIT", - "BACKQUOTE", - "CIRCUMFLEX", - "CIRCUMFLEXEQUAL", - "COLON", - "COLONEQUAL", - "COMMA", - "COMMENT", - "DEDENT", - "DOT", - "DOUBLESLASH", - "DOUBLESLASHEQUAL", - "DOUBLESTAR", - "DOUBLESTAREQUAL", - "ENDMARKER", - "EQEQUAL", - "EQUAL", - "ERRORTOKEN", - "GREATER", - "GREATEREQUAL", - "INDENT", - "ISEOF", - "ISNONTERMINAL", - "ISTERMINAL", - "LBRACE", - "LEFTSHIFT", - "LEFTSHIFTEQUAL", - "LESS", - "LESSEQUAL", - "LPAR", - "LSQB", - "MINEQUAL", - "MINUS", - "NAME", - "NEWLINE", - "NL", - "NOTEQUAL", - "NT_OFFSET", - "NUMBER", - "N_TOKENS", - "OP", - "PERCENT", - "PERCENTEQUAL", - "PLUS", - "PLUSEQUAL", - "RARROW", - "RBRACE", - "RIGHTSHIFT", - "RIGHTSHIFTEQUAL", - "RPAR", - "RSQB", - "SEMI", - "SLASH", - "SLASHEQUAL", - "STAR", - "STAREQUAL", - "STRING", - "TILDE", - "VBAR", - "VBAREQUAL", - "tok_name", - "tokenize", - "generate_tokens", - "untokenize", - ] -else: - __all__ = [ - "AMPER", - "AMPEREQUAL", - "ASYNC", - "AT", - "ATEQUAL", - "AWAIT", - "BACKQUOTE", - "CIRCUMFLEX", - "CIRCUMFLEXEQUAL", - "COLON", - "COMMA", - "COMMENT", - "DEDENT", - "DOT", - "DOUBLESLASH", - "DOUBLESLASHEQUAL", - "DOUBLESTAR", - "DOUBLESTAREQUAL", - "ENDMARKER", - "EQEQUAL", - "EQUAL", - "ERRORTOKEN", - "GREATER", - "GREATEREQUAL", - "INDENT", - "ISEOF", - "ISNONTERMINAL", - "ISTERMINAL", - "LBRACE", - "LEFTSHIFT", - "LEFTSHIFTEQUAL", - "LESS", - "LESSEQUAL", - "LPAR", - "LSQB", - "MINEQUAL", - "MINUS", - "NAME", - "NEWLINE", - "NL", - "NOTEQUAL", - "NT_OFFSET", - "NUMBER", - "N_TOKENS", - "OP", - "PERCENT", - "PERCENTEQUAL", - "PLUS", - "PLUSEQUAL", - "RARROW", - "RBRACE", - "RIGHTSHIFT", - "RIGHTSHIFTEQUAL", - "RPAR", - "RSQB", - "SEMI", - "SLASH", - "SLASHEQUAL", - "STAR", - "STAREQUAL", - "STRING", - "TILDE", - "VBAR", - "VBAREQUAL", - "tok_name", - "tokenize", - "generate_tokens", - "untokenize", - ] +__all__ = [ + "AMPER", + "AMPEREQUAL", + "ASYNC", + "AT", + "ATEQUAL", + "AWAIT", + "BACKQUOTE", + "CIRCUMFLEX", + "CIRCUMFLEXEQUAL", + "COLON", + "COMMA", + "COMMENT", + "DEDENT", + "DOT", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "DOUBLESTAR", + "DOUBLESTAREQUAL", + "ENDMARKER", + "EQEQUAL", + "EQUAL", + "ERRORTOKEN", + "GREATER", + "GREATEREQUAL", + "INDENT", + "ISEOF", + "ISNONTERMINAL", + "ISTERMINAL", + "LBRACE", + "LEFTSHIFT", + "LEFTSHIFTEQUAL", + "LESS", + "LESSEQUAL", + "LPAR", + "LSQB", + "MINEQUAL", + "MINUS", + "NAME", + "NEWLINE", + "NL", + "NOTEQUAL", + "NT_OFFSET", + "NUMBER", + "N_TOKENS", + "OP", + "PERCENT", + "PERCENTEQUAL", + "PLUS", + "PLUSEQUAL", + "RARROW", + "RBRACE", + "RIGHTSHIFT", + "RIGHTSHIFTEQUAL", + "RPAR", + "RSQB", + "SEMI", + "SLASH", + "SLASHEQUAL", + "STAR", + "STAREQUAL", + "STRING", + "TILDE", + "VBAR", + "VBAREQUAL", + "tok_name", + "tokenize", + "generate_tokens", + "untokenize", +] + +if sys.version_info >= (3, 7): + __all__ += ["COLONEQUAL"] _Coord: TypeAlias = tuple[int, int] _TokenEater: TypeAlias = Callable[[int, str, _Coord, _Coord, str], None] diff --git a/mypy/typeshed/stdlib/locale.pyi b/mypy/typeshed/stdlib/locale.pyi index 959054e847a8..393ddcbda841 100644 --- a/mypy/typeshed/stdlib/locale.pyi +++ b/mypy/typeshed/stdlib/locale.pyi @@ -29,6 +29,9 @@ __all__ = [ "CHAR_MAX", ] +if sys.version_info >= (3, 11): + __all__ += ["getencoding"] + # This module defines a function "str()", which is why "str" can't be used # as a type annotation or type alias. from builtins import str as _str @@ -126,7 +129,7 @@ if sys.version_info >= (3, 7): else: def format_string(f: _str, val: Any, grouping: bool = ...) -> _str: ... -def currency(val: int | float | Decimal, symbol: bool = ..., grouping: bool = ..., international: bool = ...) -> _str: ... +def currency(val: float | Decimal, symbol: bool = ..., grouping: bool = ..., international: bool = ...) -> _str: ... def delocalize(string: _str) -> _str: ... def atof(string: _str, func: Callable[[_str], float] = ...) -> float: ... def atoi(string: _str) -> int: ... @@ -143,6 +146,9 @@ if sys.platform == "linux" or sys.platform == "darwin": def bindtextdomain(__domain: _str, __dir: StrPath | None) -> _str: ... def bind_textdomain_codeset(__domain: _str, __codeset: _str | None) -> _str | None: ... +if sys.version_info >= (3, 11): + def getencoding() -> _str: ... + locale_alias: dict[_str, _str] # undocumented locale_encoding_alias: dict[_str, _str] # undocumented windows_locale: dict[int, _str] # undocumented diff --git a/mypy/typeshed/stdlib/logging/__init__.pyi b/mypy/typeshed/stdlib/logging/__init__.pyi index 6ad4cd4f94e7..6a8f66871a67 100644 --- a/mypy/typeshed/stdlib/logging/__init__.pyi +++ b/mypy/typeshed/stdlib/logging/__init__.pyi @@ -9,6 +9,9 @@ from types import FrameType, TracebackType from typing import Any, ClassVar, Generic, Pattern, TextIO, TypeVar, Union, overload from typing_extensions import Literal, TypeAlias +if sys.version_info >= (3, 11): + from types import GenericAlias + __all__ = [ "BASIC_FORMAT", "BufferingFormatter", @@ -54,6 +57,9 @@ __all__ = [ "raiseExceptions", ] +if sys.version_info >= (3, 11): + __all__ += ["getLevelNamesMapping"] + _SysExcInfoType: TypeAlias = Union[tuple[type[BaseException], BaseException, TracebackType | None], tuple[None, None, None]] _ExcInfoType: TypeAlias = None | bool | _SysExcInfoType | BaseException _ArgsType: TypeAlias = tuple[object, ...] | Mapping[str, object] @@ -407,6 +413,8 @@ class LogRecord: sinfo: str | None = ..., ) -> None: ... def getMessage(self) -> str: ... + # Allows setting contextual information on LogRecord objects as per the docs, see #7833 + def __setattr__(self, __name: str, __value: Any) -> None: ... _L = TypeVar("_L", bound=Logger | LoggerAdapter[Any]) @@ -593,6 +601,8 @@ class LoggerAdapter(Generic[_L]): ) -> None: ... # undocumented @property def name(self) -> str: ... # undocumented + if sys.version_info >= (3, 11): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... def getLogger(name: str | None = ...) -> Logger: ... def getLoggerClass() -> type[Logger]: ... @@ -706,6 +716,10 @@ else: def addLevelName(level: int, levelName: str) -> None: ... def getLevelName(level: _Level) -> Any: ... + +if sys.version_info >= (3, 11): + def getLevelNamesMapping() -> dict[str, int]: ... + def makeLogRecord(dict: Mapping[str, object]) -> LogRecord: ... if sys.version_info >= (3, 9): @@ -769,6 +783,8 @@ class StreamHandler(Handler, Generic[_StreamT]): def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None: ... if sys.version_info >= (3, 7): def setStream(self, stream: _StreamT) -> _StreamT | None: ... + if sys.version_info >= (3, 11): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... class FileHandler(StreamHandler[TextIOWrapper]): baseFilename: str # undocumented @@ -818,8 +834,8 @@ class PercentStyle: # undocumented def format(self, record: Any) -> str: ... class StrFormatStyle(PercentStyle): # undocumented - fmt_spec = Any - field_spec = Any + fmt_spec: Pattern[str] + field_spec: Pattern[str] class StringTemplateStyle(PercentStyle): # undocumented _tpl: Template diff --git a/mypy/typeshed/stdlib/logging/handlers.pyi b/mypy/typeshed/stdlib/logging/handlers.pyi index 640236149000..d3ea29075b81 100644 --- a/mypy/typeshed/stdlib/logging/handlers.pyi +++ b/mypy/typeshed/stdlib/logging/handlers.pyi @@ -181,6 +181,9 @@ class SysLogHandler(Handler): facility_names: ClassVar[dict[str, int]] # undocumented priority_map: ClassVar[dict[str, str]] # undocumented def __init__(self, address: tuple[str, int] | str = ..., facility: int = ..., socktype: SocketKind | None = ...) -> None: ... + if sys.version_info >= (3, 11): + def createSocket(self) -> None: ... + def encodePriority(self, facility: int | str, priority: int | str) -> int: ... def mapPriority(self, levelName: str) -> str: ... diff --git a/mypy/typeshed/stdlib/macpath.pyi b/mypy/typeshed/stdlib/macpath.pyi index 2512e086b735..37821f44b200 100644 --- a/mypy/typeshed/stdlib/macpath.pyi +++ b/mypy/typeshed/stdlib/macpath.pyi @@ -34,6 +34,41 @@ from posixpath import ( ) from typing import AnyStr, overload +__all__ = [ + "normcase", + "isabs", + "join", + "splitdrive", + "split", + "splitext", + "basename", + "dirname", + "commonprefix", + "getsize", + "getmtime", + "getatime", + "getctime", + "islink", + "exists", + "lexists", + "isdir", + "isfile", + "expanduser", + "expandvars", + "normpath", + "abspath", + "curdir", + "pardir", + "sep", + "pathsep", + "defpath", + "altsep", + "extsep", + "devnull", + "realpath", + "supports_unicode_filenames", +] + altsep: str | None @overload diff --git a/mypy/typeshed/stdlib/macurl2path.pyi b/mypy/typeshed/stdlib/macurl2path.pyi index 6aac6dfeace5..af74b11c7850 100644 --- a/mypy/typeshed/stdlib/macurl2path.pyi +++ b/mypy/typeshed/stdlib/macurl2path.pyi @@ -1,3 +1,5 @@ +__all__ = ["url2pathname", "pathname2url"] + def url2pathname(pathname: str) -> str: ... def pathname2url(pathname: str) -> str: ... def _pncomp2url(component: str | bytes) -> str: ... diff --git a/mypy/typeshed/stdlib/mailbox.pyi b/mypy/typeshed/stdlib/mailbox.pyi index 64183cd0b3a4..3169e8cfa689 100644 --- a/mypy/typeshed/stdlib/mailbox.pyi +++ b/mypy/typeshed/stdlib/mailbox.pyi @@ -46,9 +46,10 @@ class Mailbox(Generic[_MessageT]): _path: bytes | str # undocumented _factory: Callable[[IO[Any]], _MessageT] | None # undocumented - def __init__( - self, path: StrOrBytesPath, factory: Callable[[IO[Any]], _MessageT] | None = ..., create: bool = ... - ) -> None: ... + @overload + def __init__(self, path: StrOrBytesPath, factory: Callable[[IO[Any]], _MessageT], create: bool = ...) -> None: ... + @overload + def __init__(self, path: StrOrBytesPath, factory: None = ..., create: bool = ...) -> None: ... @abstractmethod def add(self, message: _MessageData) -> str: ... @abstractmethod diff --git a/mypy/typeshed/stdlib/mmap.pyi b/mypy/typeshed/stdlib/mmap.pyi index 96bb01a271fc..8dbec2388838 100644 --- a/mypy/typeshed/stdlib/mmap.pyi +++ b/mypy/typeshed/stdlib/mmap.pyi @@ -79,6 +79,7 @@ if sys.version_info >= (3, 8) and sys.platform != "win32": MADV_SEQUENTIAL: int MADV_WILLNEED: int MADV_DONTNEED: int + MADV_FREE: int if sys.platform == "linux": MADV_REMOVE: int @@ -94,7 +95,6 @@ if sys.version_info >= (3, 8) and sys.platform != "win32": MADV_NOHUGEPAGE: int MADV_DONTDUMP: int MADV_DODUMP: int - MADV_FREE: int # This Values are defined for FreeBSD but type checkers do not support conditions for these if sys.platform != "linux" and sys.platform != "darwin": diff --git a/mypy/typeshed/stdlib/modulefinder.pyi b/mypy/typeshed/stdlib/modulefinder.pyi index cd01e0e1381f..caed7efadccc 100644 --- a/mypy/typeshed/stdlib/modulefinder.pyi +++ b/mypy/typeshed/stdlib/modulefinder.pyi @@ -3,12 +3,13 @@ from collections.abc import Container, Iterable, Iterator, Sequence from types import CodeType from typing import IO, Any -LOAD_CONST: int # undocumented -IMPORT_NAME: int # undocumented -STORE_NAME: int # undocumented -STORE_GLOBAL: int # undocumented -STORE_OPS: tuple[int, int] # undocumented -EXTENDED_ARG: int # undocumented +if sys.version_info < (3, 11): + LOAD_CONST: int # undocumented + IMPORT_NAME: int # undocumented + STORE_NAME: int # undocumented + STORE_GLOBAL: int # undocumented + STORE_OPS: tuple[int, int] # undocumented + EXTENDED_ARG: int # undocumented packagePathMap: dict[str, list[str]] # undocumented diff --git a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi index 87ceda10573d..41af971bc619 100644 --- a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi @@ -29,85 +29,47 @@ if sys.version_info >= (3, 8): if sys.platform != "win32": from multiprocessing.context import ForkContext, ForkServerContext +__all__ = [ + "Array", + "AuthenticationError", + "Barrier", + "BoundedSemaphore", + "BufferTooShort", + "Condition", + "Event", + "JoinableQueue", + "Lock", + "Manager", + "Pipe", + "Pool", + "Process", + "ProcessError", + "Queue", + "RLock", + "RawArray", + "RawValue", + "Semaphore", + "SimpleQueue", + "TimeoutError", + "Value", + "active_children", + "allow_connection_pickling", + "cpu_count", + "current_process", + "freeze_support", + "get_all_start_methods", + "get_context", + "get_logger", + "get_start_method", + "log_to_stderr", + "reducer", + "set_executable", + "set_forkserver_preload", + "set_start_method", +] + if sys.version_info >= (3, 8): - __all__ = [ - "Array", - "AuthenticationError", - "Barrier", - "BoundedSemaphore", - "BufferTooShort", - "Condition", - "Event", - "JoinableQueue", - "Lock", - "Manager", - "Pipe", - "Pool", - "Process", - "ProcessError", - "Queue", - "RLock", - "RawArray", - "RawValue", - "Semaphore", - "SimpleQueue", - "TimeoutError", - "Value", - "active_children", - "allow_connection_pickling", - "cpu_count", - "current_process", - "freeze_support", - "get_all_start_methods", - "get_context", - "get_logger", - "get_start_method", - "parent_process", - "log_to_stderr", - "reducer", - "set_executable", - "set_forkserver_preload", - "set_start_method", - ] -else: - __all__ = [ - "Array", - "AuthenticationError", - "Barrier", - "BoundedSemaphore", - "BufferTooShort", - "Condition", - "Event", - "JoinableQueue", - "Lock", - "Manager", - "Pipe", - "Pool", - "Process", - "ProcessError", - "Queue", - "RLock", - "RawArray", - "RawValue", - "Semaphore", - "SimpleQueue", - "TimeoutError", - "Value", - "active_children", - "allow_connection_pickling", - "cpu_count", - "current_process", - "freeze_support", - "get_all_start_methods", - "get_context", - "get_logger", - "get_start_method", - "log_to_stderr", - "reducer", - "set_executable", - "set_forkserver_preload", - "set_start_method", - ] + __all__ += ["parent_process"] # The following type aliases can be used to annotate the return values of # the corresponding functions. They are not defined at runtime. diff --git a/mypy/typeshed/stdlib/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi index b8d5ddda0f35..212ffcbf5a3a 100644 --- a/mypy/typeshed/stdlib/multiprocessing/managers.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/managers.pyi @@ -1,12 +1,11 @@ import queue import sys import threading -from _typeshed import Self -from builtins import dict as _dict, list as _list # Conflicts with method names -from collections.abc import Callable, Iterable, Mapping, Sequence +from _typeshed import Self, SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT +from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence from types import TracebackType -from typing import Any, AnyStr, Generic, TypeVar -from typing_extensions import TypeAlias +from typing import Any, AnyStr, ClassVar, Generic, TypeVar, overload +from typing_extensions import SupportsIndex, TypeAlias from .connection import Connection from .context import BaseContext @@ -66,6 +65,62 @@ class ValueProxy(BaseProxy, Generic[_T]): if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... +class DictProxy(BaseProxy, MutableMapping[_KT, _VT]): + __builtins__: ClassVar[dict[str, Any]] + def __len__(self) -> int: ... + def __getitem__(self, __k: _KT) -> _VT: ... + def __setitem__(self, __k: _KT, __v: _VT) -> None: ... + def __delitem__(self, __v: _KT) -> None: ... + def __iter__(self) -> Iterator[_KT]: ... + def copy(self) -> dict[_KT, _VT]: ... + @overload + def get(self, __key: _KT) -> _VT | None: ... + @overload + def get(self, __key: _KT, __default: _VT | _T) -> _VT | _T: ... + @overload + def pop(self, __key: _KT) -> _VT: ... + @overload + def pop(self, __key: _KT, __default: _VT | _T) -> _VT | _T: ... + def keys(self) -> list[_KT]: ... # type: ignore[override] + def values(self) -> list[tuple[_KT, _VT]]: ... # type: ignore[override] + def items(self) -> list[_VT]: ... # type: ignore[override] + if sys.version_info < (3, 7): + def has_key(self, k: _KT) -> bool: ... + +class BaseListProxy(BaseProxy, MutableSequence[_T]): + __builtins__: ClassVar[dict[str, Any]] + def __len__(self) -> int: ... + def __add__(self, __x: list[_T]) -> list[_T]: ... + def __delitem__(self, __i: SupportsIndex | slice) -> None: ... + @overload + def __getitem__(self, __i: SupportsIndex) -> _T: ... + @overload + def __getitem__(self, __s: slice) -> list[_T]: ... + @overload + def __setitem__(self, __i: SupportsIndex, __o: _T) -> None: ... + @overload + def __setitem__(self, __s: slice, __o: Iterable[_T]) -> None: ... + def __mul__(self, __n: SupportsIndex) -> list[_T]: ... + def __rmul__(self, __n: SupportsIndex) -> list[_T]: ... + def __reversed__(self) -> Iterator[_T]: ... + def append(self, __object: _T) -> None: ... + def extend(self, __iterable: Iterable[_T]) -> None: ... + def pop(self, __index: SupportsIndex = ...) -> _T: ... + def index(self, __value: _T, __start: SupportsIndex = ..., __stop: SupportsIndex = ...) -> int: ... + def count(self, __value: _T) -> int: ... + def insert(self, __index: SupportsIndex, __object: _T) -> None: ... + def remove(self, __value: _T) -> None: ... + # Use BaseListProxy[SupportsRichComparisonT] for the first overload rather than [SupportsRichComparison] + # to work around invariance + @overload + def sort(self: BaseListProxy[SupportsRichComparisonT], *, key: None = ..., reverse: bool = ...) -> None: ... + @overload + def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> None: ... + +class ListProxy(BaseListProxy[_T]): + def __iadd__(self: Self, __x: Iterable[_T]) -> Self: ... # type: ignore[override] + def __imul__(self: Self, __n: SupportsIndex) -> Self: ... # type: ignore[override] + # Returned by BaseManager.get_server() class Server: address: Any @@ -124,8 +179,21 @@ class SyncManager(BaseManager): def Semaphore(self, value: Any = ...) -> threading.Semaphore: ... def Array(self, typecode: Any, sequence: Sequence[_T]) -> Sequence[_T]: ... def Value(self, typecode: Any, value: _T) -> ValueProxy[_T]: ... - def dict(self, sequence: Mapping[_KT, _VT] = ...) -> _dict[_KT, _VT]: ... - def list(self, sequence: Sequence[_T] = ...) -> _list[_T]: ... + # Overloads are copied from builtins.dict.__init__ + @overload + def dict(self) -> DictProxy[Any, Any]: ... + @overload + def dict(self, **kwargs: _VT) -> DictProxy[str, _VT]: ... + @overload + def dict(self, __map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> DictProxy[_KT, _VT]: ... + @overload + def dict(self, __iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> DictProxy[_KT, _VT]: ... + @overload + def dict(self, __iterable: Iterable[list[str]]) -> DictProxy[str, str]: ... + @overload + def list(self, __sequence: Sequence[_T]) -> ListProxy[_T]: ... + @overload + def list(self) -> ListProxy[Any]: ... class RemoteError(Exception): ... diff --git a/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi index 76ccedaf478e..3ce0ca3863cc 100644 --- a/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import Self from collections.abc import Iterable -from typing import Any, Generic, TypeVar +from typing import Any, Generic, TypeVar, overload if sys.version_info >= (3, 9): from types import GenericAlias @@ -23,7 +23,10 @@ class SharedMemory: class ShareableList(Generic[_SLT]): shm: SharedMemory - def __init__(self, sequence: Iterable[_SLT] | None = ..., *, name: str | None = ...) -> None: ... + @overload + def __init__(self, sequence: None = ..., *, name: str | None = ...) -> None: ... + @overload + def __init__(self, sequence: Iterable[_SLT], *, name: str | None = ...) -> None: ... def __getitem__(self, position: int) -> _SLT: ... def __setitem__(self, position: int, value: _SLT) -> None: ... def __reduce__(self: Self) -> tuple[Self, tuple[_SLT, ...]]: ... diff --git a/mypy/typeshed/stdlib/ntpath.pyi b/mypy/typeshed/stdlib/ntpath.pyi index ffe5cc1e5a2d..78aa2346835c 100644 --- a/mypy/typeshed/stdlib/ntpath.pyi +++ b/mypy/typeshed/stdlib/ntpath.pyi @@ -43,99 +43,62 @@ from posixpath import ( supports_unicode_filenames as supports_unicode_filenames, ) from typing import AnyStr, overload +from typing_extensions import LiteralString -if sys.version_info >= (3, 7) or sys.platform != "win32": - __all__ = [ - "normcase", - "isabs", - "join", - "splitdrive", - "split", - "splitext", - "basename", - "dirname", - "commonprefix", - "getsize", - "getmtime", - "getatime", - "getctime", - "islink", - "exists", - "lexists", - "isdir", - "isfile", - "ismount", - "expanduser", - "expandvars", - "normpath", - "abspath", - "curdir", - "pardir", - "sep", - "pathsep", - "defpath", - "altsep", - "extsep", - "devnull", - "realpath", - "supports_unicode_filenames", - "relpath", - "samefile", - "sameopenfile", - "samestat", - "commonpath", - ] -else: - __all__ = [ - "normcase", - "isabs", - "join", - "splitdrive", - "split", - "splitext", - "basename", - "dirname", - "commonprefix", - "getsize", - "getmtime", - "getatime", - "getctime", - "islink", - "exists", - "lexists", - "isdir", - "isfile", - "ismount", - "expanduser", - "expandvars", - "normpath", - "abspath", - "splitunc", - "curdir", - "pardir", - "sep", - "pathsep", - "defpath", - "altsep", - "extsep", - "devnull", - "realpath", - "supports_unicode_filenames", - "relpath", - "samefile", - "sameopenfile", - "samestat", - "commonpath", - ] +__all__ = [ + "normcase", + "isabs", + "join", + "splitdrive", + "split", + "splitext", + "basename", + "dirname", + "commonprefix", + "getsize", + "getmtime", + "getatime", + "getctime", + "islink", + "exists", + "lexists", + "isdir", + "isfile", + "ismount", + "expanduser", + "expandvars", + "normpath", + "abspath", + "curdir", + "pardir", + "sep", + "pathsep", + "defpath", + "altsep", + "extsep", + "devnull", + "realpath", + "supports_unicode_filenames", + "relpath", + "samefile", + "sameopenfile", + "samestat", + "commonpath", +] + +if sys.version_info < (3, 7): + __all__ += ["splitunc"] def splitunc(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... # deprecated -altsep: str +altsep: LiteralString # First parameter is not actually pos-only, # but must be defined as pos-only in the stub or cross-platform code doesn't type-check, # as the parameter name is different in posixpath.join() @overload +def join(__path: LiteralString, *paths: LiteralString) -> LiteralString: ... +@overload def join(__path: StrPath, *paths: StrPath) -> str: ... @overload def join(__path: BytesPath, *paths: BytesPath) -> bytes: ... diff --git a/mypy/typeshed/stdlib/operator.pyi b/mypy/typeshed/stdlib/operator.pyi index 603e15ebc7be..c3fc4b0a8503 100644 --- a/mypy/typeshed/stdlib/operator.pyi +++ b/mypy/typeshed/stdlib/operator.pyi @@ -2,121 +2,65 @@ import sys from _operator import * +__all__ = [ + "abs", + "add", + "and_", + "attrgetter", + "concat", + "contains", + "countOf", + "delitem", + "eq", + "floordiv", + "ge", + "getitem", + "gt", + "iadd", + "iand", + "iconcat", + "ifloordiv", + "ilshift", + "imatmul", + "imod", + "imul", + "index", + "indexOf", + "inv", + "invert", + "ior", + "ipow", + "irshift", + "is_", + "is_not", + "isub", + "itemgetter", + "itruediv", + "ixor", + "le", + "length_hint", + "lshift", + "lt", + "matmul", + "methodcaller", + "mod", + "mul", + "ne", + "neg", + "not_", + "or_", + "pos", + "pow", + "rshift", + "setitem", + "sub", + "truediv", + "truth", + "xor", +] + if sys.version_info >= (3, 11): - __all__ = [ - "abs", - "add", - "and_", - "attrgetter", - "call", - "concat", - "contains", - "countOf", - "delitem", - "eq", - "floordiv", - "ge", - "getitem", - "gt", - "iadd", - "iand", - "iconcat", - "ifloordiv", - "ilshift", - "imatmul", - "imod", - "imul", - "index", - "indexOf", - "inv", - "invert", - "ior", - "ipow", - "irshift", - "is_", - "is_not", - "isub", - "itemgetter", - "itruediv", - "ixor", - "le", - "length_hint", - "lshift", - "lt", - "matmul", - "methodcaller", - "mod", - "mul", - "ne", - "neg", - "not_", - "or_", - "pos", - "pow", - "rshift", - "setitem", - "sub", - "truediv", - "truth", - "xor", - ] -else: - __all__ = [ - "abs", - "add", - "and_", - "attrgetter", - "concat", - "contains", - "countOf", - "delitem", - "eq", - "floordiv", - "ge", - "getitem", - "gt", - "iadd", - "iand", - "iconcat", - "ifloordiv", - "ilshift", - "imatmul", - "imod", - "imul", - "index", - "indexOf", - "inv", - "invert", - "ior", - "ipow", - "irshift", - "is_", - "is_not", - "isub", - "itemgetter", - "itruediv", - "ixor", - "le", - "length_hint", - "lshift", - "lt", - "matmul", - "methodcaller", - "mod", - "mul", - "ne", - "neg", - "not_", - "or_", - "pos", - "pow", - "rshift", - "setitem", - "sub", - "truediv", - "truth", - "xor", - ] + __all__ += ["call"] __lt__ = lt __le__ = le diff --git a/mypy/typeshed/stdlib/optparse.pyi b/mypy/typeshed/stdlib/optparse.pyi index 1e7428f59a95..b571ff0680b7 100644 --- a/mypy/typeshed/stdlib/optparse.pyi +++ b/mypy/typeshed/stdlib/optparse.pyi @@ -240,7 +240,10 @@ class OptionParser(OptionContainer): def get_prog_name(self) -> str: ... def get_usage(self) -> str: ... def get_version(self) -> str: ... - def parse_args(self, args: Sequence[AnyStr] | None = ..., values: Values | None = ...) -> tuple[Values, list[AnyStr]]: ... + @overload + def parse_args(self, args: None = ..., values: Values | None = ...) -> tuple[Values, list[str]]: ... + @overload + def parse_args(self, args: Sequence[AnyStr], values: Values | None = ...) -> tuple[Values, list[AnyStr]]: ... def print_usage(self, file: IO[str] | None = ...) -> None: ... def print_help(self, file: IO[str] | None = ...) -> None: ... def print_version(self, file: IO[str] | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/os/__init__.pyi b/mypy/typeshed/stdlib/os/__init__.pyi index 2310de701d54..68ea2948f17e 100644 --- a/mypy/typeshed/stdlib/os/__init__.pyi +++ b/mypy/typeshed/stdlib/os/__init__.pyi @@ -1,7 +1,9 @@ import sys from _typeshed import ( + AnyStr_co, BytesPath, FileDescriptorLike, + GenericPath, OpenBinaryMode, OpenBinaryModeReading, OpenBinaryModeUpdating, @@ -32,7 +34,6 @@ path = _path _T = TypeVar("_T") _T1 = TypeVar("_T1") _T2 = TypeVar("_T2") -_AnyStr_co = TypeVar("_AnyStr_co", str, bytes, covariant=True) # ----- os variables ----- @@ -356,9 +357,9 @@ class stat_result(structseq[float], tuple[int, int, int, int, int, int, int, flo # See https://github.com/python/typeshed/pull/6560#issuecomment-991253327 @runtime_checkable -class PathLike(Protocol[_AnyStr_co]): +class PathLike(Protocol[AnyStr_co]): @abstractmethod - def __fspath__(self) -> _AnyStr_co: ... + def __fspath__(self) -> AnyStr_co: ... @overload def listdir(path: StrPath | None = ...) -> list[str]: ... @@ -726,7 +727,7 @@ if sys.platform != "win32": def makedev(__major: int, __minor: int) -> int: ... def pathconf(path: _FdOrAnyPath, name: str | int) -> int: ... # Unix only -def readlink(path: AnyStr | PathLike[AnyStr], *, dir_fd: int | None = ...) -> AnyStr: ... +def readlink(path: GenericPath[AnyStr], *, dir_fd: int | None = ...) -> AnyStr: ... def remove(path: StrOrBytesPath, *, dir_fd: int | None = ...) -> None: ... def removedirs(name: StrOrBytesPath) -> None: ... def rename(src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = ..., dst_dir_fd: int | None = ...) -> None: ... @@ -747,7 +748,7 @@ if sys.version_info >= (3, 7): def scandir(path: int) -> _ScandirIterator[str]: ... @overload -def scandir(path: AnyStr | PathLike[AnyStr]) -> _ScandirIterator[AnyStr]: ... +def scandir(path: GenericPath[AnyStr]) -> _ScandirIterator[AnyStr]: ... def stat(path: _FdOrAnyPath, *, dir_fd: int | None = ..., follow_symlinks: bool = ...) -> stat_result: ... if sys.version_info < (3, 7): @@ -778,7 +779,7 @@ def utime( _OnError: TypeAlias = Callable[[OSError], Any] def walk( - top: AnyStr | PathLike[AnyStr], topdown: bool = ..., onerror: _OnError | None = ..., followlinks: bool = ... + top: GenericPath[AnyStr], topdown: bool = ..., onerror: _OnError | None = ..., followlinks: bool = ... ) -> Iterator[tuple[AnyStr, list[AnyStr], list[AnyStr]]]: ... if sys.platform != "win32": diff --git a/mypy/typeshed/stdlib/pdb.pyi b/mypy/typeshed/stdlib/pdb.pyi index e787b4a4c416..3c2cabe8abe2 100644 --- a/mypy/typeshed/stdlib/pdb.pyi +++ b/mypy/typeshed/stdlib/pdb.pyi @@ -74,7 +74,9 @@ class Pdb(Bdb, Cmd): def print_stack_trace(self) -> None: ... def print_stack_entry(self, frame_lineno: tuple[FrameType, int], prompt_prefix: str = ...) -> None: ... def lookupmodule(self, filename: str) -> str | None: ... - def _runscript(self, filename: str) -> None: ... + if sys.version_info < (3, 11): + def _runscript(self, filename: str) -> None: ... + def do_commands(self, arg: str) -> bool | None: ... def do_break(self, arg: str, temporary: bool = ...) -> bool | None: ... def do_tbreak(self, arg: str) -> bool | None: ... @@ -165,7 +167,7 @@ class Pdb(Bdb, Cmd): complete_whatis = _complete_expression complete_display = _complete_expression - if sys.version_info >= (3, 7): + if sys.version_info >= (3, 7) and sys.version_info < (3, 11): def _runmodule(self, module_name: str) -> None: ... # undocumented diff --git a/mypy/typeshed/stdlib/pickle.pyi b/mypy/typeshed/stdlib/pickle.pyi index d58cf8ed9d50..088adc8196c2 100644 --- a/mypy/typeshed/stdlib/pickle.pyi +++ b/mypy/typeshed/stdlib/pickle.pyi @@ -4,172 +4,89 @@ from collections.abc import Callable, Iterable, Iterator, Mapping from typing import Any, ClassVar, Protocol, SupportsBytes, Union from typing_extensions import SupportsIndex, TypeAlias, final +__all__ = [ + "PickleError", + "PicklingError", + "UnpicklingError", + "Pickler", + "Unpickler", + "dump", + "dumps", + "load", + "loads", + "ADDITEMS", + "APPEND", + "APPENDS", + "BINBYTES", + "BINBYTES8", + "BINFLOAT", + "BINGET", + "BININT", + "BININT1", + "BININT2", + "BINPERSID", + "BINPUT", + "BINSTRING", + "BINUNICODE", + "BINUNICODE8", + "BUILD", + "DEFAULT_PROTOCOL", + "DICT", + "DUP", + "EMPTY_DICT", + "EMPTY_LIST", + "EMPTY_SET", + "EMPTY_TUPLE", + "EXT1", + "EXT2", + "EXT4", + "FALSE", + "FLOAT", + "FRAME", + "FROZENSET", + "GET", + "GLOBAL", + "HIGHEST_PROTOCOL", + "INST", + "INT", + "LIST", + "LONG", + "LONG1", + "LONG4", + "LONG_BINGET", + "LONG_BINPUT", + "MARK", + "MEMOIZE", + "NEWFALSE", + "NEWOBJ", + "NEWOBJ_EX", + "NEWTRUE", + "NONE", + "OBJ", + "PERSID", + "POP", + "POP_MARK", + "PROTO", + "PUT", + "REDUCE", + "SETITEM", + "SETITEMS", + "SHORT_BINBYTES", + "SHORT_BINSTRING", + "SHORT_BINUNICODE", + "STACK_GLOBAL", + "STOP", + "STRING", + "TRUE", + "TUPLE", + "TUPLE1", + "TUPLE2", + "TUPLE3", + "UNICODE", +] + if sys.version_info >= (3, 8): - __all__ = [ - "PickleError", - "PicklingError", - "UnpicklingError", - "Pickler", - "Unpickler", - "dump", - "dumps", - "load", - "loads", - "PickleBuffer", - "ADDITEMS", - "APPEND", - "APPENDS", - "BINBYTES", - "BINBYTES8", - "BINFLOAT", - "BINGET", - "BININT", - "BININT1", - "BININT2", - "BINPERSID", - "BINPUT", - "BINSTRING", - "BINUNICODE", - "BINUNICODE8", - "BUILD", - "BYTEARRAY8", - "DEFAULT_PROTOCOL", - "DICT", - "DUP", - "EMPTY_DICT", - "EMPTY_LIST", - "EMPTY_SET", - "EMPTY_TUPLE", - "EXT1", - "EXT2", - "EXT4", - "FALSE", - "FLOAT", - "FRAME", - "FROZENSET", - "GET", - "GLOBAL", - "HIGHEST_PROTOCOL", - "INST", - "INT", - "LIST", - "LONG", - "LONG1", - "LONG4", - "LONG_BINGET", - "LONG_BINPUT", - "MARK", - "MEMOIZE", - "NEWFALSE", - "NEWOBJ", - "NEWOBJ_EX", - "NEWTRUE", - "NEXT_BUFFER", - "NONE", - "OBJ", - "PERSID", - "POP", - "POP_MARK", - "PROTO", - "PUT", - "READONLY_BUFFER", - "REDUCE", - "SETITEM", - "SETITEMS", - "SHORT_BINBYTES", - "SHORT_BINSTRING", - "SHORT_BINUNICODE", - "STACK_GLOBAL", - "STOP", - "STRING", - "TRUE", - "TUPLE", - "TUPLE1", - "TUPLE2", - "TUPLE3", - "UNICODE", - ] -else: - __all__ = [ - "PickleError", - "PicklingError", - "UnpicklingError", - "Pickler", - "Unpickler", - "dump", - "dumps", - "load", - "loads", - "ADDITEMS", - "APPEND", - "APPENDS", - "BINBYTES", - "BINBYTES8", - "BINFLOAT", - "BINGET", - "BININT", - "BININT1", - "BININT2", - "BINPERSID", - "BINPUT", - "BINSTRING", - "BINUNICODE", - "BINUNICODE8", - "BUILD", - "DEFAULT_PROTOCOL", - "DICT", - "DUP", - "EMPTY_DICT", - "EMPTY_LIST", - "EMPTY_SET", - "EMPTY_TUPLE", - "EXT1", - "EXT2", - "EXT4", - "FALSE", - "FLOAT", - "FRAME", - "FROZENSET", - "GET", - "GLOBAL", - "HIGHEST_PROTOCOL", - "INST", - "INT", - "LIST", - "LONG", - "LONG1", - "LONG4", - "LONG_BINGET", - "LONG_BINPUT", - "MARK", - "MEMOIZE", - "NEWFALSE", - "NEWOBJ", - "NEWOBJ_EX", - "NEWTRUE", - "NONE", - "OBJ", - "PERSID", - "POP", - "POP_MARK", - "PROTO", - "PUT", - "REDUCE", - "SETITEM", - "SETITEMS", - "SHORT_BINBYTES", - "SHORT_BINSTRING", - "SHORT_BINUNICODE", - "STACK_GLOBAL", - "STOP", - "STRING", - "TRUE", - "TUPLE", - "TUPLE1", - "TUPLE2", - "TUPLE3", - "UNICODE", - ] + __all__ += ["BYTEARRAY8", "NEXT_BUFFER", "PickleBuffer", "READONLY_BUFFER"] HIGHEST_PROTOCOL: int DEFAULT_PROTOCOL: int diff --git a/mypy/typeshed/stdlib/posixpath.pyi b/mypy/typeshed/stdlib/posixpath.pyi index 4cec7c770ea3..8d880a072dfb 100644 --- a/mypy/typeshed/stdlib/posixpath.pyi +++ b/mypy/typeshed/stdlib/posixpath.pyi @@ -1,5 +1,5 @@ import sys -from _typeshed import BytesPath, StrOrBytesPath, StrPath +from _typeshed import AnyOrLiteralStr, BytesPath, StrOrBytesPath, StrPath from collections.abc import Sequence from genericpath import ( commonprefix as commonprefix, @@ -16,6 +16,7 @@ from genericpath import ( ) from os import PathLike from typing import AnyStr, overload +from typing_extensions import LiteralString __all__ = [ "normcase", @@ -60,14 +61,14 @@ __all__ = [ supports_unicode_filenames: bool # aliases (also in os) -curdir: str -pardir: str -sep: str -altsep: str | None -extsep: str -pathsep: str -defpath: str -devnull: str +curdir: LiteralString +pardir: LiteralString +sep: LiteralString +altsep: LiteralString | None +extsep: LiteralString +pathsep: LiteralString +defpath: LiteralString +devnull: LiteralString # Overloads are necessary to work around python/mypy#3644. @overload @@ -77,11 +78,11 @@ def abspath(path: AnyStr) -> AnyStr: ... @overload def basename(p: PathLike[AnyStr]) -> AnyStr: ... @overload -def basename(p: AnyStr) -> AnyStr: ... +def basename(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ... @overload def dirname(p: PathLike[AnyStr]) -> AnyStr: ... @overload -def dirname(p: AnyStr) -> AnyStr: ... +def dirname(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ... @overload def expanduser(path: PathLike[AnyStr]) -> AnyStr: ... @overload @@ -93,11 +94,13 @@ def expandvars(path: AnyStr) -> AnyStr: ... @overload def normcase(s: PathLike[AnyStr]) -> AnyStr: ... @overload -def normcase(s: AnyStr) -> AnyStr: ... +def normcase(s: AnyOrLiteralStr) -> AnyOrLiteralStr: ... @overload def normpath(path: PathLike[AnyStr]) -> AnyStr: ... @overload -def normpath(path: AnyStr) -> AnyStr: ... +def normpath(path: AnyOrLiteralStr) -> AnyOrLiteralStr: ... +@overload +def commonpath(paths: Sequence[LiteralString]) -> LiteralString: ... @overload def commonpath(paths: Sequence[StrPath]) -> str: ... @overload @@ -107,6 +110,8 @@ def commonpath(paths: Sequence[BytesPath]) -> bytes: ... # but must be defined as pos-only in the stub or cross-platform code doesn't type-check, # as the parameter name is different in ntpath.join() @overload +def join(__a: LiteralString, *paths: LiteralString) -> LiteralString: ... +@overload def join(__a: StrPath, *paths: StrPath) -> str: ... @overload def join(__a: BytesPath, *paths: BytesPath) -> bytes: ... @@ -123,6 +128,8 @@ else: @overload def realpath(filename: AnyStr) -> AnyStr: ... +@overload +def relpath(path: LiteralString, start: LiteralString | None = ...) -> LiteralString: ... @overload def relpath(path: BytesPath, start: BytesPath | None = ...) -> bytes: ... @overload @@ -130,15 +137,15 @@ def relpath(path: StrPath, start: StrPath | None = ...) -> str: ... @overload def split(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... @overload -def split(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... +def split(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... @overload def splitdrive(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... @overload -def splitdrive(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... +def splitdrive(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... @overload def splitext(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ... @overload -def splitext(p: AnyStr) -> tuple[AnyStr, AnyStr]: ... +def splitext(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ... def isabs(s: StrOrBytesPath) -> bool: ... def islink(path: StrOrBytesPath | int) -> bool: ... def ismount(path: StrOrBytesPath | int) -> bool: ... diff --git a/mypy/typeshed/stdlib/pydoc.pyi b/mypy/typeshed/stdlib/pydoc.pyi index 6e5d3e818f83..6ea4a74a9d28 100644 --- a/mypy/typeshed/stdlib/pydoc.pyi +++ b/mypy/typeshed/stdlib/pydoc.pyi @@ -1,3 +1,4 @@ +import sys from _typeshed import OptExcInfo, SupportsWrite from abc import abstractmethod from builtins import list as _list # "list" conflicts with method name @@ -78,21 +79,36 @@ class HTMLDoc(Doc): repr = _repr_instance.repr escape = _repr_instance.escape def page(self, title: str, contents: str) -> str: ... - def heading(self, title: str, fgcol: str, bgcol: str, extras: str = ...) -> str: ... - def section( - self, - title: str, - fgcol: str, - bgcol: str, - contents: str, - width: int = ..., - prelude: str = ..., - marginalia: str | None = ..., - gap: str = ..., - ) -> str: ... + if sys.version_info >= (3, 11): + def heading(self, title: str, extras: str = ...) -> str: ... + def section( + self, + title: str, + cls: str, + contents: str, + width: int = ..., + prelude: str = ..., + marginalia: str | None = ..., + gap: str = ..., + ) -> str: ... + def multicolumn(self, list: list[_T], format: Callable[[_T], str]) -> str: ... + else: + def heading(self, title: str, fgcol: str, bgcol: str, extras: str = ...) -> str: ... + def section( + self, + title: str, + fgcol: str, + bgcol: str, + contents: str, + width: int = ..., + prelude: str = ..., + marginalia: str | None = ..., + gap: str = ..., + ) -> str: ... + def multicolumn(self, list: list[_T], format: Callable[[_T], str], cols: int = ...) -> str: ... + def bigsection(self, title: str, *args: Any) -> str: ... def preformat(self, text: str) -> str: ... - def multicolumn(self, list: list[_T], format: Callable[[_T], str], cols: int = ...) -> str: ... def grey(self, text: str) -> str: ... def namelink(self, name: str, *dicts: MutableMapping[str, str]) -> str: ... def classlink(self, object: object, modname: str) -> str: ... diff --git a/mypy/typeshed/stdlib/pyexpat/__init__.pyi b/mypy/typeshed/stdlib/pyexpat/__init__.pyi index 2fe76a3d61b6..6a4ed891fe10 100644 --- a/mypy/typeshed/stdlib/pyexpat/__init__.pyi +++ b/mypy/typeshed/stdlib/pyexpat/__init__.pyi @@ -33,6 +33,8 @@ class XMLParserType: def ExternalEntityParserCreate(self, __context: str | None, __encoding: str = ...) -> XMLParserType: ... def SetParamEntityParsing(self, __flag: int) -> int: ... def UseForeignDTD(self, __flag: bool = ...) -> None: ... + @property + def intern(self) -> dict[str, str]: ... buffer_size: int buffer_text: bool buffer_used: int @@ -69,6 +71,7 @@ class XMLParserType: DefaultHandlerExpand: Callable[[str], Any] | None NotStandaloneHandler: Callable[[], int] | None ExternalEntityRefHandler: Callable[[str, str | None, str | None, str | None], int] | None + SkippedEntityHandler: Callable[[str, bool], Any] | None def ErrorString(__code: int) -> str: ... diff --git a/mypy/typeshed/stdlib/pyexpat/errors.pyi b/mypy/typeshed/stdlib/pyexpat/errors.pyi index 61826e12da00..2e512eb12989 100644 --- a/mypy/typeshed/stdlib/pyexpat/errors.pyi +++ b/mypy/typeshed/stdlib/pyexpat/errors.pyi @@ -1,3 +1,5 @@ +import sys + codes: dict[str, int] messages: dict[int, str] @@ -38,3 +40,10 @@ XML_ERROR_UNDEFINED_ENTITY: str XML_ERROR_UNEXPECTED_STATE: str XML_ERROR_UNKNOWN_ENCODING: str XML_ERROR_XML_DECL: str +if sys.version_info >= (3, 11): + XML_ERROR_RESERVED_PREFIX_XML: str + XML_ERROR_RESERVED_PREFIX_XMLNS: str + XML_ERROR_RESERVED_NAMESPACE_URI: str + XML_ERROR_INVALID_ARGUMENT: str + XML_ERROR_NO_BUFFER: str + XML_ERROR_AMPLIFICATION_LIMIT_BREACH: str diff --git a/mypy/typeshed/stdlib/random.pyi b/mypy/typeshed/stdlib/random.pyi index 255436dc377d..3bb999bfaaa6 100644 --- a/mypy/typeshed/stdlib/random.pyi +++ b/mypy/typeshed/stdlib/random.pyi @@ -5,61 +5,35 @@ from collections.abc import Callable, Iterable, MutableSequence, Sequence, Set a from fractions import Fraction from typing import Any, ClassVar, NoReturn, TypeVar +__all__ = [ + "Random", + "seed", + "random", + "uniform", + "randint", + "choice", + "sample", + "randrange", + "shuffle", + "normalvariate", + "lognormvariate", + "expovariate", + "vonmisesvariate", + "gammavariate", + "triangular", + "gauss", + "betavariate", + "paretovariate", + "weibullvariate", + "getstate", + "setstate", + "getrandbits", + "choices", + "SystemRandom", +] + if sys.version_info >= (3, 9): - __all__ = [ - "Random", - "SystemRandom", - "betavariate", - "choice", - "choices", - "expovariate", - "gammavariate", - "gauss", - "getrandbits", - "getstate", - "lognormvariate", - "normalvariate", - "paretovariate", - "randbytes", - "randint", - "random", - "randrange", - "sample", - "seed", - "setstate", - "shuffle", - "triangular", - "uniform", - "vonmisesvariate", - "weibullvariate", - ] -else: - __all__ = [ - "Random", - "seed", - "random", - "uniform", - "randint", - "choice", - "sample", - "randrange", - "shuffle", - "normalvariate", - "lognormvariate", - "expovariate", - "vonmisesvariate", - "gammavariate", - "triangular", - "gauss", - "betavariate", - "paretovariate", - "weibullvariate", - "getstate", - "setstate", - "getrandbits", - "choices", - "SystemRandom", - ] + __all__ += ["randbytes"] _T = TypeVar("_T") @@ -67,8 +41,10 @@ class Random(_random.Random): VERSION: ClassVar[int] def __init__(self, x: Any = ...) -> None: ... # Using other `seed` types is deprecated since 3.9 and removed in 3.11 + # Ignore Y041, since random.seed doesn't treat int like a float subtype. Having an explicit + # int better documents conventional usage of random.seed. if sys.version_info >= (3, 9): - def seed(self, a: int | float | str | bytes | bytearray | None = ..., version: int = ...) -> None: ... # type: ignore[override] + def seed(self, a: int | float | str | bytes | bytearray | None = ..., version: int = ...) -> None: ... # type: ignore[override] # noqa: Y041 else: def seed(self, a: Any = ..., version: int = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi index 2f4f3a3a0ed4..bdabf32d895e 100644 --- a/mypy/typeshed/stdlib/re.pyi +++ b/mypy/typeshed/stdlib/re.pyi @@ -13,102 +13,41 @@ if sys.version_info >= (3, 7): else: from typing import Match, Pattern +__all__ = [ + "match", + "fullmatch", + "search", + "sub", + "subn", + "split", + "findall", + "finditer", + "compile", + "purge", + "template", + "escape", + "error", + "A", + "I", + "L", + "M", + "S", + "X", + "U", + "ASCII", + "IGNORECASE", + "LOCALE", + "MULTILINE", + "DOTALL", + "VERBOSE", + "UNICODE", +] + +if sys.version_info >= (3, 7): + __all__ += ["Match", "Pattern"] + if sys.version_info >= (3, 11): - __all__ = [ - "match", - "fullmatch", - "search", - "sub", - "subn", - "split", - "findall", - "finditer", - "compile", - "purge", - "template", - "escape", - "error", - "Pattern", - "Match", - "A", - "I", - "L", - "M", - "S", - "X", - "U", - "ASCII", - "IGNORECASE", - "LOCALE", - "MULTILINE", - "DOTALL", - "VERBOSE", - "UNICODE", - "RegexFlag", - "NOFLAG", - ] -elif sys.version_info >= (3, 8): - __all__ = [ - "match", - "fullmatch", - "search", - "sub", - "subn", - "split", - "findall", - "finditer", - "compile", - "purge", - "template", - "escape", - "error", - "Pattern", - "Match", - "A", - "I", - "L", - "M", - "S", - "X", - "U", - "ASCII", - "IGNORECASE", - "LOCALE", - "MULTILINE", - "DOTALL", - "VERBOSE", - "UNICODE", - ] -else: - __all__ = [ - "match", - "fullmatch", - "search", - "sub", - "subn", - "split", - "findall", - "finditer", - "compile", - "purge", - "template", - "escape", - "error", - "A", - "I", - "L", - "M", - "S", - "X", - "U", - "ASCII", - "IGNORECASE", - "LOCALE", - "MULTILINE", - "DOTALL", - "VERBOSE", - "UNICODE", - ] + __all__ += ["NOFLAG", "RegexFlag"] class RegexFlag(enum.IntFlag): A = sre_compile.SRE_FLAG_ASCII diff --git a/mypy/typeshed/stdlib/shutil.pyi b/mypy/typeshed/stdlib/shutil.pyi index b367a46fe572..ae62ea4b658f 100644 --- a/mypy/typeshed/stdlib/shutil.pyi +++ b/mypy/typeshed/stdlib/shutil.pyi @@ -82,7 +82,17 @@ else: ignore_dangling_symlinks: bool = ..., ) -> _PathReturn: ... -def rmtree(path: StrOrBytesPath, ignore_errors: bool = ..., onerror: Callable[[Any, Any, Any], Any] | None = ...) -> None: ... +if sys.version_info >= (3, 11): + def rmtree( + path: StrOrBytesPath, + ignore_errors: bool = ..., + onerror: Callable[[Any, Any, Any], Any] | None = ..., + *, + dir_fd: int | None = ..., + ) -> None: ... + +else: + def rmtree(path: StrOrBytesPath, ignore_errors: bool = ..., onerror: Callable[[Any, Any, Any], Any] | None = ...) -> None: ... _CopyFn: TypeAlias = Callable[[str, str], None] | Callable[[StrPath, StrPath], None] diff --git a/mypy/typeshed/stdlib/smtplib.pyi b/mypy/typeshed/stdlib/smtplib.pyi index d90c744c504a..65a85627b642 100644 --- a/mypy/typeshed/stdlib/smtplib.pyi +++ b/mypy/typeshed/stdlib/smtplib.pyi @@ -8,39 +8,24 @@ from types import TracebackType from typing import Any, Pattern, Protocol, overload from typing_extensions import TypeAlias +__all__ = [ + "SMTPException", + "SMTPServerDisconnected", + "SMTPResponseException", + "SMTPSenderRefused", + "SMTPRecipientsRefused", + "SMTPDataError", + "SMTPConnectError", + "SMTPHeloError", + "SMTPAuthenticationError", + "quoteaddr", + "quotedata", + "SMTP", + "SMTP_SSL", +] + if sys.version_info >= (3, 7): - __all__ = [ - "SMTPException", - "SMTPNotSupportedError", - "SMTPServerDisconnected", - "SMTPResponseException", - "SMTPSenderRefused", - "SMTPRecipientsRefused", - "SMTPDataError", - "SMTPConnectError", - "SMTPHeloError", - "SMTPAuthenticationError", - "quoteaddr", - "quotedata", - "SMTP", - "SMTP_SSL", - ] -else: - __all__ = [ - "SMTPException", - "SMTPServerDisconnected", - "SMTPResponseException", - "SMTPSenderRefused", - "SMTPRecipientsRefused", - "SMTPDataError", - "SMTPConnectError", - "SMTPHeloError", - "SMTPAuthenticationError", - "quoteaddr", - "quotedata", - "SMTP", - "SMTP_SSL", - ] + __all__ += ["SMTPNotSupportedError"] _Reply: TypeAlias = tuple[int, bytes] _SendErrs: TypeAlias = dict[str, _Reply] diff --git a/mypy/typeshed/stdlib/socket.pyi b/mypy/typeshed/stdlib/socket.pyi index 4f8ec07ccc95..d84fd66b87cf 100644 --- a/mypy/typeshed/stdlib/socket.pyi +++ b/mypy/typeshed/stdlib/socket.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import ReadableBuffer, Self, WriteableBuffer from collections.abc import Iterable from enum import IntEnum, IntFlag -from io import RawIOBase -from typing import Any, BinaryIO, TextIO, overload +from io import BufferedReader, BufferedRWPair, BufferedWriter, IOBase, RawIOBase, TextIOWrapper +from typing import Any, Protocol, overload from typing_extensions import Literal # Ideally, we'd just do "from _socket import *". Unfortunately, socket @@ -538,6 +538,16 @@ AI_V4MAPPED_CFG: AddressInfo if sys.platform == "win32": errorTab: dict[int, str] # undocumented +class _SendableFile(Protocol): + def read(self, __size: int) -> bytes: ... + def seek(self, __offset: int) -> object: ... + + # optional fields: + # + # @property + # def mode(self) -> str: ... + # def fileno(self) -> int: ... + class socket(_socket.socket): def __init__( self, family: AddressFamily | int = ..., type: SocketKind | int = ..., proto: int = ..., fileno: int | None = ... @@ -549,26 +559,66 @@ class socket(_socket.socket): # Note that the makefile's documented windows-specific behavior is not represented # mode strings with duplicates are intentionally excluded @overload + def makefile( # type: ignore[misc] + self, + mode: Literal["b", "rb", "br", "wb", "bw", "rwb", "rbw", "wrb", "wbr", "brw", "bwr"], + buffering: Literal[0], + *, + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + ) -> SocketIO: ... + @overload def makefile( self, - mode: Literal["r", "w", "rw", "wr", ""] = ..., - buffering: int | None = ..., + mode: Literal["rwb", "rbw", "wrb", "wbr", "brw", "bwr"], + buffering: Literal[-1, 1] | None = ..., *, encoding: str | None = ..., errors: str | None = ..., newline: str | None = ..., - ) -> TextIO: ... + ) -> BufferedRWPair: ... + @overload + def makefile( + self, + mode: Literal["rb", "br"], + buffering: Literal[-1, 1] | None = ..., + *, + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + ) -> BufferedReader: ... + @overload + def makefile( + self, + mode: Literal["wb", "bw"], + buffering: Literal[-1, 1] | None = ..., + *, + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + ) -> BufferedWriter: ... @overload def makefile( self, mode: Literal["b", "rb", "br", "wb", "bw", "rwb", "rbw", "wrb", "wbr", "brw", "bwr"], + buffering: int, + *, + encoding: str | None = ..., + errors: str | None = ..., + newline: str | None = ..., + ) -> IOBase: ... + @overload + def makefile( + self, + mode: Literal["r", "w", "rw", "wr", ""] = ..., buffering: int | None = ..., *, encoding: str | None = ..., errors: str | None = ..., newline: str | None = ..., - ) -> BinaryIO: ... - def sendfile(self, file: BinaryIO, offset: int = ..., count: int | None = ...) -> int: ... + ) -> TextIOWrapper: ... + def sendfile(self, file: _SendableFile, offset: int = ..., count: int | None = ...) -> int: ... @property def family(self) -> AddressFamily: ... # type: ignore[override] @property diff --git a/mypy/typeshed/stdlib/socketserver.pyi b/mypy/typeshed/stdlib/socketserver.pyi index 20ff5daa718e..8e2a24e7edfd 100644 --- a/mypy/typeshed/stdlib/socketserver.pyi +++ b/mypy/typeshed/stdlib/socketserver.pyi @@ -6,36 +6,26 @@ from socket import socket as _socket from typing import Any, BinaryIO, ClassVar, Union from typing_extensions import TypeAlias -if sys.platform == "win32": - __all__ = [ - "BaseServer", - "TCPServer", - "UDPServer", - "ThreadingUDPServer", - "ThreadingTCPServer", - "BaseRequestHandler", - "StreamRequestHandler", - "DatagramRequestHandler", - "ThreadingMixIn", - ] -else: - __all__ = [ - "BaseServer", - "TCPServer", - "UDPServer", - "ThreadingUDPServer", - "ThreadingTCPServer", - "BaseRequestHandler", - "StreamRequestHandler", - "DatagramRequestHandler", - "ThreadingMixIn", - "ForkingUDPServer", - "ForkingTCPServer", +__all__ = [ + "BaseServer", + "TCPServer", + "UDPServer", + "ThreadingUDPServer", + "ThreadingTCPServer", + "BaseRequestHandler", + "StreamRequestHandler", + "DatagramRequestHandler", + "ThreadingMixIn", +] +if sys.platform != "win32": + __all__ += [ "ForkingMixIn", - "UnixStreamServer", - "UnixDatagramServer", - "ThreadingUnixStreamServer", + "ForkingTCPServer", + "ForkingUDPServer", "ThreadingUnixDatagramServer", + "ThreadingUnixStreamServer", + "UnixDatagramServer", + "UnixStreamServer", ] _RequestType: TypeAlias = Union[_socket, tuple[bytes, _socket]] @@ -91,6 +81,8 @@ class TCPServer(BaseServer): def get_request(self) -> tuple[_socket, Any]: ... class UDPServer(BaseServer): + if sys.version_info >= (3, 11): + allow_reuse_port: bool max_packet_size: ClassVar[int] def get_request(self) -> tuple[tuple[bytes, _socket], Any]: ... diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index dc00a3971b0f..6db4a9294755 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -4,11 +4,10 @@ from _typeshed import ReadableBuffer, Self, StrOrBytesPath, SupportsLenAndGetIte from collections.abc import Callable, Generator, Iterable, Iterator, Mapping from datetime import date, datetime, time from types import TracebackType -from typing import Any, Generic, Protocol, TypeVar, overload +from typing import Any, Protocol, TypeVar, overload from typing_extensions import Literal, SupportsIndex, TypeAlias, final _T = TypeVar("_T") -_T_co = TypeVar("_T_co", covariant=True) _CursorT = TypeVar("_CursorT", bound=Cursor) _SqliteData: TypeAlias = str | ReadableBuffer | int | float | None # Data that is passed through adapters can be of any type accepted by an adapter. @@ -379,7 +378,7 @@ class Cursor(Iterator[Any]): def description(self) -> tuple[tuple[str, None, None, None, None, None, None], ...] | Any: ... @property def lastrowid(self) -> int | None: ... - row_factory: Callable[[Cursor, Row[Any]], object] | None + row_factory: Callable[[Cursor, Row], object] | None @property def rowcount(self) -> int: ... def __init__(self, __cursor: Connection) -> None: ... @@ -420,15 +419,15 @@ class PrepareProtocol: class ProgrammingError(DatabaseError): ... -class Row(Generic[_T_co]): - def __init__(self, __cursor: Cursor, __data: tuple[_T_co, ...]) -> None: ... +class Row: + def __init__(self, __cursor: Cursor, __data: tuple[Any, ...]) -> None: ... def keys(self) -> list[str]: ... @overload - def __getitem__(self, __index: int | str) -> _T_co: ... + def __getitem__(self, __index: int | str) -> Any: ... @overload - def __getitem__(self, __index: slice) -> tuple[_T_co, ...]: ... + def __getitem__(self, __index: slice) -> tuple[Any, ...]: ... def __hash__(self) -> int: ... - def __iter__(self) -> Iterator[_T_co]: ... + def __iter__(self) -> Iterator[Any]: ... def __len__(self) -> int: ... # These return NotImplemented for anything that is not a Row. def __eq__(self, __other: object) -> bool: ... @@ -451,13 +450,14 @@ else: class Warning(Exception): ... if sys.version_info >= (3, 11): + @final class Blob: def close(self) -> None: ... def read(self, __length: int = ...) -> bytes: ... def write(self, __data: bytes) -> None: ... def tell(self) -> int: ... # whence must be one of os.SEEK_SET, os.SEEK_CUR, os.SEEK_END - def seek(self, __offset: int, __whence: int = ...) -> None: ... + def seek(self, __offset: int, __origin: int = ...) -> None: ... def __len__(self) -> int: ... def __enter__(self: Self) -> Self: ... def __exit__(self, __typ: object, __val: object, __tb: object) -> Literal[False]: ... diff --git a/mypy/typeshed/stdlib/sre_constants.pyi b/mypy/typeshed/stdlib/sre_constants.pyi index 00644994fe3e..20a8437ed007 100644 --- a/mypy/typeshed/stdlib/sre_constants.pyi +++ b/mypy/typeshed/stdlib/sre_constants.pyi @@ -55,7 +55,8 @@ ASSERT: _NamedIntConstant ASSERT_NOT: _NamedIntConstant AT: _NamedIntConstant BRANCH: _NamedIntConstant -CALL: _NamedIntConstant +if sys.version_info < (3, 11): + CALL: _NamedIntConstant CATEGORY: _NamedIntConstant CHARSET: _NamedIntConstant BIGCHARSET: _NamedIntConstant diff --git a/mypy/typeshed/stdlib/sre_parse.pyi b/mypy/typeshed/stdlib/sre_parse.pyi index 0958e73f5176..1e903028ba7e 100644 --- a/mypy/typeshed/stdlib/sre_parse.pyi +++ b/mypy/typeshed/stdlib/sre_parse.pyi @@ -19,7 +19,8 @@ if sys.version_info >= (3, 7): TYPE_FLAGS: int GLOBAL_FLAGS: int -class Verbose(Exception): ... +if sys.version_info < (3, 11): + class Verbose(Exception): ... class _State: flags: int @@ -64,7 +65,7 @@ class SubPattern: def __setitem__(self, index: int | slice, code: _CodeType) -> None: ... def insert(self, index: int, code: _CodeType) -> None: ... def append(self, code: _CodeType) -> None: ... - def getwidth(self) -> int: ... + def getwidth(self) -> tuple[int, int]: ... class Tokenizer: istext: bool @@ -87,6 +88,9 @@ class Tokenizer: def seek(self, index: int) -> None: ... def error(self, msg: str, offset: int = ...) -> _Error: ... + if sys.version_info >= (3, 11): + def checkgroupname(self, name: str, offset: int, nested: int) -> None: ... + def fix_flags(src: str | bytes, flags: int) -> int: ... _TemplateType: TypeAlias = tuple[list[tuple[int, int]], list[str | None]] diff --git a/mypy/typeshed/stdlib/ssl.pyi b/mypy/typeshed/stdlib/ssl.pyi index 8445435fa346..9f0420029258 100644 --- a/mypy/typeshed/stdlib/ssl.pyi +++ b/mypy/typeshed/stdlib/ssl.pyi @@ -412,7 +412,12 @@ class SSLContext: def load_verify_locations( self, cafile: StrOrBytesPath | None = ..., capath: StrOrBytesPath | None = ..., cadata: str | bytes | None = ... ) -> None: ... - def get_ca_certs(self, binary_form: bool = ...) -> list[_PeerCertRetDictType] | list[bytes]: ... + @overload + def get_ca_certs(self, binary_form: Literal[False] = ...) -> list[_PeerCertRetDictType]: ... + @overload + def get_ca_certs(self, binary_form: Literal[True]) -> list[bytes]: ... + @overload + def get_ca_certs(self, binary_form: bool = ...) -> Any: ... def get_ciphers(self) -> list[_Cipher]: ... def set_default_verify_paths(self) -> None: ... def set_ciphers(self, __cipherlist: str) -> None: ... diff --git a/mypy/typeshed/stdlib/statistics.pyi b/mypy/typeshed/stdlib/statistics.pyi index e6c3d8f35bc6..58e7fd909f1f 100644 --- a/mypy/typeshed/stdlib/statistics.pyi +++ b/mypy/typeshed/stdlib/statistics.pyi @@ -6,64 +6,26 @@ from fractions import Fraction from typing import Any, NamedTuple, SupportsFloat, TypeVar from typing_extensions import Literal, TypeAlias +__all__ = [ + "StatisticsError", + "pstdev", + "pvariance", + "stdev", + "variance", + "median", + "median_low", + "median_high", + "median_grouped", + "mean", + "mode", + "harmonic_mean", +] + +if sys.version_info >= (3, 8): + __all__ += ["geometric_mean", "multimode", "NormalDist", "fmean", "quantiles"] + if sys.version_info >= (3, 10): - __all__ = [ - "NormalDist", - "StatisticsError", - "correlation", - "covariance", - "fmean", - "geometric_mean", - "harmonic_mean", - "linear_regression", - "mean", - "median", - "median_grouped", - "median_high", - "median_low", - "mode", - "multimode", - "pstdev", - "pvariance", - "quantiles", - "stdev", - "variance", - ] -elif sys.version_info >= (3, 8): - __all__ = [ - "NormalDist", - "StatisticsError", - "fmean", - "geometric_mean", - "harmonic_mean", - "mean", - "median", - "median_grouped", - "median_high", - "median_low", - "mode", - "multimode", - "pstdev", - "pvariance", - "quantiles", - "stdev", - "variance", - ] -else: - __all__ = [ - "StatisticsError", - "pstdev", - "pvariance", - "stdev", - "variance", - "median", - "median_low", - "median_high", - "median_grouped", - "mean", - "mode", - "harmonic_mean", - ] + __all__ += ["covariance", "correlation", "linear_regression"] # Most functions in this module accept homogeneous collections of one of these types _Number: TypeAlias = float | Decimal | Fraction diff --git a/mypy/typeshed/stdlib/string.pyi b/mypy/typeshed/stdlib/string.pyi index 4404bde8bc4f..525806a74043 100644 --- a/mypy/typeshed/stdlib/string.pyi +++ b/mypy/typeshed/stdlib/string.pyi @@ -45,6 +45,9 @@ class Template: def __init__(self, template: str) -> None: ... def substitute(self, __mapping: Mapping[str, object] = ..., **kwds: object) -> str: ... def safe_substitute(self, __mapping: Mapping[str, object] = ..., **kwds: object) -> str: ... + if sys.version_info >= (3, 11): + def get_identifiers(self) -> list[str]: ... + def is_valid(self) -> bool: ... # TODO(MichalPokorny): This is probably badly and/or loosely typed. class Formatter: diff --git a/mypy/typeshed/stdlib/subprocess.pyi b/mypy/typeshed/stdlib/subprocess.pyi index 83178e15d9e8..6ce1073002b8 100644 --- a/mypy/typeshed/stdlib/subprocess.pyi +++ b/mypy/typeshed/stdlib/subprocess.pyi @@ -8,86 +8,49 @@ from typing_extensions import Literal, TypeAlias if sys.version_info >= (3, 9): from types import GenericAlias +__all__ = [ + "Popen", + "PIPE", + "STDOUT", + "call", + "check_call", + "getstatusoutput", + "getoutput", + "check_output", + "run", + "CalledProcessError", + "DEVNULL", + "SubprocessError", + "TimeoutExpired", + "CompletedProcess", +] + if sys.platform == "win32": + __all__ += [ + "CREATE_NEW_CONSOLE", + "CREATE_NEW_PROCESS_GROUP", + "STARTF_USESHOWWINDOW", + "STARTF_USESTDHANDLES", + "STARTUPINFO", + "STD_ERROR_HANDLE", + "STD_INPUT_HANDLE", + "STD_OUTPUT_HANDLE", + "SW_HIDE", + ] + if sys.version_info >= (3, 7): - __all__ = [ - "Popen", - "PIPE", - "STDOUT", - "call", - "check_call", - "getstatusoutput", - "getoutput", - "check_output", - "run", - "CalledProcessError", - "DEVNULL", - "SubprocessError", - "TimeoutExpired", - "CompletedProcess", - "CREATE_NEW_CONSOLE", - "CREATE_NEW_PROCESS_GROUP", - "STD_INPUT_HANDLE", - "STD_OUTPUT_HANDLE", - "STD_ERROR_HANDLE", - "SW_HIDE", - "STARTF_USESTDHANDLES", - "STARTF_USESHOWWINDOW", - "STARTUPINFO", + __all__ += [ "ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS", + "CREATE_BREAKAWAY_FROM_JOB", + "CREATE_DEFAULT_ERROR_MODE", + "CREATE_NO_WINDOW", + "DETACHED_PROCESS", "HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS", "NORMAL_PRIORITY_CLASS", "REALTIME_PRIORITY_CLASS", - "CREATE_NO_WINDOW", - "DETACHED_PROCESS", - "CREATE_DEFAULT_ERROR_MODE", - "CREATE_BREAKAWAY_FROM_JOB", - ] - else: - __all__ = [ - "Popen", - "PIPE", - "STDOUT", - "call", - "check_call", - "getstatusoutput", - "getoutput", - "check_output", - "run", - "CalledProcessError", - "DEVNULL", - "SubprocessError", - "TimeoutExpired", - "CompletedProcess", - "CREATE_NEW_CONSOLE", - "CREATE_NEW_PROCESS_GROUP", - "STD_INPUT_HANDLE", - "STD_OUTPUT_HANDLE", - "STD_ERROR_HANDLE", - "SW_HIDE", - "STARTF_USESTDHANDLES", - "STARTF_USESHOWWINDOW", - "STARTUPINFO", ] -else: - __all__ = [ - "Popen", - "PIPE", - "STDOUT", - "call", - "check_call", - "getstatusoutput", - "getoutput", - "check_output", - "run", - "CalledProcessError", - "DEVNULL", - "SubprocessError", - "TimeoutExpired", - "CompletedProcess", - ] # We prefer to annotate inputs to methods (eg subprocess.check_call) with these # union types. @@ -444,49 +407,99 @@ else: ) -> CompletedProcess[Any]: ... # Same args as Popen.__init__ -def call( - args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath | None = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - *, - timeout: float | None = ..., -) -> int: ... +if sys.version_info >= (3, 7): + def call( + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: float | None = ..., + text: bool | None = ..., + ) -> int: ... + +else: + def call( + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath | None = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + *, + timeout: float | None = ..., + ) -> int: ... # Same args as Popen.__init__ -def check_call( - args: _CMD, - bufsize: int = ..., - executable: StrOrBytesPath = ..., - stdin: _FILE = ..., - stdout: _FILE = ..., - stderr: _FILE = ..., - preexec_fn: Callable[[], Any] | None = ..., - close_fds: bool = ..., - shell: bool = ..., - cwd: StrOrBytesPath | None = ..., - env: _ENV | None = ..., - universal_newlines: bool = ..., - startupinfo: Any = ..., - creationflags: int = ..., - restore_signals: bool = ..., - start_new_session: bool = ..., - pass_fds: Any = ..., - timeout: float | None = ..., -) -> int: ... +if sys.version_info >= (3, 7): + def check_call( + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + timeout: float | None = ..., + *, + text: bool | None = ..., + ) -> int: ... + +else: + def check_call( + args: _CMD, + bufsize: int = ..., + executable: StrOrBytesPath = ..., + stdin: _FILE = ..., + stdout: _FILE = ..., + stderr: _FILE = ..., + preexec_fn: Callable[[], Any] | None = ..., + close_fds: bool = ..., + shell: bool = ..., + cwd: StrOrBytesPath | None = ..., + env: _ENV | None = ..., + universal_newlines: bool = ..., + startupinfo: Any = ..., + creationflags: int = ..., + restore_signals: bool = ..., + start_new_session: bool = ..., + pass_fds: Any = ..., + timeout: float | None = ..., + ) -> int: ... if sys.version_info >= (3, 7): # 3.7 added text @@ -1652,8 +1665,13 @@ class Popen(Generic[AnyStr]): def __class_getitem__(cls, item: Any) -> GenericAlias: ... # The result really is always a str. -def getstatusoutput(cmd: _TXT) -> tuple[int, str]: ... -def getoutput(cmd: _TXT) -> str: ... +if sys.version_info >= (3, 11): + def getstatusoutput(cmd: _TXT, *, encoding: str | None = ..., errors: str | None = ...) -> tuple[int, str]: ... + def getoutput(cmd: _TXT, *, encoding: str | None = ..., errors: str | None = ...) -> str: ... + +else: + def getstatusoutput(cmd: _TXT) -> tuple[int, str]: ... + def getoutput(cmd: _TXT) -> str: ... if sys.version_info >= (3, 8): def list2cmdline(seq: Iterable[StrOrBytesPath]) -> str: ... # undocumented diff --git a/mypy/typeshed/stdlib/symtable.pyi b/mypy/typeshed/stdlib/symtable.pyi index 7a95fe5e445f..d44b2d7927b3 100644 --- a/mypy/typeshed/stdlib/symtable.pyi +++ b/mypy/typeshed/stdlib/symtable.pyi @@ -1,4 +1,5 @@ import sys +from _collections_abc import dict_keys from collections.abc import Sequence from typing import Any @@ -15,8 +16,10 @@ class SymbolTable: def is_optimized(self) -> bool: ... def is_nested(self) -> bool: ... def has_children(self) -> bool: ... - def has_exec(self) -> bool: ... - def get_identifiers(self) -> Sequence[str]: ... + if sys.version_info < (3, 9): + def has_exec(self) -> bool: ... + + def get_identifiers(self) -> dict_keys[str, int]: ... def lookup(self, name: str) -> Symbol: ... def get_symbols(self) -> list[Symbol]: ... def get_children(self) -> list[SymbolTable]: ... diff --git a/mypy/typeshed/stdlib/sys.pyi b/mypy/typeshed/stdlib/sys.pyi index 4e24cbd167d9..667b7024fe12 100644 --- a/mypy/typeshed/stdlib/sys.pyi +++ b/mypy/typeshed/stdlib/sys.pyi @@ -221,6 +221,9 @@ def __displayhook__(__value: object) -> None: ... def __excepthook__(__exctype: type[BaseException], __value: BaseException, __traceback: TracebackType | None) -> None: ... def exc_info() -> OptExcInfo: ... +if sys.version_info >= (3, 11): + def exception() -> BaseException | None: ... + # sys.exit() accepts an optional argument of anything printable def exit(__status: object = ...) -> NoReturn: ... def getallocatedblocks() -> int: ... diff --git a/mypy/typeshed/stdlib/tarfile.pyi b/mypy/typeshed/stdlib/tarfile.pyi index 364bcad0683f..87c57311aa99 100644 --- a/mypy/typeshed/stdlib/tarfile.pyi +++ b/mypy/typeshed/stdlib/tarfile.pyi @@ -315,7 +315,9 @@ class TarFile: ) -> None: ... def addfile(self, tarinfo: TarInfo, fileobj: IO[bytes] | None = ...) -> None: ... - def gettarinfo(self, name: str | None = ..., arcname: str | None = ..., fileobj: IO[bytes] | None = ...) -> TarInfo: ... + def gettarinfo( + self, name: StrOrBytesPath | None = ..., arcname: str | None = ..., fileobj: IO[bytes] | None = ... + ) -> TarInfo: ... def close(self) -> None: ... if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stdlib/tempfile.pyi b/mypy/typeshed/stdlib/tempfile.pyi index 4f2b4a545ff7..2c096f0fb4de 100644 --- a/mypy/typeshed/stdlib/tempfile.pyi +++ b/mypy/typeshed/stdlib/tempfile.pyi @@ -1,6 +1,6 @@ -import os +import io import sys -from _typeshed import Self +from _typeshed import BytesPath, GenericPath, Self, StrPath, WriteableBuffer from collections.abc import Iterable, Iterator from types import TracebackType from typing import IO, Any, AnyStr, Generic, overload @@ -30,31 +30,32 @@ TMP_MAX: int tempdir: str | None template: str -_DirT: TypeAlias = AnyStr | os.PathLike[AnyStr] +_StrMode: TypeAlias = Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"] +_BytesMode: TypeAlias = Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] if sys.version_info >= (3, 8): @overload def NamedTemporaryFile( - mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"], + mode: _StrMode, buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., + dir: GenericPath[AnyStr] | None = ..., delete: bool = ..., *, errors: str | None = ..., ) -> _TemporaryFileWrapper[str]: ... @overload def NamedTemporaryFile( - mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., + mode: _BytesMode = ..., buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., + dir: GenericPath[AnyStr] | None = ..., delete: bool = ..., *, errors: str | None = ..., @@ -67,7 +68,7 @@ if sys.version_info >= (3, 8): newline: str | None = ..., suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., + dir: GenericPath[AnyStr] | None = ..., delete: bool = ..., *, errors: str | None = ..., @@ -76,24 +77,24 @@ if sys.version_info >= (3, 8): else: @overload def NamedTemporaryFile( - mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"], + mode: _StrMode, buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., + dir: GenericPath[AnyStr] | None = ..., delete: bool = ..., ) -> _TemporaryFileWrapper[str]: ... @overload def NamedTemporaryFile( - mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., + mode: _BytesMode = ..., buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., + dir: GenericPath[AnyStr] | None = ..., delete: bool = ..., ) -> _TemporaryFileWrapper[bytes]: ... @overload @@ -104,7 +105,7 @@ else: newline: str | None = ..., suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., + dir: GenericPath[AnyStr] | None = ..., delete: bool = ..., ) -> _TemporaryFileWrapper[Any]: ... @@ -114,25 +115,25 @@ else: if sys.version_info >= (3, 8): @overload def TemporaryFile( - mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"], + mode: _StrMode, buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., + dir: GenericPath[AnyStr] | None = ..., *, errors: str | None = ..., ) -> IO[str]: ... @overload def TemporaryFile( - mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., + mode: _BytesMode = ..., buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., + dir: GenericPath[AnyStr] | None = ..., *, errors: str | None = ..., ) -> IO[bytes]: ... @@ -144,30 +145,30 @@ else: newline: str | None = ..., suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., + dir: GenericPath[AnyStr] | None = ..., *, errors: str | None = ..., ) -> IO[Any]: ... else: @overload def TemporaryFile( - mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"], + mode: _StrMode, buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., + dir: GenericPath[AnyStr] | None = ..., ) -> IO[str]: ... @overload def TemporaryFile( - mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., + mode: _BytesMode = ..., buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., + dir: GenericPath[AnyStr] | None = ..., ) -> IO[bytes]: ... @overload def TemporaryFile( @@ -177,7 +178,7 @@ else: newline: str | None = ..., suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., + dir: GenericPath[AnyStr] | None = ..., ) -> IO[Any]: ... class _TemporaryFileWrapper(Generic[AnyStr], IO[AnyStr]): @@ -217,9 +218,14 @@ class _TemporaryFileWrapper(Generic[AnyStr], IO[AnyStr]): def write(self, s: AnyStr) -> int: ... def writelines(self, lines: Iterable[AnyStr]) -> None: ... -# It does not actually derive from IO[AnyStr], but it does implement the -# protocol. -class SpooledTemporaryFile(IO[AnyStr]): +if sys.version_info >= (3, 11): + _SpooledTemporaryFileBase = io.IOBase +else: + _SpooledTemporaryFileBase = object + +# It does not actually derive from IO[AnyStr], but it does mostly behave +# like one. +class SpooledTemporaryFile(IO[AnyStr], _SpooledTemporaryFileBase): @property def encoding(self) -> str: ... # undocumented @property @@ -230,7 +236,7 @@ class SpooledTemporaryFile(IO[AnyStr]): def __init__( self: SpooledTemporaryFile[bytes], max_size: int = ..., - mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., + mode: _BytesMode = ..., buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., @@ -244,7 +250,7 @@ class SpooledTemporaryFile(IO[AnyStr]): def __init__( self: SpooledTemporaryFile[str], max_size: int = ..., - mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"] = ..., + mode: _StrMode = ..., buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., @@ -275,7 +281,7 @@ class SpooledTemporaryFile(IO[AnyStr]): def __init__( self: SpooledTemporaryFile[bytes], max_size: int = ..., - mode: Literal["rb", "wb", "ab", "xb", "r+b", "w+b", "a+b", "x+b"] = ..., + mode: _BytesMode = ..., buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., @@ -287,7 +293,7 @@ class SpooledTemporaryFile(IO[AnyStr]): def __init__( self: SpooledTemporaryFile[str], max_size: int = ..., - mode: Literal["r", "w", "a", "x", "r+", "w+", "a+", "x+", "rt", "wt", "at", "xt", "r+t", "w+t", "a+t", "x+t"] = ..., + mode: _StrMode = ..., buffering: int = ..., encoding: str | None = ..., newline: str | None = ..., @@ -318,20 +324,28 @@ class SpooledTemporaryFile(IO[AnyStr]): def fileno(self) -> int: ... def flush(self) -> None: ... def isatty(self) -> bool: ... - def read(self, n: int = ...) -> AnyStr: ... - def readline(self, limit: int = ...) -> AnyStr: ... - def readlines(self, hint: int = ...) -> list[AnyStr]: ... + if sys.version_info >= (3, 11): + # These three work only if the SpooledTemporaryFile is opened in binary mode, + # because the underlying object in text mode does not have these methods. + def read1(self, __size: int = ...) -> AnyStr: ... + def readinto(self, b: WriteableBuffer) -> int: ... + def readinto1(self, b: WriteableBuffer) -> int: ... + def detach(self) -> io.RawIOBase: ... + + def read(self, __n: int = ...) -> AnyStr: ... + def readline(self, __limit: int | None = ...) -> AnyStr: ... # type: ignore[override] + def readlines(self, __hint: int = ...) -> list[AnyStr]: ... # type: ignore[override] def seek(self, offset: int, whence: int = ...) -> int: ... def tell(self) -> int: ... def truncate(self, size: int | None = ...) -> None: ... # type: ignore[override] def write(self, s: AnyStr) -> int: ... - def writelines(self, iterable: Iterable[AnyStr]) -> None: ... - def __iter__(self) -> Iterator[AnyStr]: ... - # Other than the following methods, which do not exist on SpooledTemporaryFile + def writelines(self, iterable: Iterable[AnyStr]) -> None: ... # type: ignore[override] + def __iter__(self) -> Iterator[AnyStr]: ... # type: ignore[override] + # These exist at runtime only on 3.11+. def readable(self) -> bool: ... def seekable(self) -> bool: ... def writable(self) -> bool: ... - def __next__(self) -> AnyStr: ... + def __next__(self) -> AnyStr: ... # type: ignore[override] if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... @@ -341,24 +355,28 @@ class TemporaryDirectory(Generic[AnyStr]): @overload def __init__( self: TemporaryDirectory[str], - suffix: None = ..., - prefix: None = ..., - dir: None = ..., + suffix: str | None = ..., + prefix: str | None = ..., + dir: StrPath | None = ..., ignore_cleanup_errors: bool = ..., ) -> None: ... @overload def __init__( - self, - suffix: AnyStr | None = ..., - prefix: AnyStr | None = ..., - dir: _DirT[AnyStr] | None = ..., + self: TemporaryDirectory[bytes], + suffix: bytes | None = ..., + prefix: bytes | None = ..., + dir: BytesPath | None = ..., ignore_cleanup_errors: bool = ..., ) -> None: ... else: @overload - def __init__(self: TemporaryDirectory[str], suffix: None = ..., prefix: None = ..., dir: None = ...) -> None: ... + def __init__( + self: TemporaryDirectory[str], suffix: str | None = ..., prefix: str | None = ..., dir: StrPath | None = ... + ) -> None: ... @overload - def __init__(self, suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., dir: _DirT[AnyStr] | None = ...) -> None: ... + def __init__( + self: TemporaryDirectory[bytes], suffix: bytes | None = ..., prefix: bytes | None = ..., dir: BytesPath | None = ... + ) -> None: ... def cleanup(self) -> None: ... def __enter__(self) -> AnyStr: ... @@ -366,20 +384,22 @@ class TemporaryDirectory(Generic[AnyStr]): if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... +# The overloads overlap, but they should still work fine. @overload -def mkstemp() -> tuple[int, str]: ... +def mkstemp( # type: ignore[misc] + suffix: str | None = ..., prefix: str | None = ..., dir: StrPath | None = ..., text: bool = ... +) -> tuple[int, str]: ... @overload def mkstemp( - suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., dir: _DirT[AnyStr] | None = ..., text: bool = ... -) -> tuple[int, AnyStr]: ... -@overload -def mkdtemp() -> str: ... -@overload -def mkdtemp(suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., dir: _DirT[AnyStr] | None = ...) -> AnyStr: ... + suffix: bytes | None = ..., prefix: bytes | None = ..., dir: BytesPath | None = ..., text: bool = ... +) -> tuple[int, bytes]: ... + +# The overloads overlap, but they should still work fine. @overload -def mktemp() -> str: ... +def mkdtemp(suffix: str | None = ..., prefix: str | None = ..., dir: StrPath | None = ...) -> str: ... # type: ignore[misc] @overload -def mktemp(suffix: AnyStr | None = ..., prefix: AnyStr | None = ..., dir: _DirT[AnyStr] | None = ...) -> AnyStr: ... +def mkdtemp(suffix: bytes | None = ..., prefix: bytes | None = ..., dir: BytesPath | None = ...) -> bytes: ... +def mktemp(suffix: str = ..., prefix: str = ..., dir: StrPath | None = ...) -> str: ... def gettempdirb() -> bytes: ... def gettempprefixb() -> bytes: ... def gettempdir() -> str: ... diff --git a/mypy/typeshed/stdlib/termios.pyi b/mypy/typeshed/stdlib/termios.pyi index b2423304b930..494162a49b38 100644 --- a/mypy/typeshed/stdlib/termios.pyi +++ b/mypy/typeshed/stdlib/termios.pyi @@ -244,5 +244,8 @@ if sys.platform != "win32": def tcdrain(__fd: FileDescriptorLike) -> None: ... def tcflush(__fd: FileDescriptorLike, __queue: int) -> None: ... def tcflow(__fd: FileDescriptorLike, __action: int) -> None: ... + if sys.version_info >= (3, 11): + def tcgetwinsize(__fd: FileDescriptorLike) -> tuple[int, int]: ... + def tcsetwinsize(__fd: FileDescriptorLike, __winsize: tuple[int, int]) -> None: ... class error(Exception): ... diff --git a/mypy/typeshed/stdlib/threading.pyi b/mypy/typeshed/stdlib/threading.pyi index 231018ca731a..afc37b771e8c 100644 --- a/mypy/typeshed/stdlib/threading.pyi +++ b/mypy/typeshed/stdlib/threading.pyi @@ -10,86 +10,35 @@ _TF: TypeAlias = Callable[[FrameType, str, Any], Callable[..., Any] | None] _PF: TypeAlias = Callable[[FrameType, str, Any], None] _T = TypeVar("_T") +__all__ = [ + "get_ident", + "active_count", + "Condition", + "current_thread", + "enumerate", + "main_thread", + "TIMEOUT_MAX", + "Event", + "Lock", + "RLock", + "Semaphore", + "BoundedSemaphore", + "Thread", + "Barrier", + "BrokenBarrierError", + "Timer", + "ThreadError", + "setprofile", + "settrace", + "local", + "stack_size", +] + +if sys.version_info >= (3, 8): + __all__ += ["ExceptHookArgs", "excepthook", "get_native_id"] + if sys.version_info >= (3, 10): - __all__ = [ - "get_ident", - "active_count", - "Condition", - "current_thread", - "enumerate", - "main_thread", - "TIMEOUT_MAX", - "Event", - "Lock", - "RLock", - "Semaphore", - "BoundedSemaphore", - "Thread", - "Barrier", - "BrokenBarrierError", - "Timer", - "ThreadError", - "setprofile", - "settrace", - "local", - "stack_size", - "excepthook", - "ExceptHookArgs", - "gettrace", - "getprofile", - "get_native_id", - ] -elif sys.version_info >= (3, 8): - __all__ = [ - "get_ident", - "active_count", - "Condition", - "current_thread", - "enumerate", - "main_thread", - "TIMEOUT_MAX", - "Event", - "Lock", - "RLock", - "Semaphore", - "BoundedSemaphore", - "Thread", - "Barrier", - "BrokenBarrierError", - "Timer", - "ThreadError", - "setprofile", - "settrace", - "local", - "stack_size", - "excepthook", - "ExceptHookArgs", - "get_native_id", - ] -else: - __all__ = [ - "get_ident", - "active_count", - "Condition", - "current_thread", - "enumerate", - "main_thread", - "TIMEOUT_MAX", - "Event", - "Lock", - "RLock", - "Semaphore", - "BoundedSemaphore", - "Thread", - "Barrier", - "BrokenBarrierError", - "Timer", - "ThreadError", - "setprofile", - "settrace", - "local", - "stack_size", - ] + __all__ += ["getprofile", "gettrace"] _profile_hook: _PF | None @@ -190,6 +139,7 @@ class Condition: def notifyAll(self) -> None: ... # deprecated alias for notify_all() class Semaphore: + _value: int def __init__(self, value: int = ...) -> None: ... def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ... def acquire(self, blocking: bool = ..., timeout: float | None = ...) -> bool: ... @@ -216,6 +166,12 @@ if sys.version_info >= (3, 8): ExceptHookArgs = _ExceptHookArgs class Timer(Thread): + args: Iterable[Any] # undocumented + finished: Event # undocumented + function: Callable[..., Any] # undocumented + interval: float # undocumented + kwargs: Mapping[str, Any] # undocumented + def __init__( self, interval: float, diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 582503971e15..0955992d2688 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -2197,31 +2197,29 @@ class Listbox(Widget, XView, YView): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure - def activate(self, index) -> None: ... - def bbox(self, index) -> tuple[int, int, int, int] | None: ... # type: ignore[override] + def activate(self, index: str | int) -> None: ... + def bbox(self, index: str | int) -> tuple[int, int, int, int] | None: ... # type: ignore[override] def curselection(self): ... - def delete(self, first, last: Any | None = ...) -> None: ... - def get(self, first, last: Any | None = ...): ... - def index(self, index): ... - def insert(self, index, *elements) -> None: ... + def delete(self, first: str | int, last: str | int | None = ...) -> None: ... + def get(self, first: str | int, last: str | int | None = ...): ... + def index(self, index: str | int) -> int: ... + def insert(self, index: str | int, *elements: str | float) -> None: ... def nearest(self, y): ... def scan_mark(self, x, y) -> None: ... def scan_dragto(self, x, y) -> None: ... - def see(self, index) -> None: ... - def selection_anchor(self, index) -> None: ... - select_anchor: Any - def selection_clear(self, first, last: Any | None = ...) -> None: ... # type: ignore[override] - select_clear: Any - def selection_includes(self, index): ... - select_includes: Any - def selection_set(self, first, last: Any | None = ...) -> None: ... - select_set: Any + def see(self, index: str | int) -> None: ... + def selection_anchor(self, index: str | int) -> None: ... + select_anchor = selection_anchor + def selection_clear(self, first: str | int, last: str | int | None = ...) -> None: ... # type: ignore[override] + select_clear = selection_clear + def selection_includes(self, index: str | int): ... + select_includes = selection_includes + def selection_set(self, first: str | int, last: str | int | None = ...) -> None: ... + select_set = selection_set def size(self) -> int: ... # type: ignore[override] - def itemcget(self, index, option): ... - def itemconfigure(self, index, cnf: Any | None = ..., **kw): ... - itemconfig: Any - -_MenuIndex: TypeAlias = str | int + def itemcget(self, index: str | int, option): ... + def itemconfigure(self, index: str | int, cnf: Any | None = ..., **kw): ... + itemconfig = itemconfigure class Menu(Widget): def __init__( @@ -2285,8 +2283,8 @@ class Menu(Widget): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure - def tk_popup(self, x: int, y: int, entry: _MenuIndex = ...) -> None: ... - def activate(self, index: _MenuIndex) -> None: ... + def tk_popup(self, x: int, y: int, entry: str | int = ...) -> None: ... + def activate(self, index: str | int) -> None: ... def add(self, itemType, cnf=..., **kw): ... # docstring says "Internal function." def insert(self, index, itemType, cnf=..., **kw): ... # docstring says "Internal function." def add_cascade( @@ -2384,7 +2382,7 @@ class Menu(Widget): def add_separator(self, cnf: dict[str, Any] | None = ..., *, background: _Color = ...) -> None: ... def insert_cascade( self, - index: _MenuIndex, + index: str | int, cnf: dict[str, Any] | None = ..., *, accelerator: str = ..., @@ -2406,7 +2404,7 @@ class Menu(Widget): ) -> None: ... def insert_checkbutton( self, - index: _MenuIndex, + index: str | int, cnf: dict[str, Any] | None = ..., *, accelerator: str = ..., @@ -2433,7 +2431,7 @@ class Menu(Widget): ) -> None: ... def insert_command( self, - index: _MenuIndex, + index: str | int, cnf: dict[str, Any] | None = ..., *, accelerator: str = ..., @@ -2454,7 +2452,7 @@ class Menu(Widget): ) -> None: ... def insert_radiobutton( self, - index: _MenuIndex, + index: str | int, cnf: dict[str, Any] | None = ..., *, accelerator: str = ..., @@ -2478,20 +2476,20 @@ class Menu(Widget): value: Any = ..., variable: Variable = ..., ) -> None: ... - def insert_separator(self, index: _MenuIndex, cnf: dict[str, Any] | None = ..., *, background: _Color = ...) -> None: ... - def delete(self, index1: _MenuIndex, index2: _MenuIndex | None = ...) -> None: ... - def entrycget(self, index: _MenuIndex, option: str) -> Any: ... + def insert_separator(self, index: str | int, cnf: dict[str, Any] | None = ..., *, background: _Color = ...) -> None: ... + def delete(self, index1: str | int, index2: str | int | None = ...) -> None: ... + def entrycget(self, index: str | int, option: str) -> Any: ... def entryconfigure( - self, index: _MenuIndex, cnf: dict[str, Any] | None = ..., **kw: Any + self, index: str | int, cnf: dict[str, Any] | None = ..., **kw: Any ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... entryconfig = entryconfigure - def index(self, index: _MenuIndex) -> int | None: ... - def invoke(self, index: _MenuIndex) -> Any: ... + def index(self, index: str | int) -> int | None: ... + def invoke(self, index: str | int) -> Any: ... def post(self, x: int, y: int) -> None: ... - def type(self, index: _MenuIndex) -> Literal["cascade", "checkbutton", "command", "radiobutton", "separator"]: ... + def type(self, index: str | int) -> Literal["cascade", "checkbutton", "command", "radiobutton", "separator"]: ... def unpost(self) -> None: ... - def xposition(self, index: _MenuIndex) -> int: ... - def yposition(self, index: _MenuIndex) -> int: ... + def xposition(self, index: str | int) -> int: ... + def yposition(self, index: str | int) -> int: ... class Menubutton(Widget): def __init__( @@ -3578,3 +3576,5 @@ class PanedWindow(Widget): def paneconfigure(self, tagOrId, cnf: Any | None = ..., **kw): ... paneconfig: Any def panes(self): ... + +def _test() -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index 7ca8f9b800ce..0fe94ad30ff5 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -6,61 +6,35 @@ from tkinter.font import _FontDescription from typing import Any, overload from typing_extensions import Literal, TypeAlias, TypedDict +__all__ = [ + "Button", + "Checkbutton", + "Combobox", + "Entry", + "Frame", + "Label", + "Labelframe", + "LabelFrame", + "Menubutton", + "Notebook", + "Panedwindow", + "PanedWindow", + "Progressbar", + "Radiobutton", + "Scale", + "Scrollbar", + "Separator", + "Sizegrip", + "Style", + "Treeview", + "LabeledScale", + "OptionMenu", + "tclobjs_to_py", + "setup_master", +] + if sys.version_info >= (3, 7): - __all__ = [ - "Button", - "Checkbutton", - "Combobox", - "Entry", - "Frame", - "Label", - "Labelframe", - "LabelFrame", - "Menubutton", - "Notebook", - "Panedwindow", - "PanedWindow", - "Progressbar", - "Radiobutton", - "Scale", - "Scrollbar", - "Separator", - "Sizegrip", - "Spinbox", - "Style", - "Treeview", - "LabeledScale", - "OptionMenu", - "tclobjs_to_py", - "setup_master", - ] -else: - __all__ = [ - "Button", - "Checkbutton", - "Combobox", - "Entry", - "Frame", - "Label", - "Labelframe", - "LabelFrame", - "Menubutton", - "Notebook", - "Panedwindow", - "PanedWindow", - "Progressbar", - "Radiobutton", - "Scale", - "Scrollbar", - "Separator", - "Sizegrip", - "Style", - "Treeview", - "LabeledScale", - "OptionMenu", - "tclobjs_to_py", - "setup_master", - ] + __all__ += ["Spinbox"] def tclobjs_to_py(adict: dict[Any, Any]) -> dict[Any, Any]: ... def setup_master(master: Any | None = ...): ... diff --git a/mypy/typeshed/stdlib/token.pyi b/mypy/typeshed/stdlib/token.pyi index 49329ec442f0..5fe9db7e230d 100644 --- a/mypy/typeshed/stdlib/token.pyi +++ b/mypy/typeshed/stdlib/token.pyi @@ -1,283 +1,80 @@ import sys +__all__ = [ + "AMPER", + "AMPEREQUAL", + "AT", + "ATEQUAL", + "CIRCUMFLEX", + "CIRCUMFLEXEQUAL", + "COLON", + "COMMA", + "DEDENT", + "DOT", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "DOUBLESTAR", + "DOUBLESTAREQUAL", + "ELLIPSIS", + "ENDMARKER", + "EQEQUAL", + "EQUAL", + "ERRORTOKEN", + "GREATER", + "GREATEREQUAL", + "INDENT", + "ISEOF", + "ISNONTERMINAL", + "ISTERMINAL", + "LBRACE", + "LEFTSHIFT", + "LEFTSHIFTEQUAL", + "LESS", + "LESSEQUAL", + "LPAR", + "LSQB", + "MINEQUAL", + "MINUS", + "NAME", + "NEWLINE", + "NOTEQUAL", + "NT_OFFSET", + "NUMBER", + "N_TOKENS", + "OP", + "PERCENT", + "PERCENTEQUAL", + "PLUS", + "PLUSEQUAL", + "RARROW", + "RBRACE", + "RIGHTSHIFT", + "RIGHTSHIFTEQUAL", + "RPAR", + "RSQB", + "SEMI", + "SLASH", + "SLASHEQUAL", + "STAR", + "STAREQUAL", + "STRING", + "TILDE", + "VBAR", + "VBAREQUAL", + "tok_name", +] + +if sys.version_info < (3, 7) or sys.version_info >= (3, 8): + __all__ += ["ASYNC", "AWAIT"] + +if sys.version_info >= (3, 7): + __all__ += ["ENCODING", "NL", "COMMENT"] + +if sys.version_info >= (3, 8): + __all__ += ["COLONEQUAL", "TYPE_COMMENT", "TYPE_IGNORE"] + if sys.version_info >= (3, 10): - __all__ = [ - "tok_name", - "ISTERMINAL", - "ISNONTERMINAL", - "ISEOF", - "ENDMARKER", - "NAME", - "NUMBER", - "STRING", - "NEWLINE", - "INDENT", - "DEDENT", - "LPAR", - "RPAR", - "LSQB", - "RSQB", - "COLON", - "COMMA", - "SEMI", - "PLUS", - "MINUS", - "STAR", - "SLASH", - "VBAR", - "AMPER", - "LESS", - "GREATER", - "EQUAL", - "DOT", - "PERCENT", - "LBRACE", - "RBRACE", - "EQEQUAL", - "NOTEQUAL", - "LESSEQUAL", - "GREATEREQUAL", - "TILDE", - "CIRCUMFLEX", - "LEFTSHIFT", - "RIGHTSHIFT", - "DOUBLESTAR", - "PLUSEQUAL", - "MINEQUAL", - "STAREQUAL", - "SLASHEQUAL", - "PERCENTEQUAL", - "AMPEREQUAL", - "VBAREQUAL", - "CIRCUMFLEXEQUAL", - "LEFTSHIFTEQUAL", - "RIGHTSHIFTEQUAL", - "DOUBLESTAREQUAL", - "DOUBLESLASH", - "DOUBLESLASHEQUAL", - "AT", - "ATEQUAL", - "RARROW", - "ELLIPSIS", - "COLONEQUAL", - "OP", - "AWAIT", - "ASYNC", - "TYPE_IGNORE", - "TYPE_COMMENT", - "SOFT_KEYWORD", - "ERRORTOKEN", - "COMMENT", - "NL", - "ENCODING", - "N_TOKENS", - "NT_OFFSET", - ] -elif sys.version_info >= (3, 8): - __all__ = [ - "tok_name", - "ISTERMINAL", - "ISNONTERMINAL", - "ISEOF", - "ENDMARKER", - "NAME", - "NUMBER", - "STRING", - "NEWLINE", - "INDENT", - "DEDENT", - "LPAR", - "RPAR", - "LSQB", - "RSQB", - "COLON", - "COMMA", - "SEMI", - "PLUS", - "MINUS", - "STAR", - "SLASH", - "VBAR", - "AMPER", - "LESS", - "GREATER", - "EQUAL", - "DOT", - "PERCENT", - "LBRACE", - "RBRACE", - "EQEQUAL", - "NOTEQUAL", - "LESSEQUAL", - "GREATEREQUAL", - "TILDE", - "CIRCUMFLEX", - "LEFTSHIFT", - "RIGHTSHIFT", - "DOUBLESTAR", - "PLUSEQUAL", - "MINEQUAL", - "STAREQUAL", - "SLASHEQUAL", - "PERCENTEQUAL", - "AMPEREQUAL", - "VBAREQUAL", - "CIRCUMFLEXEQUAL", - "LEFTSHIFTEQUAL", - "RIGHTSHIFTEQUAL", - "DOUBLESTAREQUAL", - "DOUBLESLASH", - "DOUBLESLASHEQUAL", - "AT", - "ATEQUAL", - "RARROW", - "ELLIPSIS", - "COLONEQUAL", - "OP", - "AWAIT", - "ASYNC", - "TYPE_IGNORE", - "TYPE_COMMENT", - "ERRORTOKEN", - "COMMENT", - "NL", - "ENCODING", - "N_TOKENS", - "NT_OFFSET", - ] -elif sys.version_info >= (3, 7): - __all__ = [ - "tok_name", - "ISTERMINAL", - "ISNONTERMINAL", - "ISEOF", - "ENDMARKER", - "NAME", - "NUMBER", - "STRING", - "NEWLINE", - "INDENT", - "DEDENT", - "LPAR", - "RPAR", - "LSQB", - "RSQB", - "COLON", - "COMMA", - "SEMI", - "PLUS", - "MINUS", - "STAR", - "SLASH", - "VBAR", - "AMPER", - "LESS", - "GREATER", - "EQUAL", - "DOT", - "PERCENT", - "LBRACE", - "RBRACE", - "EQEQUAL", - "NOTEQUAL", - "LESSEQUAL", - "GREATEREQUAL", - "TILDE", - "CIRCUMFLEX", - "LEFTSHIFT", - "RIGHTSHIFT", - "DOUBLESTAR", - "PLUSEQUAL", - "MINEQUAL", - "STAREQUAL", - "SLASHEQUAL", - "PERCENTEQUAL", - "AMPEREQUAL", - "VBAREQUAL", - "CIRCUMFLEXEQUAL", - "LEFTSHIFTEQUAL", - "RIGHTSHIFTEQUAL", - "DOUBLESTAREQUAL", - "DOUBLESLASH", - "DOUBLESLASHEQUAL", - "AT", - "ATEQUAL", - "RARROW", - "ELLIPSIS", - "OP", - "ERRORTOKEN", - "COMMENT", - "NL", - "ENCODING", - "N_TOKENS", - "NT_OFFSET", - ] -else: - __all__ = [ - "tok_name", - "ISTERMINAL", - "ISNONTERMINAL", - "ISEOF", - "ENDMARKER", - "NAME", - "NUMBER", - "STRING", - "NEWLINE", - "INDENT", - "DEDENT", - "LPAR", - "RPAR", - "LSQB", - "RSQB", - "COLON", - "COMMA", - "SEMI", - "PLUS", - "MINUS", - "STAR", - "SLASH", - "VBAR", - "AMPER", - "LESS", - "GREATER", - "EQUAL", - "DOT", - "PERCENT", - "LBRACE", - "RBRACE", - "EQEQUAL", - "NOTEQUAL", - "LESSEQUAL", - "GREATEREQUAL", - "TILDE", - "CIRCUMFLEX", - "LEFTSHIFT", - "RIGHTSHIFT", - "DOUBLESTAR", - "PLUSEQUAL", - "MINEQUAL", - "STAREQUAL", - "SLASHEQUAL", - "PERCENTEQUAL", - "AMPEREQUAL", - "VBAREQUAL", - "CIRCUMFLEXEQUAL", - "LEFTSHIFTEQUAL", - "RIGHTSHIFTEQUAL", - "DOUBLESTAREQUAL", - "DOUBLESLASH", - "DOUBLESLASHEQUAL", - "AT", - "ATEQUAL", - "RARROW", - "ELLIPSIS", - "OP", - "AWAIT", - "ASYNC", - "ERRORTOKEN", - "N_TOKENS", - "NT_OFFSET", - ] + __all__ += ["SOFT_KEYWORD"] ENDMARKER: int NAME: int diff --git a/mypy/typeshed/stdlib/tokenize.pyi b/mypy/typeshed/stdlib/tokenize.pyi index dea83263b550..3ac136150ab5 100644 --- a/mypy/typeshed/stdlib/tokenize.pyi +++ b/mypy/typeshed/stdlib/tokenize.pyi @@ -6,305 +6,85 @@ from token import * from typing import Any, NamedTuple, Pattern, TextIO from typing_extensions import TypeAlias +__all__ = [ + "AMPER", + "AMPEREQUAL", + "AT", + "ATEQUAL", + "CIRCUMFLEX", + "CIRCUMFLEXEQUAL", + "COLON", + "COMMA", + "COMMENT", + "DEDENT", + "DOT", + "DOUBLESLASH", + "DOUBLESLASHEQUAL", + "DOUBLESTAR", + "DOUBLESTAREQUAL", + "ELLIPSIS", + "ENCODING", + "ENDMARKER", + "EQEQUAL", + "EQUAL", + "ERRORTOKEN", + "GREATER", + "GREATEREQUAL", + "INDENT", + "ISEOF", + "ISNONTERMINAL", + "ISTERMINAL", + "LBRACE", + "LEFTSHIFT", + "LEFTSHIFTEQUAL", + "LESS", + "LESSEQUAL", + "LPAR", + "LSQB", + "MINEQUAL", + "MINUS", + "NAME", + "NEWLINE", + "NL", + "NOTEQUAL", + "NT_OFFSET", + "NUMBER", + "N_TOKENS", + "OP", + "PERCENT", + "PERCENTEQUAL", + "PLUS", + "PLUSEQUAL", + "RARROW", + "RBRACE", + "RIGHTSHIFT", + "RIGHTSHIFTEQUAL", + "RPAR", + "RSQB", + "SEMI", + "SLASH", + "SLASHEQUAL", + "STAR", + "STAREQUAL", + "STRING", + "TILDE", + "TokenInfo", + "VBAR", + "VBAREQUAL", + "detect_encoding", + "tok_name", + "tokenize", + "untokenize", +] + +if sys.version_info < (3, 7) or sys.version_info >= (3, 8): + __all__ += ["ASYNC", "AWAIT"] + +if sys.version_info >= (3, 8): + __all__ += ["COLONEQUAL", "generate_tokens", "TYPE_COMMENT", "TYPE_IGNORE"] + if sys.version_info >= (3, 10): - __all__ = [ - "tok_name", - "ISTERMINAL", - "ISNONTERMINAL", - "ISEOF", - "ENDMARKER", - "NAME", - "NUMBER", - "STRING", - "NEWLINE", - "INDENT", - "DEDENT", - "LPAR", - "RPAR", - "LSQB", - "RSQB", - "COLON", - "COMMA", - "SEMI", - "PLUS", - "MINUS", - "STAR", - "SLASH", - "VBAR", - "AMPER", - "LESS", - "GREATER", - "EQUAL", - "DOT", - "PERCENT", - "LBRACE", - "RBRACE", - "EQEQUAL", - "NOTEQUAL", - "LESSEQUAL", - "GREATEREQUAL", - "TILDE", - "CIRCUMFLEX", - "LEFTSHIFT", - "RIGHTSHIFT", - "DOUBLESTAR", - "PLUSEQUAL", - "MINEQUAL", - "STAREQUAL", - "SLASHEQUAL", - "PERCENTEQUAL", - "AMPEREQUAL", - "VBAREQUAL", - "CIRCUMFLEXEQUAL", - "LEFTSHIFTEQUAL", - "RIGHTSHIFTEQUAL", - "DOUBLESTAREQUAL", - "DOUBLESLASH", - "DOUBLESLASHEQUAL", - "AT", - "ATEQUAL", - "RARROW", - "ELLIPSIS", - "COLONEQUAL", - "OP", - "AWAIT", - "ASYNC", - "TYPE_IGNORE", - "TYPE_COMMENT", - "SOFT_KEYWORD", - "ERRORTOKEN", - "COMMENT", - "NL", - "ENCODING", - "N_TOKENS", - "NT_OFFSET", - "tokenize", - "generate_tokens", - "detect_encoding", - "untokenize", - "TokenInfo", - ] -elif sys.version_info >= (3, 8): - __all__ = [ - "tok_name", - "ISTERMINAL", - "ISNONTERMINAL", - "ISEOF", - "ENDMARKER", - "NAME", - "NUMBER", - "STRING", - "NEWLINE", - "INDENT", - "DEDENT", - "LPAR", - "RPAR", - "LSQB", - "RSQB", - "COLON", - "COMMA", - "SEMI", - "PLUS", - "MINUS", - "STAR", - "SLASH", - "VBAR", - "AMPER", - "LESS", - "GREATER", - "EQUAL", - "DOT", - "PERCENT", - "LBRACE", - "RBRACE", - "EQEQUAL", - "NOTEQUAL", - "LESSEQUAL", - "GREATEREQUAL", - "TILDE", - "CIRCUMFLEX", - "LEFTSHIFT", - "RIGHTSHIFT", - "DOUBLESTAR", - "PLUSEQUAL", - "MINEQUAL", - "STAREQUAL", - "SLASHEQUAL", - "PERCENTEQUAL", - "AMPEREQUAL", - "VBAREQUAL", - "CIRCUMFLEXEQUAL", - "LEFTSHIFTEQUAL", - "RIGHTSHIFTEQUAL", - "DOUBLESTAREQUAL", - "DOUBLESLASH", - "DOUBLESLASHEQUAL", - "AT", - "ATEQUAL", - "RARROW", - "ELLIPSIS", - "COLONEQUAL", - "OP", - "AWAIT", - "ASYNC", - "TYPE_IGNORE", - "TYPE_COMMENT", - "ERRORTOKEN", - "COMMENT", - "NL", - "ENCODING", - "N_TOKENS", - "NT_OFFSET", - "tokenize", - "generate_tokens", - "detect_encoding", - "untokenize", - "TokenInfo", - ] -elif sys.version_info >= (3, 7): - __all__ = [ - "tok_name", - "ISTERMINAL", - "ISNONTERMINAL", - "ISEOF", - "ENDMARKER", - "NAME", - "NUMBER", - "STRING", - "NEWLINE", - "INDENT", - "DEDENT", - "LPAR", - "RPAR", - "LSQB", - "RSQB", - "COLON", - "COMMA", - "SEMI", - "PLUS", - "MINUS", - "STAR", - "SLASH", - "VBAR", - "AMPER", - "LESS", - "GREATER", - "EQUAL", - "DOT", - "PERCENT", - "LBRACE", - "RBRACE", - "EQEQUAL", - "NOTEQUAL", - "LESSEQUAL", - "GREATEREQUAL", - "TILDE", - "CIRCUMFLEX", - "LEFTSHIFT", - "RIGHTSHIFT", - "DOUBLESTAR", - "PLUSEQUAL", - "MINEQUAL", - "STAREQUAL", - "SLASHEQUAL", - "PERCENTEQUAL", - "AMPEREQUAL", - "VBAREQUAL", - "CIRCUMFLEXEQUAL", - "LEFTSHIFTEQUAL", - "RIGHTSHIFTEQUAL", - "DOUBLESTAREQUAL", - "DOUBLESLASH", - "DOUBLESLASHEQUAL", - "AT", - "ATEQUAL", - "RARROW", - "ELLIPSIS", - "OP", - "ERRORTOKEN", - "COMMENT", - "NL", - "ENCODING", - "N_TOKENS", - "NT_OFFSET", - "tokenize", - "detect_encoding", - "untokenize", - "TokenInfo", - ] -else: - __all__ = [ - "tok_name", - "ISTERMINAL", - "ISNONTERMINAL", - "ISEOF", - "ENDMARKER", - "NAME", - "NUMBER", - "STRING", - "NEWLINE", - "INDENT", - "DEDENT", - "LPAR", - "RPAR", - "LSQB", - "RSQB", - "COLON", - "COMMA", - "SEMI", - "PLUS", - "MINUS", - "STAR", - "SLASH", - "VBAR", - "AMPER", - "LESS", - "GREATER", - "EQUAL", - "DOT", - "PERCENT", - "LBRACE", - "RBRACE", - "EQEQUAL", - "NOTEQUAL", - "LESSEQUAL", - "GREATEREQUAL", - "TILDE", - "CIRCUMFLEX", - "LEFTSHIFT", - "RIGHTSHIFT", - "DOUBLESTAR", - "PLUSEQUAL", - "MINEQUAL", - "STAREQUAL", - "SLASHEQUAL", - "PERCENTEQUAL", - "AMPEREQUAL", - "VBAREQUAL", - "CIRCUMFLEXEQUAL", - "LEFTSHIFTEQUAL", - "RIGHTSHIFTEQUAL", - "DOUBLESTAREQUAL", - "DOUBLESLASH", - "DOUBLESLASHEQUAL", - "AT", - "ATEQUAL", - "RARROW", - "ELLIPSIS", - "OP", - "AWAIT", - "ASYNC", - "ERRORTOKEN", - "N_TOKENS", - "NT_OFFSET", - "COMMENT", - "tokenize", - "detect_encoding", - "NL", - "untokenize", - "ENCODING", - "TokenInfo", - ] + __all__ += ["SOFT_KEYWORD"] if sys.version_info >= (3, 8): from token import EXACT_TOKEN_TYPES as EXACT_TOKEN_TYPES diff --git a/mypy/typeshed/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi index 5c4d323a2d9f..16151f9431eb 100644 --- a/mypy/typeshed/stdlib/traceback.pyi +++ b/mypy/typeshed/stdlib/traceback.pyi @@ -96,6 +96,12 @@ def clear_frames(tb: TracebackType) -> None: ... def walk_stack(f: FrameType | None) -> Iterator[tuple[FrameType, int]]: ... def walk_tb(tb: TracebackType | None) -> Iterator[tuple[FrameType, int]]: ... +if sys.version_info >= (3, 11): + class _ExceptionPrintContext: + def __init__(self) -> None: ... + def indent(self) -> str: ... + def emit(self, text_gen: str | Iterable[str], margin_char: str | None = ...) -> Generator[str, None, None]: ... + class TracebackException: __cause__: TracebackException __context__: TracebackException @@ -107,7 +113,34 @@ class TracebackException: text: str offset: int msg: str - if sys.version_info >= (3, 10): + if sys.version_info >= (3, 11): + def __init__( + self, + exc_type: type[BaseException], + exc_value: BaseException, + exc_traceback: TracebackType | None, + *, + limit: int | None = ..., + lookup_lines: bool = ..., + capture_locals: bool = ..., + compact: bool = ..., + max_group_width: int = ..., + max_group_depth: int = ..., + _seen: set[int] | None = ..., + ) -> None: ... + @classmethod + def from_exception( + cls: type[Self], + exc: BaseException, + *, + limit: int | None = ..., + lookup_lines: bool = ..., + capture_locals: bool = ..., + compact: bool = ..., + max_group_width: int = ..., + max_group_depth: int = ..., + ) -> Self: ... + elif sys.version_info >= (3, 10): def __init__( self, exc_type: type[BaseException], @@ -148,9 +181,16 @@ class TracebackException: ) -> Self: ... def __eq__(self, other: object) -> bool: ... - def format(self, *, chain: bool = ...) -> Generator[str, None, None]: ... + if sys.version_info >= (3, 11): + def format(self, *, chain: bool = ..., _ctx: _ExceptionPrintContext | None = ...) -> Generator[str, None, None]: ... + else: + def format(self, *, chain: bool = ...) -> Generator[str, None, None]: ... + def format_exception_only(self) -> Generator[str, None, None]: ... + if sys.version_info >= (3, 11): + def print(self, *, file: SupportsWrite[str] | None = ..., chain: bool = ...) -> None: ... + class FrameSummary(Iterable[Any]): if sys.version_info >= (3, 11): def __init__( @@ -213,4 +253,7 @@ class StackSummary(list[FrameSummary]): ) -> StackSummary: ... @classmethod def from_list(cls, a_list: list[_PT]) -> StackSummary: ... + if sys.version_info >= (3, 11): + def format_frame_summary(self, frame_summary: FrameSummary) -> str: ... + def format(self) -> list[str]: ... diff --git a/mypy/typeshed/stdlib/turtle.pyi b/mypy/typeshed/stdlib/turtle.pyi index 3e91a5eb0ebf..cdacaf63c41f 100644 --- a/mypy/typeshed/stdlib/turtle.pyi +++ b/mypy/typeshed/stdlib/turtle.pyi @@ -142,9 +142,18 @@ _PenState: TypeAlias = dict[str, Any] _Speed: TypeAlias = str | float _PolygonCoords: TypeAlias = Sequence[tuple[float, float]] -# TODO: Type this more accurately -# Vec2D is actually a custom subclass of 'tuple'. -Vec2D: TypeAlias = tuple[float, float] +class Vec2D(tuple[float, float]): + def __new__(cls: type[Self], x: float, y: float) -> Self: ... + def __add__(self, other: tuple[float, float]) -> Vec2D: ... # type: ignore[override] + @overload # type: ignore[override] + def __mul__(self, other: Vec2D) -> float: ... + @overload + def __mul__(self, other: float) -> Vec2D: ... + def __rmul__(self, other: float) -> Vec2D: ... # type: ignore[override] + def __sub__(self, other: tuple[float, float]) -> Vec2D: ... + def __neg__(self) -> Vec2D: ... + def __abs__(self) -> float: ... + def rotate(self, angle: float) -> Vec2D: ... # Does not actually inherit from Canvas, but dynamically gets all methods of Canvas class ScrolledCanvas(Canvas, Frame): # type: ignore[misc] @@ -410,7 +419,11 @@ class _Screen(TurtleScreen): def __init__(self) -> None: ... # Note int and float are interpreted differently, hence the Union instead of just float def setup( - self, width: int | float = ..., height: int | float = ..., startx: int | None = ..., starty: int | None = ... + self, + width: int | float = ..., # noqa: Y041 + height: int | float = ..., # noqa: Y041 + startx: int | None = ..., + starty: int | None = ..., ) -> None: ... def title(self, titlestring: str) -> None: ... def bye(self) -> None: ... diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index ed2476e44a86..de8c8423d47e 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -20,150 +20,47 @@ from importlib.machinery import ModuleSpec from typing import Any, ClassVar, Generic, Mapping, TypeVar, overload # noqa: Y027 from typing_extensions import Literal, ParamSpec, final -if sys.version_info >= (3, 10): - __all__ = [ - "FunctionType", - "LambdaType", - "CodeType", - "MappingProxyType", - "SimpleNamespace", - "CellType", - "GeneratorType", - "CoroutineType", - "AsyncGeneratorType", - "MethodType", - "BuiltinFunctionType", - "BuiltinMethodType", - "WrapperDescriptorType", - "MethodWrapperType", - "MethodDescriptorType", +__all__ = [ + "FunctionType", + "LambdaType", + "CodeType", + "MappingProxyType", + "SimpleNamespace", + "GeneratorType", + "CoroutineType", + "AsyncGeneratorType", + "MethodType", + "BuiltinFunctionType", + "ModuleType", + "TracebackType", + "FrameType", + "GetSetDescriptorType", + "MemberDescriptorType", + "new_class", + "prepare_class", + "DynamicClassAttribute", + "coroutine", + "BuiltinMethodType", +] + +if sys.version_info >= (3, 7): + __all__ += [ "ClassMethodDescriptorType", - "ModuleType", - "TracebackType", - "FrameType", - "GetSetDescriptorType", - "MemberDescriptorType", - "new_class", - "resolve_bases", - "prepare_class", - "DynamicClassAttribute", - "coroutine", - "GenericAlias", - "UnionType", - "EllipsisType", - "NoneType", - "NotImplementedType", - ] -elif sys.version_info >= (3, 9): - __all__ = [ - "FunctionType", - "LambdaType", - "CodeType", - "MappingProxyType", - "SimpleNamespace", - "CellType", - "GeneratorType", - "CoroutineType", - "AsyncGeneratorType", - "MethodType", - "BuiltinFunctionType", - "BuiltinMethodType", - "WrapperDescriptorType", - "MethodWrapperType", "MethodDescriptorType", - "ClassMethodDescriptorType", - "ModuleType", - "TracebackType", - "FrameType", - "GetSetDescriptorType", - "MemberDescriptorType", - "new_class", - "resolve_bases", - "prepare_class", - "DynamicClassAttribute", - "coroutine", - "GenericAlias", - ] -elif sys.version_info >= (3, 8): - __all__ = [ - "FunctionType", - "LambdaType", - "CodeType", - "MappingProxyType", - "SimpleNamespace", - "CellType", - "GeneratorType", - "CoroutineType", - "AsyncGeneratorType", - "MethodType", - "BuiltinFunctionType", - "BuiltinMethodType", - "WrapperDescriptorType", "MethodWrapperType", - "MethodDescriptorType", - "ClassMethodDescriptorType", - "ModuleType", - "TracebackType", - "FrameType", - "GetSetDescriptorType", - "MemberDescriptorType", - "new_class", - "resolve_bases", - "prepare_class", - "DynamicClassAttribute", - "coroutine", - ] -elif sys.version_info >= (3, 7): - __all__ = [ - "FunctionType", - "LambdaType", - "CodeType", - "MappingProxyType", - "SimpleNamespace", - "GeneratorType", - "CoroutineType", - "AsyncGeneratorType", - "MethodType", - "BuiltinFunctionType", - "BuiltinMethodType", "WrapperDescriptorType", - "MethodWrapperType", - "MethodDescriptorType", - "ClassMethodDescriptorType", - "ModuleType", - "TracebackType", - "FrameType", - "GetSetDescriptorType", - "MemberDescriptorType", - "new_class", "resolve_bases", - "prepare_class", - "DynamicClassAttribute", - "coroutine", - ] -else: - __all__ = [ - "FunctionType", - "LambdaType", - "CodeType", - "MappingProxyType", - "SimpleNamespace", - "GeneratorType", - "CoroutineType", - "AsyncGeneratorType", - "MethodType", - "BuiltinFunctionType", - "ModuleType", - "TracebackType", - "FrameType", - "GetSetDescriptorType", - "MemberDescriptorType", - "new_class", - "prepare_class", - "DynamicClassAttribute", - "coroutine", ] +if sys.version_info >= (3, 8): + __all__ += ["CellType"] + +if sys.version_info >= (3, 9): + __all__ += ["GenericAlias"] + +if sys.version_info >= (3, 10): + __all__ += ["EllipsisType", "NoneType", "NotImplementedType", "UnionType"] + # Note, all classes "defined" here require special handling. _T1 = TypeVar("_T1") @@ -250,46 +147,99 @@ class CodeType: def co_freevars(self) -> tuple[str, ...]: ... @property def co_cellvars(self) -> tuple[str, ...]: ... - if sys.version_info >= (3, 8): + if sys.version_info >= (3, 10): + @property + def co_linetable(self) -> bytes: ... + def co_lines(self) -> Iterator[tuple[int, int, int | None]]: ... + if sys.version_info >= (3, 11): + @property + def co_exceptiontable(self) -> bytes: ... + @property + def co_qualname(self) -> str: ... + def co_positions(self) -> Iterable[tuple[int | None, int | None, int | None, int | None]]: ... + + if sys.version_info >= (3, 11): + def __init__( + self, + __argcount: int, + __posonlyargcount: int, + __kwonlyargcount: int, + __nlocals: int, + __stacksize: int, + __flags: int, + __codestring: bytes, + __constants: tuple[object, ...], + __names: tuple[str, ...], + __varnames: tuple[str, ...], + __filename: str, + __name: str, + __qualname: str, + __firstlineno: int, + __linetable: bytes, + __exceptiontable: bytes, + __freevars: tuple[str, ...] = ..., + __cellvars: tuple[str, ...] = ..., + ) -> None: ... + elif sys.version_info >= (3, 10): + def __init__( + self, + __argcount: int, + __posonlyargcount: int, + __kwonlyargcount: int, + __nlocals: int, + __stacksize: int, + __flags: int, + __codestring: bytes, + __constants: tuple[object, ...], + __names: tuple[str, ...], + __varnames: tuple[str, ...], + __filename: str, + __name: str, + __firstlineno: int, + __linetable: bytes, + __freevars: tuple[str, ...] = ..., + __cellvars: tuple[str, ...] = ..., + ) -> None: ... + elif sys.version_info >= (3, 8): def __init__( self, - argcount: int, - posonlyargcount: int, - kwonlyargcount: int, - nlocals: int, - stacksize: int, - flags: int, - codestring: bytes, - constants: tuple[Any, ...], - names: tuple[str, ...], - varnames: tuple[str, ...], - filename: str, - name: str, - firstlineno: int, - lnotab: bytes, - freevars: tuple[str, ...] = ..., - cellvars: tuple[str, ...] = ..., + __argcount: int, + __posonlyargcount: int, + __kwonlyargcount: int, + __nlocals: int, + __stacksize: int, + __flags: int, + __codestring: bytes, + __constants: tuple[object, ...], + __names: tuple[str, ...], + __varnames: tuple[str, ...], + __filename: str, + __name: str, + __firstlineno: int, + __lnotab: bytes, + __freevars: tuple[str, ...] = ..., + __cellvars: tuple[str, ...] = ..., ) -> None: ... else: def __init__( self, - argcount: int, - kwonlyargcount: int, - nlocals: int, - stacksize: int, - flags: int, - codestring: bytes, - constants: tuple[Any, ...], - names: tuple[str, ...], - varnames: tuple[str, ...], - filename: str, - name: str, - firstlineno: int, - lnotab: bytes, - freevars: tuple[str, ...] = ..., - cellvars: tuple[str, ...] = ..., + __argcount: int, + __kwonlyargcount: int, + __nlocals: int, + __stacksize: int, + __flags: int, + __codestring: bytes, + __constants: tuple[object, ...], + __names: tuple[str, ...], + __varnames: tuple[str, ...], + __filename: str, + __name: str, + __firstlineno: int, + __lnotab: bytes, + __freevars: tuple[str, ...] = ..., + __cellvars: tuple[str, ...] = ..., ) -> None: ... - if sys.version_info >= (3, 10): + if sys.version_info >= (3, 11): def replace( self, *, @@ -301,18 +251,38 @@ class CodeType: co_flags: int = ..., co_firstlineno: int = ..., co_code: bytes = ..., - co_consts: tuple[Any, ...] = ..., + co_consts: tuple[object, ...] = ..., co_names: tuple[str, ...] = ..., co_varnames: tuple[str, ...] = ..., co_freevars: tuple[str, ...] = ..., co_cellvars: tuple[str, ...] = ..., co_filename: str = ..., co_name: str = ..., - co_linetable: object = ..., + co_qualname: str = ..., + co_linetable: bytes = ..., + co_exceptiontable: bytes = ..., + ) -> CodeType: ... + elif sys.version_info >= (3, 10): + def replace( + self, + *, + co_argcount: int = ..., + co_posonlyargcount: int = ..., + co_kwonlyargcount: int = ..., + co_nlocals: int = ..., + co_stacksize: int = ..., + co_flags: int = ..., + co_firstlineno: int = ..., + co_code: bytes = ..., + co_consts: tuple[object, ...] = ..., + co_names: tuple[str, ...] = ..., + co_varnames: tuple[str, ...] = ..., + co_freevars: tuple[str, ...] = ..., + co_cellvars: tuple[str, ...] = ..., + co_filename: str = ..., + co_name: str = ..., + co_linetable: bytes = ..., ) -> CodeType: ... - def co_lines(self) -> Iterator[tuple[int, int, int | None]]: ... - @property - def co_linetable(self) -> object: ... elif sys.version_info >= (3, 8): def replace( self, @@ -325,7 +295,7 @@ class CodeType: co_flags: int = ..., co_firstlineno: int = ..., co_code: bytes = ..., - co_consts: tuple[Any, ...] = ..., + co_consts: tuple[object, ...] = ..., co_names: tuple[str, ...] = ..., co_varnames: tuple[str, ...] = ..., co_freevars: tuple[str, ...] = ..., @@ -334,8 +304,6 @@ class CodeType: co_name: str = ..., co_lnotab: bytes = ..., ) -> CodeType: ... - if sys.version_info >= (3, 11): - def co_positions(self) -> Iterable[tuple[int | None, int | None, int | None, int | None]]: ... @final class MappingProxyType(Mapping[_KT, _VT_co], Generic[_KT, _VT_co]): @@ -386,6 +354,9 @@ class GeneratorType(Generator[_T_co, _T_contra, _V_co]): def gi_running(self) -> bool: ... @property def gi_yieldfrom(self) -> GeneratorType[_T_co, _T_contra, Any] | None: ... + if sys.version_info >= (3, 11): + @property + def gi_suspended(self) -> bool: ... __name__: str __qualname__: str def __iter__(self) -> GeneratorType[_T_co, _T_contra, _V_co]: ... @@ -439,6 +410,9 @@ class CoroutineType(Coroutine[_T_co, _T_contra, _V_co]): if sys.version_info >= (3, 7): @property def cr_origin(self) -> tuple[tuple[str, int, str], ...] | None: ... + if sys.version_info >= (3, 11): + @property + def cr_suspended(self) -> bool: ... def close(self) -> None: ... def __await__(self) -> Generator[Any, None, _V_co]: ... @@ -654,6 +628,8 @@ if sys.version_info >= (3, 9): if sys.version_info >= (3, 11): @property def __unpacked__(self) -> bool: ... + @property + def __typing_unpacked_tuple_args__(self) -> tuple[Any, ...] | None: ... def __getattr__(self, name: str) -> Any: ... # incomplete diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 37ea55c9f2ef..969e61952d5f 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -1,6 +1,6 @@ import collections # Needed by aliases like DefaultDict, see mypy issue 2986 import sys -from _typeshed import ReadableBuffer, Self as TypeshedSelf, SupportsKeysAndGetItem +from _typeshed import IdentityFunction, ReadableBuffer, Self as TypeshedSelf, SupportsKeysAndGetItem from abc import ABCMeta, abstractmethod from types import BuiltinFunctionType, CodeType, FrameType, FunctionType, MethodType, ModuleType, TracebackType from typing_extensions import Literal as _Literal, ParamSpec as _ParamSpec, final as _final @@ -11,466 +11,108 @@ if sys.version_info >= (3, 7): if sys.version_info >= (3, 9): from types import GenericAlias -if sys.version_info >= (3, 11): - __all__ = [ - "Annotated", - "Any", - "Callable", - "ClassVar", - "Concatenate", +__all__ = [ + "AbstractSet", + "Any", + "AnyStr", + "AsyncContextManager", + "AsyncGenerator", + "AsyncIterable", + "AsyncIterator", + "Awaitable", + "ByteString", + "Callable", + "ChainMap", + "ClassVar", + "Collection", + "Container", + "ContextManager", + "Coroutine", + "Counter", + "DefaultDict", + "Deque", + "Dict", + "FrozenSet", + "Generator", + "Generic", + "Hashable", + "ItemsView", + "Iterable", + "Iterator", + "KeysView", + "List", + "Mapping", + "MappingView", + "MutableMapping", + "MutableSequence", + "MutableSet", + "NamedTuple", + "NewType", + "Optional", + "Reversible", + "Sequence", + "Set", + "Sized", + "SupportsAbs", + "SupportsBytes", + "SupportsComplex", + "SupportsFloat", + "SupportsInt", + "SupportsRound", + "Text", + "Tuple", + "Type", + "TypeVar", + "Union", + "ValuesView", + "TYPE_CHECKING", + "cast", + "get_type_hints", + "no_type_check", + "no_type_check_decorator", + "overload", +] + +if sys.version_info < (3, 7): + __all__ += ["GenericMeta"] + +if sys.version_info >= (3, 7): + __all__ += ["ForwardRef", "NoReturn", "OrderedDict"] + +if sys.version_info >= (3, 8): + __all__ += [ "Final", - "ForwardRef", - "Generic", "Literal", + "Protocol", + "SupportsIndex", + "TypedDict", + "final", + "get_args", + "get_origin", + "runtime_checkable", + ] + +if sys.version_info >= (3, 9): + __all__ += ["Annotated", "BinaryIO", "IO", "Match", "Pattern", "TextIO"] + +if sys.version_info >= (3, 10): + __all__ += ["Concatenate", "ParamSpec", "ParamSpecArgs", "ParamSpecKwargs", "TypeAlias", "TypeGuard", "is_typeddict"] + +if sys.version_info >= (3, 11): + __all__ += [ "LiteralString", + "Never", "NotRequired", - "Optional", - "ParamSpec", - "Protocol", "Required", - "Tuple", - "Type", - "TypeVar", + "Self", "TypeVarTuple", - "Union", "Unpack", - "AbstractSet", - "ByteString", - "Container", - "ContextManager", - "Hashable", - "ItemsView", - "Iterable", - "Iterator", - "KeysView", - "Mapping", - "MappingView", - "MutableMapping", - "MutableSequence", - "MutableSet", - "Sequence", - "Sized", - "ValuesView", - "Awaitable", - "AsyncIterator", - "AsyncIterable", - "Coroutine", - "Collection", - "AsyncGenerator", - "AsyncContextManager", - "Reversible", - "SupportsAbs", - "SupportsBytes", - "SupportsComplex", - "SupportsFloat", - "SupportsIndex", - "SupportsInt", - "SupportsRound", - "ChainMap", - "Counter", - "Deque", - "Dict", - "DefaultDict", - "List", - "OrderedDict", - "Set", - "FrozenSet", - "NamedTuple", - "TypedDict", - "Generator", - "BinaryIO", - "IO", - "Match", - "Pattern", - "TextIO", - "AnyStr", "assert_never", "assert_type", - "cast", "clear_overloads", "dataclass_transform", - "final", - "get_args", - "get_origin", "get_overloads", - "get_type_hints", - "is_typeddict", - "Never", - "NewType", - "no_type_check", - "no_type_check_decorator", - "NoReturn", - "overload", - "ParamSpecArgs", - "ParamSpecKwargs", "reveal_type", - "runtime_checkable", - "Self", - "Text", - "TYPE_CHECKING", - "TypeAlias", - "TypeGuard", - ] -elif sys.version_info >= (3, 10): - __all__ = [ - "Annotated", - "Any", - "Callable", - "ClassVar", - "Concatenate", - "Final", - "ForwardRef", - "Generic", - "Literal", - "Optional", - "ParamSpec", - "Protocol", - "Tuple", - "Type", - "TypeVar", - "Union", - "AbstractSet", - "ByteString", - "Container", - "ContextManager", - "Hashable", - "ItemsView", - "Iterable", - "Iterator", - "KeysView", - "Mapping", - "MappingView", - "MutableMapping", - "MutableSequence", - "MutableSet", - "Sequence", - "Sized", - "ValuesView", - "Awaitable", - "AsyncIterator", - "AsyncIterable", - "Coroutine", - "Collection", - "AsyncGenerator", - "AsyncContextManager", - "Reversible", - "SupportsAbs", - "SupportsBytes", - "SupportsComplex", - "SupportsFloat", - "SupportsIndex", - "SupportsInt", - "SupportsRound", - "ChainMap", - "Counter", - "Deque", - "Dict", - "DefaultDict", - "List", - "OrderedDict", - "Set", - "FrozenSet", - "NamedTuple", - "TypedDict", - "Generator", - "BinaryIO", - "IO", - "Match", - "Pattern", - "TextIO", - "AnyStr", - "cast", - "final", - "get_args", - "get_origin", - "get_type_hints", - "is_typeddict", - "NewType", - "no_type_check", - "no_type_check_decorator", - "NoReturn", - "overload", - "ParamSpecArgs", - "ParamSpecKwargs", - "runtime_checkable", - "Text", - "TYPE_CHECKING", - "TypeAlias", - "TypeGuard", - ] -elif sys.version_info >= (3, 9): - __all__ = [ - "Annotated", - "Any", - "Callable", - "ClassVar", - "Final", - "ForwardRef", - "Generic", - "Literal", - "Optional", - "Protocol", - "Tuple", - "Type", - "TypeVar", - "Union", - "AbstractSet", - "ByteString", - "Container", - "ContextManager", - "Hashable", - "ItemsView", - "Iterable", - "Iterator", - "KeysView", - "Mapping", - "MappingView", - "MutableMapping", - "MutableSequence", - "MutableSet", - "Sequence", - "Sized", - "ValuesView", - "Awaitable", - "AsyncIterator", - "AsyncIterable", - "Coroutine", - "Collection", - "AsyncGenerator", - "AsyncContextManager", - "Reversible", - "SupportsAbs", - "SupportsBytes", - "SupportsComplex", - "SupportsFloat", - "SupportsIndex", - "SupportsInt", - "SupportsRound", - "ChainMap", - "Counter", - "Deque", - "Dict", - "DefaultDict", - "List", - "OrderedDict", - "Set", - "FrozenSet", - "NamedTuple", - "TypedDict", - "Generator", - "BinaryIO", - "IO", - "Match", - "Pattern", - "TextIO", - "AnyStr", - "cast", - "final", - "get_args", - "get_origin", - "get_type_hints", - "NewType", - "no_type_check", - "no_type_check_decorator", - "NoReturn", - "overload", - "runtime_checkable", - "Text", - "TYPE_CHECKING", - ] -elif sys.version_info >= (3, 8): - __all__ = [ - "Any", - "Callable", - "ClassVar", - "Final", - "ForwardRef", - "Generic", - "Literal", - "Optional", - "Protocol", - "Tuple", - "Type", - "TypeVar", - "Union", - "AbstractSet", - "ByteString", - "Container", - "ContextManager", - "Hashable", - "ItemsView", - "Iterable", - "Iterator", - "KeysView", - "Mapping", - "MappingView", - "MutableMapping", - "MutableSequence", - "MutableSet", - "Sequence", - "Sized", - "ValuesView", - "Awaitable", - "AsyncIterator", - "AsyncIterable", - "Coroutine", - "Collection", - "AsyncGenerator", - "AsyncContextManager", - "Reversible", - "SupportsAbs", - "SupportsBytes", - "SupportsComplex", - "SupportsFloat", - "SupportsIndex", - "SupportsInt", - "SupportsRound", - "ChainMap", - "Counter", - "Deque", - "Dict", - "DefaultDict", - "List", - "OrderedDict", - "Set", - "FrozenSet", - "NamedTuple", - "TypedDict", - "Generator", - "AnyStr", - "cast", - "final", - "get_args", - "get_origin", - "get_type_hints", - "NewType", - "no_type_check", - "no_type_check_decorator", - "NoReturn", - "overload", - "runtime_checkable", - "Text", - "TYPE_CHECKING", - ] -elif sys.version_info >= (3, 7): - __all__ = [ - "Any", - "Callable", - "ClassVar", - "ForwardRef", - "Generic", - "Optional", - "Tuple", - "Type", - "TypeVar", - "Union", - "AbstractSet", - "ByteString", - "Container", - "ContextManager", - "Hashable", - "ItemsView", - "Iterable", - "Iterator", - "KeysView", - "Mapping", - "MappingView", - "MutableMapping", - "MutableSequence", - "MutableSet", - "Sequence", - "Sized", - "ValuesView", - "Awaitable", - "AsyncIterator", - "AsyncIterable", - "Coroutine", - "Collection", - "AsyncGenerator", - "AsyncContextManager", - "Reversible", - "SupportsAbs", - "SupportsBytes", - "SupportsComplex", - "SupportsFloat", - "SupportsInt", - "SupportsRound", - "ChainMap", - "Counter", - "Deque", - "Dict", - "DefaultDict", - "List", - "OrderedDict", - "Set", - "FrozenSet", - "NamedTuple", - "Generator", - "AnyStr", - "cast", - "get_type_hints", - "NewType", - "no_type_check", - "no_type_check_decorator", - "NoReturn", - "overload", - "Text", - "TYPE_CHECKING", - ] -else: - __all__ = [ - "Any", - "Callable", - "ClassVar", - "Generic", - "Optional", - "Tuple", - "Type", - "TypeVar", - "Union", - "AbstractSet", - "GenericMeta", - "ByteString", - "Container", - "ContextManager", - "Hashable", - "ItemsView", - "Iterable", - "Iterator", - "KeysView", - "Mapping", - "MappingView", - "MutableMapping", - "MutableSequence", - "MutableSet", - "Sequence", - "Sized", - "ValuesView", - "Reversible", - "SupportsAbs", - "SupportsBytes", - "SupportsComplex", - "SupportsFloat", - "SupportsInt", - "SupportsRound", - "Counter", - "Deque", - "Dict", - "DefaultDict", - "List", - "Set", - "FrozenSet", - "NamedTuple", - "Generator", - "AnyStr", - "cast", - "get_type_hints", - "NewType", - "no_type_check", - "no_type_check_decorator", - "overload", - "Text", - "TYPE_CHECKING", ] Any = object() @@ -1232,7 +874,7 @@ if sys.version_info >= (3, 11): kw_only_default: bool = ..., field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = ..., **kwargs: Any, - ) -> Callable[[_T], _T]: ... + ) -> IdentityFunction: ... # Type constructors diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index b94daaba9f49..38fb9dec19d9 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -1,6 +1,6 @@ import abc import sys -from _typeshed import Self as TypeshedSelf # see #6932 for why the alias cannot have a leading underscore +from _typeshed import IdentityFunction, Self as TypeshedSelf # see #6932 for why the Self alias cannot have a leading underscore from typing import ( # noqa: Y022,Y027,Y039 TYPE_CHECKING as TYPE_CHECKING, Any, @@ -232,4 +232,4 @@ else: kw_only_default: bool = ..., field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = ..., **kwargs: object, - ) -> Callable[[_T], _T]: ... + ) -> IdentityFunction: ... diff --git a/mypy/typeshed/stdlib/unicodedata.pyi b/mypy/typeshed/stdlib/unicodedata.pyi index aec8867df48d..7337ab8789b2 100644 --- a/mypy/typeshed/stdlib/unicodedata.pyi +++ b/mypy/typeshed/stdlib/unicodedata.pyi @@ -38,6 +38,9 @@ class UCD: def decomposition(self, __chr: str) -> str: ... def digit(self, __chr: str, __default: _T = ...) -> int | _T: ... def east_asian_width(self, __chr: str) -> str: ... + if sys.version_info >= (3, 8): + def is_normalized(self, __form: str, __unistr: str) -> bool: ... + def lookup(self, __name: str | bytes) -> str: ... def mirrored(self, __chr: str) -> int: ... def name(self, __chr: str, __default: _T = ...) -> str | _T: ... diff --git a/mypy/typeshed/stdlib/unittest/__init__.pyi b/mypy/typeshed/stdlib/unittest/__init__.pyi index 4bbf98c992c1..673597275b33 100644 --- a/mypy/typeshed/stdlib/unittest/__init__.pyi +++ b/mypy/typeshed/stdlib/unittest/__init__.pyi @@ -32,55 +32,37 @@ if sys.version_info >= (3, 8): from .case import addModuleCleanup as addModuleCleanup - __all__ = [ - "TestResult", - "TestCase", - "IsolatedAsyncioTestCase", - "TestSuite", - "TextTestRunner", - "TestLoader", - "FunctionTestCase", - "main", - "defaultTestLoader", - "SkipTest", - "skip", - "skipIf", - "skipUnless", - "expectedFailure", - "TextTestResult", - "installHandler", - "registerResult", - "removeResult", - "removeHandler", - "addModuleCleanup", - "getTestCaseNames", - "makeSuite", - "findTestCases", - ] +if sys.version_info >= (3, 11): + from .case import doModuleCleanups as doModuleCleanups, enterModuleContext as enterModuleContext -else: - __all__ = [ - "TestResult", - "TestCase", - "TestSuite", - "TextTestRunner", - "TestLoader", - "FunctionTestCase", - "main", - "defaultTestLoader", - "SkipTest", - "skip", - "skipIf", - "skipUnless", - "expectedFailure", - "TextTestResult", - "installHandler", - "registerResult", - "removeResult", - "removeHandler", - "getTestCaseNames", - "makeSuite", - "findTestCases", - ] +__all__ = [ + "TestResult", + "TestCase", + "TestSuite", + "TextTestRunner", + "TestLoader", + "FunctionTestCase", + "main", + "defaultTestLoader", + "SkipTest", + "skip", + "skipIf", + "skipUnless", + "expectedFailure", + "TextTestResult", + "installHandler", + "registerResult", + "removeResult", + "removeHandler", + "getTestCaseNames", + "makeSuite", + "findTestCases", +] + +if sys.version_info >= (3, 8): + __all__ += ["addModuleCleanup", "IsolatedAsyncioTestCase"] + +if sys.version_info >= (3, 11): + __all__ += ["enterModuleContext", "doModuleCleanups"] def load_tests(loader: TestLoader, tests: TestSuite, pattern: str | None) -> TestSuite: ... diff --git a/mypy/typeshed/stdlib/unittest/async_case.pyi b/mypy/typeshed/stdlib/unittest/async_case.pyi index 55407ec3f1c8..c1de205fbd55 100644 --- a/mypy/typeshed/stdlib/unittest/async_case.pyi +++ b/mypy/typeshed/stdlib/unittest/async_case.pyi @@ -1,11 +1,19 @@ +import sys from collections.abc import Awaitable, Callable +from typing import TypeVar from typing_extensions import ParamSpec from .case import TestCase +if sys.version_info >= (3, 11): + from contextlib import AbstractAsyncContextManager + +_T = TypeVar("_T") _P = ParamSpec("_P") class IsolatedAsyncioTestCase(TestCase): async def asyncSetUp(self) -> None: ... async def asyncTearDown(self) -> None: ... def addAsyncCleanup(self, __func: Callable[_P, Awaitable[object]], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + if sys.version_info >= (3, 11): + async def enterAsyncContext(self, cm: AbstractAsyncContextManager[_T]) -> _T: ... diff --git a/mypy/typeshed/stdlib/unittest/case.pyi b/mypy/typeshed/stdlib/unittest/case.pyi index 578bd6d6f271..15b573edeebb 100644 --- a/mypy/typeshed/stdlib/unittest/case.pyi +++ b/mypy/typeshed/stdlib/unittest/case.pyi @@ -1,18 +1,32 @@ -import datetime import logging import sys import unittest.result -from _typeshed import Self +from _typeshed import Self, SupportsDunderGE, SupportsSub from collections.abc import Callable, Container, Iterable, Mapping, Sequence, Set as AbstractSet from contextlib import AbstractContextManager from types import TracebackType -from typing import Any, AnyStr, ClassVar, Generic, NamedTuple, NoReturn, Pattern, TypeVar, overload +from typing import ( + Any, + AnyStr, + ClassVar, + Generic, + NamedTuple, + NoReturn, + Pattern, + Protocol, + SupportsAbs, + SupportsRound, + TypeVar, + overload, +) from typing_extensions import ParamSpec from warnings import WarningMessage if sys.version_info >= (3, 9): from types import GenericAlias +_T = TypeVar("_T") +_S = TypeVar("_S", bound=SupportsSub[Any, Any]) _E = TypeVar("_E", bound=BaseException) _FT = TypeVar("_FT", bound=Callable[..., Any]) _P = ParamSpec("_P") @@ -50,6 +64,9 @@ if sys.version_info >= (3, 8): def addModuleCleanup(__function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... def doModuleCleanups() -> None: ... +if sys.version_info >= (3, 11): + def enterModuleContext(cm: AbstractContextManager[_T]) -> _T: ... + def expectedFailure(test_item: _FT) -> _FT: ... def skip(reason: str) -> Callable[[_FT], _FT]: ... def skipIf(condition: object, reason: str) -> Callable[[_FT], _FT]: ... @@ -58,6 +75,8 @@ def skipUnless(condition: object, reason: str) -> Callable[[_FT], _FT]: ... class SkipTest(Exception): def __init__(self, reason: str) -> None: ... +class _SupportsAbsAndDunderGE(SupportsDunderGE, SupportsAbs[Any], Protocol): ... + class TestCase: failureException: type[BaseException] longMessage: bool @@ -79,7 +98,9 @@ class TestCase: def skipTest(self, reason: Any) -> None: ... def subTest(self, msg: Any = ..., **params: Any) -> AbstractContextManager[None]: ... def debug(self) -> None: ... - def _addSkip(self, result: unittest.result.TestResult, test_case: TestCase, reason: str) -> None: ... + if sys.version_info < (3, 11): + def _addSkip(self, result: unittest.result.TestResult, test_case: TestCase, reason: str) -> None: ... + def assertEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... def assertNotEqual(self, first: Any, second: Any, msg: Any = ...) -> None: ... def assertTrue(self, expr: Any, msg: Any = ...) -> None: ... @@ -159,33 +180,35 @@ class TestCase: self, logger: str | logging.Logger | None = ..., level: int | str | None = ... ) -> _AssertLogsContext[None]: ... + @overload + def assertAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: ... @overload def assertAlmostEqual( - self, first: float, second: float, places: int | None = ..., msg: Any = ..., delta: float | None = ... + self, first: _S, second: _S, places: None = ..., msg: Any = ..., *, delta: _SupportsAbsAndDunderGE ) -> None: ... @overload def assertAlmostEqual( self, - first: datetime.datetime, - second: datetime.datetime, + first: SupportsSub[_T, SupportsAbs[SupportsRound[object]]], + second: _T, places: int | None = ..., msg: Any = ..., - delta: datetime.timedelta | None = ..., + delta: None = ..., ) -> None: ... @overload - def assertNotAlmostEqual(self, first: float, second: float, *, msg: Any = ...) -> None: ... - @overload - def assertNotAlmostEqual(self, first: float, second: float, places: int | None = ..., msg: Any = ...) -> None: ... + def assertNotAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: ... @overload - def assertNotAlmostEqual(self, first: float, second: float, *, msg: Any = ..., delta: float | None = ...) -> None: ... + def assertNotAlmostEqual( + self, first: _S, second: _S, places: None = ..., msg: Any = ..., *, delta: _SupportsAbsAndDunderGE + ) -> None: ... @overload def assertNotAlmostEqual( self, - first: datetime.datetime, - second: datetime.datetime, + first: SupportsSub[_T, SupportsAbs[SupportsRound[object]]], + second: _T, places: int | None = ..., msg: Any = ..., - delta: datetime.timedelta | None = ..., + delta: None = ..., ) -> None: ... def assertRegex(self, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... def assertNotRegex(self, text: AnyStr, unexpected_regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... @@ -209,6 +232,9 @@ class TestCase: else: def addCleanup(self, function: Callable[_P, object], *args: _P.args, **kwargs: _P.kwargs) -> None: ... + if sys.version_info >= (3, 11): + def enterContext(self, cm: AbstractContextManager[_T]) -> _T: ... + def doCleanups(self) -> None: ... if sys.version_info >= (3, 8): @classmethod @@ -216,6 +242,10 @@ class TestCase: @classmethod def doClassCleanups(cls) -> None: ... + if sys.version_info >= (3, 11): + @classmethod + def enterClassContext(cls, cm: AbstractContextManager[_T]) -> _T: ... + def _formatMessage(self, msg: str | None, standardMsg: str) -> str: ... # undocumented def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ... # undocumented if sys.version_info < (3, 12): @@ -236,14 +266,10 @@ class TestCase: ) -> None: ... @overload def failUnlessRaises(self, exception: type[_E] | tuple[type[_E], ...], msg: Any = ...) -> _AssertRaisesContext[_E]: ... - def failUnlessAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... - def assertAlmostEquals( - self, first: float, second: float, places: int = ..., msg: Any = ..., delta: float = ... - ) -> None: ... - def failIfAlmostEqual(self, first: float, second: float, places: int = ..., msg: Any = ...) -> None: ... - def assertNotAlmostEquals( - self, first: float, second: float, places: int = ..., msg: Any = ..., delta: float = ... - ) -> None: ... + failUnlessAlmostEqual = assertAlmostEqual + assertAlmostEquals = assertAlmostEqual + failIfAlmostEqual = assertNotAlmostEqual + assertNotAlmostEquals = assertNotAlmostEqual def assertRegexpMatches(self, text: AnyStr, regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... def assertNotRegexpMatches(self, text: AnyStr, regex: AnyStr | Pattern[AnyStr], msg: Any = ...) -> None: ... @overload diff --git a/mypy/typeshed/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi index 400bdaac3b41..a7111ff2d090 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -440,7 +440,13 @@ class _SpecState: def mock_open(mock: Any | None = ..., read_data: Any = ...) -> Any: ... -PropertyMock = Any +class PropertyMock(Mock): + if sys.version_info >= (3, 8): + def __get__(self: Self, obj: _T, obj_type: type[_T] | None = ...) -> Self: ... + else: + def __get__(self: Self, obj: _T, obj_type: type[_T] | None) -> Self: ... + + def __set__(self, obj: Any, value: Any) -> None: ... if sys.version_info >= (3, 7): def seal(mock: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/urllib/parse.pyi b/mypy/typeshed/stdlib/urllib/parse.pyi index c6a6836e6e95..49f3825e0821 100644 --- a/mypy/typeshed/stdlib/urllib/parse.pyi +++ b/mypy/typeshed/stdlib/urllib/parse.pyi @@ -39,7 +39,8 @@ non_hierarchical: list[str] uses_query: list[str] uses_fragment: list[str] scheme_chars: str -MAX_CACHE_SIZE: int +if sys.version_info < (3, 11): + MAX_CACHE_SIZE: int class _ResultMixinBase(Generic[AnyStr]): def geturl(self) -> AnyStr: ... diff --git a/mypy/typeshed/stdlib/urllib/request.pyi b/mypy/typeshed/stdlib/urllib/request.pyi index 5e6dde01480a..02ad1bd30052 100644 --- a/mypy/typeshed/stdlib/urllib/request.pyi +++ b/mypy/typeshed/stdlib/urllib/request.pyi @@ -150,6 +150,10 @@ class HTTPRedirectHandler(BaseHandler): def http_error_302(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... def http_error_303(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... def http_error_307(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... + if sys.version_info >= (3, 11): + def http_error_308( + self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage + ) -> _UrlopenRet | None: ... class HTTPCookieProcessor(BaseHandler): cookiejar: CookieJar @@ -330,6 +334,11 @@ class FancyURLopener(URLopener): def http_error_307( self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: bytes | None = ... ) -> _UrlopenRet | addinfourl | None: ... # undocumented + if sys.version_info >= (3, 11): + def http_error_308( + self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: bytes | None = ... + ) -> _UrlopenRet | addinfourl | None: ... # undocumented + def http_error_401( self, url: str, diff --git a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi index dacb6fffcc6b..82cd735bd829 100644 --- a/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi +++ b/mypy/typeshed/stdlib/xml/etree/ElementTree.pyi @@ -1,92 +1,41 @@ import sys +from _collections_abc import dict_keys from _typeshed import FileDescriptor, StrOrBytesPath, SupportsRead, SupportsWrite -from collections.abc import Callable, Generator, ItemsView, Iterable, Iterator, KeysView, Mapping, MutableSequence, Sequence +from collections.abc import Callable, Generator, ItemsView, Iterable, Iterator, Mapping, Sequence from typing import Any, TypeVar, overload from typing_extensions import Literal, SupportsIndex, TypeAlias, TypeGuard +__all__ = [ + "Comment", + "dump", + "Element", + "ElementTree", + "fromstring", + "fromstringlist", + "iselement", + "iterparse", + "parse", + "ParseError", + "PI", + "ProcessingInstruction", + "QName", + "SubElement", + "tostring", + "tostringlist", + "TreeBuilder", + "VERSION", + "XML", + "XMLID", + "XMLParser", + "XMLPullParser", + "register_namespace", +] + +if sys.version_info >= (3, 8): + __all__ += ["C14NWriterTarget", "canonicalize"] + if sys.version_info >= (3, 9): - __all__ = [ - "Comment", - "dump", - "Element", - "ElementTree", - "fromstring", - "fromstringlist", - "indent", - "iselement", - "iterparse", - "parse", - "ParseError", - "PI", - "ProcessingInstruction", - "QName", - "SubElement", - "tostring", - "tostringlist", - "TreeBuilder", - "VERSION", - "XML", - "XMLID", - "XMLParser", - "XMLPullParser", - "register_namespace", - "canonicalize", - "C14NWriterTarget", - ] -elif sys.version_info >= (3, 8): - __all__ = [ - "Comment", - "dump", - "Element", - "ElementTree", - "fromstring", - "fromstringlist", - "iselement", - "iterparse", - "parse", - "ParseError", - "PI", - "ProcessingInstruction", - "QName", - "SubElement", - "tostring", - "tostringlist", - "TreeBuilder", - "VERSION", - "XML", - "XMLID", - "XMLParser", - "XMLPullParser", - "register_namespace", - "canonicalize", - "C14NWriterTarget", - ] -else: - __all__ = [ - "Comment", - "dump", - "Element", - "ElementTree", - "fromstring", - "fromstringlist", - "iselement", - "iterparse", - "parse", - "ParseError", - "PI", - "ProcessingInstruction", - "QName", - "SubElement", - "tostring", - "tostringlist", - "TreeBuilder", - "VERSION", - "XML", - "XMLID", - "XMLParser", - "XMLPullParser", - "register_namespace", - ] + __all__ += ["indent"] _T = TypeVar("_T") _FileRead: TypeAlias = StrOrBytesPath | FileDescriptor | SupportsRead[bytes] | SupportsRead[str] @@ -132,7 +81,7 @@ if sys.version_info >= (3, 8): exclude_tags: Iterable[str] | None = ..., ) -> None: ... -class Element(MutableSequence[Element]): +class Element: tag: str attrib: dict[str, str] text: str | None @@ -156,7 +105,7 @@ class Element(MutableSequence[Element]): def iter(self, tag: str | None = ...) -> Generator[Element, None, None]: ... def iterfind(self, path: str, namespaces: dict[str, str] | None = ...) -> Generator[Element, None, None]: ... def itertext(self) -> Generator[str, None, None]: ... - def keys(self) -> KeysView[str]: ... + def keys(self) -> dict_keys[str, str]: ... # makeelement returns the type of self in Python impl, but not in C impl def makeelement(self, __tag: str, __attrib: dict[str, str]) -> Element: ... def remove(self, __subelement: Element) -> None: ... @@ -167,8 +116,10 @@ class Element(MutableSequence[Element]): @overload def __getitem__(self, __i: SupportsIndex) -> Element: ... @overload - def __getitem__(self, __s: slice) -> MutableSequence[Element]: ... + def __getitem__(self, __s: slice) -> list[Element]: ... def __len__(self) -> int: ... + # Doesn't actually exist at runtime, but instance of the class are indeed iterable due to __getitem__. + def __iter__(self) -> Iterator[Element]: ... @overload def __setitem__(self, __i: SupportsIndex, __o: Element) -> None: ... @overload @@ -194,7 +145,7 @@ class QName: class ElementTree: def __init__(self, element: Element | None = ..., file: _FileRead | None = ...) -> None: ... - def getroot(self) -> Element: ... + def getroot(self) -> Element | Any: ... def parse(self, source: _FileRead, parser: XMLParser | None = ...) -> Element: ... def iter(self, tag: str | None = ...) -> Generator[Element, None, None]: ... if sys.version_info < (3, 9): @@ -321,7 +272,9 @@ class XMLPullParser: def __init__(self, events: Sequence[str] | None = ..., *, _parser: XMLParser | None = ...) -> None: ... def feed(self, data: str | bytes) -> None: ... def close(self) -> None: ... - def read_events(self) -> Iterator[tuple[str, Element]]: ... + # Second element in the tuple could be `Element`, `tuple[str, str]` or `None`. + # Use `Any` to avoid false-positive errors. + def read_events(self) -> Iterator[tuple[str, Any]]: ... def XML(text: str | bytes, parser: XMLParser | None = ...) -> Element: ... def XMLID(text: str | bytes, parser: XMLParser | None = ...) -> tuple[Element, dict[str, Element]]: ... diff --git a/mypy/typeshed/stdlib/xml/sax/handler.pyi b/mypy/typeshed/stdlib/xml/sax/handler.pyi index 3a5193300981..abf124f836cd 100644 --- a/mypy/typeshed/stdlib/xml/sax/handler.pyi +++ b/mypy/typeshed/stdlib/xml/sax/handler.pyi @@ -1,6 +1,6 @@ -from typing import Any +import sys -version: Any +version: str class ErrorHandler: def error(self, exception): ... @@ -30,17 +30,25 @@ class DTDHandler: class EntityResolver: def resolveEntity(self, publicId, systemId): ... -feature_namespaces: Any -feature_namespace_prefixes: Any -feature_string_interning: Any -feature_validation: Any -feature_external_ges: Any -feature_external_pes: Any -all_features: Any -property_lexical_handler: Any -property_declaration_handler: Any -property_dom_node: Any -property_xml_string: Any -property_encoding: Any -property_interning_dict: Any -all_properties: Any +feature_namespaces: str +feature_namespace_prefixes: str +feature_string_interning: str +feature_validation: str +feature_external_ges: str +feature_external_pes: str +all_features: list[str] +property_lexical_handler: str +property_declaration_handler: str +property_dom_node: str +property_xml_string: str +property_encoding: str +property_interning_dict: str +all_properties: list[str] + +if sys.version_info >= (3, 10): + class LexicalHandler: + def comment(self, content: str) -> object: ... + def startDTD(self, name: str, public_id: str | None, system_id: str | None) -> object: ... + def endDTD(self) -> object: ... + def startCDATA(self) -> object: ... + def endCDATA(self) -> object: ... diff --git a/mypy/typeshed/stdlib/xmlrpc/server.pyi b/mypy/typeshed/stdlib/xmlrpc/server.pyi index 371f1821b29d..237620f70250 100644 --- a/mypy/typeshed/stdlib/xmlrpc/server.pyi +++ b/mypy/typeshed/stdlib/xmlrpc/server.pyi @@ -4,7 +4,7 @@ import socketserver import sys from collections.abc import Callable, Iterable, Mapping from datetime import datetime -from typing import Any, Pattern, Protocol +from typing import Any, ClassVar, Pattern, Protocol from typing_extensions import TypeAlias from xmlrpc.client import Fault @@ -68,8 +68,7 @@ class SimpleXMLRPCDispatcher: # undocumented def _dispatch(self, method: str, params: Iterable[_Marshallable]) -> _Marshallable: ... # undocumented class SimpleXMLRPCRequestHandler(http.server.BaseHTTPRequestHandler): - - rpc_paths: tuple[str, str] + rpc_paths: ClassVar[tuple[str, ...]] encode_threshold: int # undocumented aepattern: Pattern[str] # undocumented def accept_encodings(self) -> dict[str, float]: ... diff --git a/mypy/typeshed/stdlib/zipfile.pyi b/mypy/typeshed/stdlib/zipfile.pyi index 276f8df82a6d..c799cf9b4e12 100644 --- a/mypy/typeshed/stdlib/zipfile.pyi +++ b/mypy/typeshed/stdlib/zipfile.pyi @@ -7,37 +7,23 @@ from types import TracebackType from typing import IO, Any, Protocol, overload from typing_extensions import Literal, TypeAlias +__all__ = [ + "BadZipFile", + "BadZipfile", + "error", + "ZIP_STORED", + "ZIP_DEFLATED", + "ZIP_BZIP2", + "ZIP_LZMA", + "is_zipfile", + "ZipInfo", + "ZipFile", + "PyZipFile", + "LargeZipFile", +] + if sys.version_info >= (3, 8): - __all__ = [ - "BadZipFile", - "BadZipfile", - "error", - "ZIP_STORED", - "ZIP_DEFLATED", - "ZIP_BZIP2", - "ZIP_LZMA", - "is_zipfile", - "ZipInfo", - "ZipFile", - "PyZipFile", - "LargeZipFile", - "Path", - ] -else: - __all__ = [ - "BadZipFile", - "BadZipfile", - "error", - "ZIP_STORED", - "ZIP_DEFLATED", - "ZIP_BZIP2", - "ZIP_LZMA", - "is_zipfile", - "ZipInfo", - "ZipFile", - "PyZipFile", - "LargeZipFile", - ] + __all__ += ["Path"] _DateTuple: TypeAlias = tuple[int, int, int, int, int, int] _ReadWriteMode: TypeAlias = Literal["r", "w"] @@ -158,7 +144,32 @@ class ZipFile: compresslevel: int | None # undocumented mode: _ZipFileMode # undocumented pwd: str | None # undocumented - if sys.version_info >= (3, 8): + if sys.version_info >= (3, 11): + @overload + def __init__( + self, + file: StrPath | IO[bytes], + mode: Literal["r"] = ..., + compression: int = ..., + allowZip64: bool = ..., + compresslevel: int | None = ..., + *, + strict_timestamps: bool = ..., + metadata_encoding: str | None, + ) -> None: ... + @overload + def __init__( + self, + file: StrPath | IO[bytes], + mode: _ZipFileMode = ..., + compression: int = ..., + allowZip64: bool = ..., + compresslevel: int | None = ..., + *, + strict_timestamps: bool = ..., + metadata_encoding: None = ..., + ) -> None: ... + elif sys.version_info >= (3, 8): def __init__( self, file: StrPath | IO[bytes], @@ -223,7 +234,7 @@ class ZipFile: else: def writestr(self, zinfo_or_arcname: str | ZipInfo, data: bytes | str, compress_type: int | None = ...) -> None: ... if sys.version_info >= (3, 11): - def mkdir(self, zinfo_or_directory: str | ZipInfo, mode: int = ...) -> None: ... + def mkdir(self, zinfo_or_directory_name: str | ZipInfo, mode: int = ...) -> None: ... class PyZipFile(ZipFile): def __init__( @@ -275,6 +286,13 @@ if sys.version_info >= (3, 8): if sys.version_info >= (3, 10): @property def filename(self) -> PathLike[str]: ... # undocumented + if sys.version_info >= (3, 11): + @property + def suffix(self) -> str: ... + @property + def suffixes(self) -> list[str]: ... + @property + def stem(self) -> str: ... def __init__(self, root: ZipFile | StrPath | IO[bytes], at: str = ...) -> None: ... if sys.version_info >= (3, 9): diff --git a/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi b/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi index 412c3cb15142..bf8d72ba8393 100644 --- a/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi +++ b/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi @@ -1,7 +1,7 @@ import abc -from _typeshed import Self -from collections.abc import Callable, ItemsView, KeysView, Mapping, ValuesView -from typing import Any, Generic, TypeVar +from _typeshed import IdentityFunction, Self +from collections.abc import ItemsView, KeysView, Mapping, ValuesView +from typing import Any, Generic, TypeVar, overload _T = TypeVar("_T") _U = TypeVar("_U") @@ -21,12 +21,30 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): def __delitem__(self, k: NoReturn) -> None: ... def TypedDict(typename: str, fields: dict[str, type[Any]], total: bool = ...) -> type[dict[str, Any]]: ... -def Arg(type: _T = ..., name: str | None = ...) -> _T: ... -def DefaultArg(type: _T = ..., name: str | None = ...) -> _T: ... -def NamedArg(type: _T = ..., name: str | None = ...) -> _T: ... -def DefaultNamedArg(type: _T = ..., name: str | None = ...) -> _T: ... -def VarArg(type: _T = ...) -> _T: ... -def KwArg(type: _T = ...) -> _T: ... +@overload +def Arg(type: _T, name: str | None = ...) -> _T: ... +@overload +def Arg(*, name: str | None = ...) -> Any: ... +@overload +def DefaultArg(type: _T, name: str | None = ...) -> _T: ... +@overload +def DefaultArg(*, name: str | None = ...) -> Any: ... +@overload +def NamedArg(type: _T, name: str | None = ...) -> _T: ... +@overload +def NamedArg(*, name: str | None = ...) -> Any: ... +@overload +def DefaultNamedArg(type: _T, name: str | None = ...) -> _T: ... +@overload +def DefaultNamedArg(*, name: str | None = ...) -> Any: ... +@overload +def VarArg(type: _T) -> _T: ... +@overload +def VarArg() -> Any: ... +@overload +def KwArg(type: _T) -> _T: ... +@overload +def KwArg() -> Any: ... # Return type that indicates a function does not return. # Deprecated: Use typing.NoReturn instead. @@ -36,6 +54,6 @@ class NoReturn: ... # a class decorator, but mypy does not support type[_T] for abstract # classes until this issue is resolved, https://github.com/python/mypy/issues/4717. def trait(cls: _T) -> _T: ... -def mypyc_attr(*attrs: str, **kwattrs: object) -> Callable[[_T], _T]: ... +def mypyc_attr(*attrs: str, **kwattrs: object) -> IdentityFunction: ... class FlexibleAlias(Generic[_T, _U]): ... From 3265bb4dda6d7194d5b8ced7e3925ba4d5250a94 Mon Sep 17 00:00:00 2001 From: hauntsaninja <> Date: Tue, 14 Jun 2022 13:41:20 -0700 Subject: [PATCH 2/2] fix tests --- test-data/unit/cmdline.test | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test-data/unit/cmdline.test b/test-data/unit/cmdline.test index 016d215027ae..3b3b64c038c1 100644 --- a/test-data/unit/cmdline.test +++ b/test-data/unit/cmdline.test @@ -335,11 +335,11 @@ file.py:6: error: Argument 1 to "foo" has incompatible type "str"; expected "int \[mypy-x] ignore_errors = True [file x.py] -"" + 0 +x: str = 5 [file y.py] -"" + 0 +x: str = 5 [out] -y.py:1: error: Unsupported operand types for + ("str" and "int") +y.py:1: error: Incompatible types in assignment (expression has type "int", variable has type "str") [case testConfigFollowImportsNormal] # cmd: mypy main.py @@ -840,19 +840,19 @@ src/anamespace/foo/bar.py:2: error: Incompatible return value type (got "int", e x = 0 # type: str [file pkg/a1/b/f.py] from pkg.a1.b.c.d.e import x -x + 1 +x() [file pkg/a2/__init__.py] [file pkg/a2/b/c/d/e.py] x = 0 # type: str [file pkg/a2/b/f.py] from pkg.a2.b.c.d.e import x -x + 1 +x() [out] pkg/a2/b/c/d/e.py:1: error: Incompatible types in assignment (expression has type "int", variable has type "str") pkg/a1/b/c/d/e.py:1: error: Incompatible types in assignment (expression has type "int", variable has type "str") -pkg/a2/b/f.py:2: error: Unsupported operand types for + ("str" and "int") -pkg/a1/b/f.py:2: error: Unsupported operand types for + ("str" and "int") +pkg/a2/b/f.py:2: error: "str" not callable +pkg/a1/b/f.py:2: error: "str" not callable [case testFollowImportStubs1] # cmd: mypy main.py