From da8819cf2353fd5592de9b045c08af56a7151007 Mon Sep 17 00:00:00 2001 From: Jared Hance Date: Thu, 11 Aug 2022 09:49:55 -0700 Subject: [PATCH 1/3] Sync typeshed Source commit: https://github.com/python/typeshed/commit/a92da58328aa259184ff45bb7408e82426fb563e --- mypy/typeshed/stdlib/_compression.pyi | 4 - mypy/typeshed/stdlib/_decimal.pyi | 9 +- mypy/typeshed/stdlib/_dummy_thread.pyi | 1 - mypy/typeshed/stdlib/_markupbase.pyi | 1 - mypy/typeshed/stdlib/_threading_local.pyi | 2 - mypy/typeshed/stdlib/_weakref.pyi | 1 - mypy/typeshed/stdlib/_weakrefset.pyi | 2 - mypy/typeshed/stdlib/array.pyi | 2 - mypy/typeshed/stdlib/ast.pyi | 14 +- mypy/typeshed/stdlib/asynchat.pyi | 7 - .../stdlib/asyncio/base_subprocess.pyi | 14 +- mypy/typeshed/stdlib/asyncio/events.pyi | 2 - mypy/typeshed/stdlib/asyncio/locks.pyi | 6 +- .../stdlib/asyncio/proactor_events.pyi | 31 +-- mypy/typeshed/stdlib/asyncio/sslproto.pyi | 15 -- mypy/typeshed/stdlib/asyncio/streams.pyi | 4 - mypy/typeshed/stdlib/asyncio/subprocess.pyi | 3 - mypy/typeshed/stdlib/asyncio/tasks.pyi | 4 - mypy/typeshed/stdlib/asyncio/transports.pyi | 3 - mypy/typeshed/stdlib/asyncio/unix_events.pyi | 3 - mypy/typeshed/stdlib/asyncore.pyi | 2 - mypy/typeshed/stdlib/builtins.pyi | 194 ++++++++++++++---- mypy/typeshed/stdlib/codecs.pyi | 2 +- mypy/typeshed/stdlib/collections/__init__.pyi | 8 +- .../stdlib/concurrent/futures/__init__.pyi | 2 + .../stdlib/concurrent/futures/_base.pyi | 13 +- mypy/typeshed/stdlib/contextlib.pyi | 29 ++- mypy/typeshed/stdlib/ctypes/__init__.pyi | 13 +- mypy/typeshed/stdlib/ctypes/wintypes.pyi | 104 +++++----- mypy/typeshed/stdlib/curses/__init__.pyi | 9 +- mypy/typeshed/stdlib/curses/has_key.pyi | 4 + mypy/typeshed/stdlib/datetime.pyi | 4 - mypy/typeshed/stdlib/doctest.pyi | 3 - mypy/typeshed/stdlib/email/__init__.pyi | 4 +- mypy/typeshed/stdlib/email/headerregistry.pyi | 14 +- mypy/typeshed/stdlib/enum.pyi | 4 +- mypy/typeshed/stdlib/http/client.pyi | 14 +- mypy/typeshed/stdlib/importlib/abc.pyi | 3 - .../stdlib/importlib/metadata/_meta.pyi | 9 +- mypy/typeshed/stdlib/io.pyi | 3 +- mypy/typeshed/stdlib/ipaddress.pyi | 1 - .../stdlib/lib2to3/pgen2/__init__.pyi | 8 + mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi | 3 +- mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi | 3 +- mypy/typeshed/stdlib/lib2to3/pytree.pyi | 5 +- .../stdlib/multiprocessing/__init__.pyi | 33 +-- .../stdlib/multiprocessing/context.pyi | 54 +++-- mypy/typeshed/stdlib/multiprocessing/heap.pyi | 36 ++++ .../stdlib/multiprocessing/managers.pyi | 8 +- .../stdlib/multiprocessing/popen_fork.pyi | 23 +++ .../multiprocessing/popen_forkserver.pyi | 22 ++ .../multiprocessing/popen_spawn_posix.pyi | 24 +++ .../multiprocessing/popen_spawn_win32.pyi | 30 +++ .../stdlib/multiprocessing/reduction.pyi | 12 +- .../multiprocessing/resource_sharer.pyi | 20 ++ mypy/typeshed/stdlib/multiprocessing/util.pyi | 87 ++++++++ mypy/typeshed/stdlib/pathlib.pyi | 1 - mypy/typeshed/stdlib/plistlib.pyi | 1 - mypy/typeshed/stdlib/re.pyi | 124 ++++++++++- mypy/typeshed/stdlib/sqlite3/dbapi2.pyi | 2 - mypy/typeshed/stdlib/statistics.pyi | 1 - mypy/typeshed/stdlib/sys.pyi | 2 +- mypy/typeshed/stdlib/tkinter/__init__.pyi | 172 ++++++++-------- mypy/typeshed/stdlib/tkinter/colorchooser.pyi | 4 +- mypy/typeshed/stdlib/tkinter/commondialog.pyi | 11 +- mypy/typeshed/stdlib/tkinter/dialog.pyi | 3 +- mypy/typeshed/stdlib/tkinter/filedialog.pyi | 28 +-- mypy/typeshed/stdlib/tkinter/messagebox.pyi | 18 +- mypy/typeshed/stdlib/tkinter/scrolledtext.pyi | 3 +- mypy/typeshed/stdlib/tkinter/tix.pyi | 121 +++++------ mypy/typeshed/stdlib/tkinter/ttk.pyi | 123 ++++++----- mypy/typeshed/stdlib/traceback.pyi | 16 +- mypy/typeshed/stdlib/types.pyi | 6 +- mypy/typeshed/stdlib/typing.pyi | 170 +++------------ mypy/typeshed/stdlib/typing_extensions.pyi | 21 +- mypy/typeshed/stdlib/unittest/__init__.pyi | 1 + mypy/typeshed/stdlib/unittest/mock.pyi | 1 + mypy/typeshed/stdlib/urllib/request.pyi | 14 +- mypy/typeshed/stdlib/xml/dom/minidom.pyi | 3 +- mypy/typeshed/stdlib/zoneinfo/__init__.pyi | 2 + .../stubs/mypy-extensions/mypy_extensions.pyi | 11 +- 81 files changed, 1043 insertions(+), 751 deletions(-) create mode 100644 mypy/typeshed/stdlib/curses/has_key.pyi create mode 100644 mypy/typeshed/stdlib/multiprocessing/heap.pyi create mode 100644 mypy/typeshed/stdlib/multiprocessing/popen_fork.pyi create mode 100644 mypy/typeshed/stdlib/multiprocessing/popen_forkserver.pyi create mode 100644 mypy/typeshed/stdlib/multiprocessing/popen_spawn_posix.pyi create mode 100644 mypy/typeshed/stdlib/multiprocessing/popen_spawn_win32.pyi create mode 100644 mypy/typeshed/stdlib/multiprocessing/resource_sharer.pyi create mode 100644 mypy/typeshed/stdlib/multiprocessing/util.pyi diff --git a/mypy/typeshed/stdlib/_compression.pyi b/mypy/typeshed/stdlib/_compression.pyi index ec3c7fe70856..7047a7bcd325 100644 --- a/mypy/typeshed/stdlib/_compression.pyi +++ b/mypy/typeshed/stdlib/_compression.pyi @@ -20,10 +20,6 @@ class DecompressReader(RawIOBase): trailing_error: type[Exception] | tuple[type[Exception], ...] = ..., **decomp_args: Any, ) -> None: ... - def readable(self) -> bool: ... - def close(self) -> None: ... - def seekable(self) -> bool: ... def readinto(self, b: WriteableBuffer) -> int: ... def read(self, size: int = ...) -> bytes: ... def seek(self, offset: int, whence: int = ...) -> int: ... - def tell(self) -> int: ... diff --git a/mypy/typeshed/stdlib/_decimal.pyi b/mypy/typeshed/stdlib/_decimal.pyi index 71dff44658be..50c0f23734cd 100644 --- a/mypy/typeshed/stdlib/_decimal.pyi +++ b/mypy/typeshed/stdlib/_decimal.pyi @@ -74,7 +74,6 @@ class Decimal: def from_float(cls: type[Self], __f: float) -> Self: ... def __bool__(self) -> bool: ... def compare(self, other: _Decimal, context: Context | None = ...) -> Decimal: ... - def __hash__(self) -> int: ... def as_tuple(self) -> DecimalTuple: ... def as_integer_ratio(self) -> tuple[int, int]: ... def to_eng_string(self, context: Context | None = ...) -> str: ... @@ -179,6 +178,11 @@ class _ContextManager: _TrapType: TypeAlias = type[DecimalException] class Context: + # TODO: Context doesn't allow you to delete *any* attributes from instances of the class at runtime, + # even settable attributes like `prec` and `rounding`, + # but that's inexpressable in the stub. + # Type checkers either ignore it or misinterpret it + # if you add a `def __delattr__(self, __name: str) -> NoReturn` method to the stub prec: int rounding: str Emin: int @@ -199,9 +203,6 @@ class Context: traps: None | dict[_TrapType, bool] | Container[_TrapType] = ..., _ignored_flags: list[_TrapType] | None = ..., ) -> None: ... - # __setattr__() only allows to set a specific set of attributes, - # already defined above. - def __delattr__(self, __name: str) -> None: ... def __reduce__(self: Self) -> tuple[type[Self], tuple[Any, ...]]: ... def clear_flags(self) -> None: ... def clear_traps(self) -> None: ... diff --git a/mypy/typeshed/stdlib/_dummy_thread.pyi b/mypy/typeshed/stdlib/_dummy_thread.pyi index 463399ca43db..ff16b1d3dcf4 100644 --- a/mypy/typeshed/stdlib/_dummy_thread.pyi +++ b/mypy/typeshed/stdlib/_dummy_thread.pyi @@ -15,7 +15,6 @@ def stack_size(size: int | None = ...) -> int: ... class LockType: locked_status: bool - def __init__(self) -> None: ... def acquire(self, waitflag: bool | None = ..., timeout: int = ...) -> bool: ... def __enter__(self, waitflag: bool | None = ..., timeout: int = ...) -> bool: ... def __exit__(self, typ: type[BaseException] | None, val: BaseException | None, tb: TracebackType | None) -> None: ... diff --git a/mypy/typeshed/stdlib/_markupbase.pyi b/mypy/typeshed/stdlib/_markupbase.pyi index 2c497f65bb43..7d2a39a7aaea 100644 --- a/mypy/typeshed/stdlib/_markupbase.pyi +++ b/mypy/typeshed/stdlib/_markupbase.pyi @@ -2,7 +2,6 @@ import sys from typing import Any class ParserBase: - def __init__(self) -> None: ... def reset(self) -> None: ... def getpos(self) -> tuple[int, int]: ... def unknown_decl(self, data: str) -> None: ... diff --git a/mypy/typeshed/stdlib/_threading_local.pyi b/mypy/typeshed/stdlib/_threading_local.pyi index 17ce1fe349fe..d455ce09227e 100644 --- a/mypy/typeshed/stdlib/_threading_local.pyi +++ b/mypy/typeshed/stdlib/_threading_local.pyi @@ -8,11 +8,9 @@ _LocalDict: TypeAlias = dict[Any, Any] class _localimpl: key: str dicts: dict[int, tuple[ReferenceType[Any], _LocalDict]] - def __init__(self) -> None: ... def get_dict(self) -> _LocalDict: ... def create_dict(self) -> _LocalDict: ... class local: def __getattribute__(self, name: str) -> Any: ... def __setattr__(self, name: str, value: Any) -> None: ... - def __delattr__(self, name: str) -> None: ... diff --git a/mypy/typeshed/stdlib/_weakref.pyi b/mypy/typeshed/stdlib/_weakref.pyi index 329cd0dd6458..742bc3ad9f36 100644 --- a/mypy/typeshed/stdlib/_weakref.pyi +++ b/mypy/typeshed/stdlib/_weakref.pyi @@ -23,7 +23,6 @@ class ReferenceType(Generic[_T]): __callback__: Callable[[ReferenceType[_T]], Any] def __new__(cls: type[Self], o: _T, callback: Callable[[ReferenceType[_T]], Any] | None = ...) -> Self: ... def __call__(self) -> _T | None: ... - def __hash__(self) -> int: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, item: Any) -> GenericAlias: ... diff --git a/mypy/typeshed/stdlib/_weakrefset.pyi b/mypy/typeshed/stdlib/_weakrefset.pyi index 9e9269758b00..da09442e855b 100644 --- a/mypy/typeshed/stdlib/_weakrefset.pyi +++ b/mypy/typeshed/stdlib/_weakrefset.pyi @@ -17,10 +17,8 @@ class WeakSet(MutableSet[_T], Generic[_T]): @overload def __init__(self, data: Iterable[_T]) -> None: ... def add(self, item: _T) -> None: ... - def clear(self) -> None: ... def discard(self, item: _T) -> None: ... def copy(self: Self) -> Self: ... - def pop(self) -> _T: ... def remove(self, item: _T) -> None: ... def update(self, other: Iterable[_T]) -> None: ... def __contains__(self, item: object) -> bool: ... diff --git a/mypy/typeshed/stdlib/array.pyi b/mypy/typeshed/stdlib/array.pyi index 4797bd067008..2d27cd72e8df 100644 --- a/mypy/typeshed/stdlib/array.pyi +++ b/mypy/typeshed/stdlib/array.pyi @@ -47,7 +47,6 @@ class array(MutableSequence[_T], Generic[_T]): def insert(self, __i: int, __v: _T) -> None: ... def pop(self, __i: int = ...) -> _T: ... def remove(self, __v: _T) -> None: ... - def reverse(self) -> None: ... def tobytes(self) -> bytes: ... def tofile(self, __f: SupportsWrite[bytes]) -> None: ... def tolist(self) -> list[_T]: ... @@ -56,7 +55,6 @@ class array(MutableSequence[_T], Generic[_T]): def fromstring(self, __buffer: bytes) -> None: ... def tostring(self) -> bytes: ... - def __contains__(self, __key: object) -> bool: ... def __len__(self) -> int: ... @overload def __getitem__(self, __i: SupportsIndex) -> _T: ... diff --git a/mypy/typeshed/stdlib/ast.pyi b/mypy/typeshed/stdlib/ast.pyi index 3a54d158affd..6c9dbd0162b8 100644 --- a/mypy/typeshed/stdlib/ast.pyi +++ b/mypy/typeshed/stdlib/ast.pyi @@ -5,21 +5,25 @@ from typing import Any, TypeVar, overload from typing_extensions import Literal if sys.version_info >= (3, 8): - class Num(Constant): + class _ABC(type): + if sys.version_info >= (3, 9): + def __init__(cls, *args: object) -> None: ... + + class Num(Constant, metaclass=_ABC): value: complex - class Str(Constant): + class Str(Constant, metaclass=_ABC): value: str # Aliases for value, for backwards compatibility s: str - class Bytes(Constant): + class Bytes(Constant, metaclass=_ABC): value: bytes # Aliases for value, for backwards compatibility s: bytes - class NameConstant(Constant): ... - class Ellipsis(Constant): ... + class NameConstant(Constant, metaclass=_ABC): ... + class Ellipsis(Constant, metaclass=_ABC): ... if sys.version_info >= (3, 9): class slice(AST): ... diff --git a/mypy/typeshed/stdlib/asynchat.pyi b/mypy/typeshed/stdlib/asynchat.pyi index 57254eef13fd..4d43b02c056c 100644 --- a/mypy/typeshed/stdlib/asynchat.pyi +++ b/mypy/typeshed/stdlib/asynchat.pyi @@ -1,5 +1,4 @@ import asyncore -import socket from abc import abstractmethod class simple_producer: @@ -9,20 +8,14 @@ class simple_producer: class async_chat(asyncore.dispatcher): ac_in_buffer_size: int ac_out_buffer_size: int - def __init__(self, sock: socket.socket | None = ..., map: asyncore._MapType | None = ...) -> None: ... @abstractmethod def collect_incoming_data(self, data: bytes) -> None: ... @abstractmethod def found_terminator(self) -> None: ... def set_terminator(self, term: bytes | int | None) -> None: ... def get_terminator(self) -> bytes | int | None: ... - def handle_read(self) -> None: ... - def handle_write(self) -> None: ... - def handle_close(self) -> None: ... def push(self, data: bytes) -> None: ... def push_with_producer(self, producer: simple_producer) -> None: ... - def readable(self) -> bool: ... - def writable(self) -> bool: ... def close_when_done(self) -> None: ... def initiate_send(self) -> None: ... def discard_buffers(self) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi index 44606b6d137c..d3ab16a3edd2 100644 --- a/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/base_subprocess.pyi @@ -44,17 +44,10 @@ class BaseSubprocessTransport(transports.SubprocessTransport): bufsize: int, **kwargs: Any, ) -> None: ... # undocumented - def set_protocol(self, protocol: protocols.BaseProtocol) -> None: ... - def get_protocol(self) -> protocols.BaseProtocol: ... - def is_closing(self) -> bool: ... - def close(self) -> None: ... def get_pid(self) -> int | None: ... # type: ignore[override] - def get_returncode(self) -> int | None: ... def get_pipe_transport(self, fd: int) -> _File: ... # type: ignore[override] def _check_proc(self) -> None: ... # undocumented def send_signal(self, signal: int) -> None: ... # type: ignore[override] - def terminate(self) -> None: ... - def kill(self) -> None: ... async def _connect_pipes(self, waiter: futures.Future[Any] | None) -> None: ... # undocumented def _call(self, cb: Callable[..., object], *data: Any) -> None: ... # undocumented def _pipe_connection_lost(self, fd: int, exc: BaseException | None) -> None: ... # undocumented @@ -66,10 +59,5 @@ class BaseSubprocessTransport(transports.SubprocessTransport): class WriteSubprocessPipeProto(protocols.BaseProtocol): # undocumented def __init__(self, proc: BaseSubprocessTransport, fd: int) -> None: ... - def connection_made(self, transport: transports.BaseTransport) -> None: ... - def connection_lost(self, exc: BaseException | None) -> None: ... - def pause_writing(self) -> None: ... - def resume_writing(self) -> None: ... -class ReadSubprocessPipeProto(WriteSubprocessPipeProto, protocols.Protocol): # undocumented - def data_received(self, data: bytes) -> None: ... +class ReadSubprocessPipeProto(WriteSubprocessPipeProto, protocols.Protocol): ... # undocumented diff --git a/mypy/typeshed/stdlib/asyncio/events.pyi b/mypy/typeshed/stdlib/asyncio/events.pyi index 0eeebbc3ab8f..586116136c1a 100644 --- a/mypy/typeshed/stdlib/asyncio/events.pyi +++ b/mypy/typeshed/stdlib/asyncio/events.pyi @@ -85,7 +85,6 @@ class TimerHandle(Handle): loop: AbstractEventLoop, context: Context | None = ..., ) -> None: ... - def __hash__(self) -> int: ... def when(self) -> float: ... def __lt__(self, other: TimerHandle) -> bool: ... def __le__(self, other: TimerHandle) -> bool: ... @@ -612,7 +611,6 @@ class AbstractEventLoopPolicy: def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy, metaclass=ABCMeta): - def __init__(self) -> None: ... def get_event_loop(self) -> AbstractEventLoop: ... def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ... def new_event_loop(self) -> AbstractEventLoop: ... diff --git a/mypy/typeshed/stdlib/asyncio/locks.pyi b/mypy/typeshed/stdlib/asyncio/locks.pyi index 61f8a81dedc7..a5cdf9aa1184 100644 --- a/mypy/typeshed/stdlib/asyncio/locks.pyi +++ b/mypy/typeshed/stdlib/asyncio/locks.pyi @@ -92,11 +92,7 @@ class Semaphore(_ContextManagerMixin): def release(self) -> None: ... def _wake_up_next(self) -> None: ... -class BoundedSemaphore(Semaphore): - if sys.version_info >= (3, 11): - def __init__(self, value: int = ...) -> None: ... - else: - def __init__(self, value: int = ..., *, loop: AbstractEventLoop | None = ...) -> None: ... +class BoundedSemaphore(Semaphore): ... if sys.version_info >= (3, 11): class _BarrierState(enum.Enum): # undocumented diff --git a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi index 665a885a1773..704939450cc5 100644 --- a/mypy/typeshed/stdlib/asyncio/proactor_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/proactor_events.pyi @@ -1,7 +1,7 @@ import sys from collections.abc import Mapping from socket import socket -from typing import Any, Protocol +from typing import Any, ClassVar, Protocol from typing_extensions import Literal from . import base_events, constants, events, futures, streams, transports @@ -29,8 +29,6 @@ class _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTr else: def __del__(self) -> None: ... - def get_write_buffer_size(self) -> int: ... - class _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTransport): if sys.version_info >= (3, 10): def __init__( @@ -54,33 +52,13 @@ class _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTran server: events.AbstractServer | None = ..., ) -> None: ... -class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport, transports.WriteTransport): - def __init__( - self, - loop: events.AbstractEventLoop, - sock: socket, - protocol: streams.StreamReaderProtocol, - waiter: futures.Future[Any] | None = ..., - extra: Mapping[Any, Any] | None = ..., - server: events.AbstractServer | None = ..., - ) -> None: ... - -class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport): - def __init__( - self, - loop: events.AbstractEventLoop, - sock: socket, - protocol: streams.StreamReaderProtocol, - waiter: futures.Future[Any] | None = ..., - extra: Mapping[Any, Any] | None = ..., - server: events.AbstractServer | None = ..., - ) -> None: ... - +class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport, transports.WriteTransport): ... +class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport): ... class _ProactorDuplexPipeTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): ... class _ProactorSocketTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): - _sendfile_compatible: constants._SendfileMode + _sendfile_compatible: ClassVar[constants._SendfileMode] def __init__( self, loop: events.AbstractEventLoop, @@ -92,7 +70,6 @@ class _ProactorSocketTransport(_ProactorReadPipeTransport, _ProactorBaseWritePip ) -> None: ... def _set_extra(self, sock: socket) -> None: ... def can_write_eof(self) -> Literal[True]: ... - def write_eof(self) -> None: ... class BaseProactorEventLoop(base_events.BaseEventLoop): def __init__(self, proactor: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/asyncio/sslproto.pyi b/mypy/typeshed/stdlib/asyncio/sslproto.pyi index 34414d649297..3bb4db69c123 100644 --- a/mypy/typeshed/stdlib/asyncio/sslproto.pyi +++ b/mypy/typeshed/stdlib/asyncio/sslproto.pyi @@ -72,20 +72,10 @@ class _SSLProtocolTransport(transports._FlowControlMixin, transports.Transport): _closed: bool def __init__(self, loop: events.AbstractEventLoop, ssl_protocol: SSLProtocol) -> None: ... def get_extra_info(self, name: str, default: Any | None = ...) -> dict[str, Any]: ... - def set_protocol(self, protocol: protocols.BaseProtocol) -> None: ... - def get_protocol(self) -> protocols.BaseProtocol: ... - def is_closing(self) -> bool: ... - def close(self) -> None: ... - def is_reading(self) -> bool: ... - def pause_reading(self) -> None: ... - def resume_reading(self) -> None: ... - def set_write_buffer_limits(self, high: int | None = ..., low: int | None = ...) -> None: ... - def get_write_buffer_size(self) -> int: ... @property def _protocol_paused(self) -> bool: ... 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]: ... @@ -149,10 +139,7 @@ class SSLProtocol(_SSLProtocolBase): def _set_app_protocol(self, app_protocol: protocols.BaseProtocol) -> None: ... def _wakeup_waiter(self, exc: BaseException | None = ...) -> None: ... - def connection_made(self, transport: transports.BaseTransport) -> None: ... def connection_lost(self, exc: BaseException | None) -> None: ... - def pause_writing(self) -> None: ... - def resume_writing(self) -> None: ... def eof_received(self) -> None: ... def _get_extra_info(self, name: str, default: Any | None = ...) -> Any: ... def _start_shutdown(self) -> None: ... @@ -167,9 +154,7 @@ class SSLProtocol(_SSLProtocolBase): def _fatal_error(self, exc: BaseException, message: str = ...) -> 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 5bf2d3620dbe..139d86b292c3 100644 --- a/mypy/typeshed/stdlib/asyncio/streams.pyi +++ b/mypy/typeshed/stdlib/asyncio/streams.pyi @@ -128,10 +128,6 @@ class StreamReaderProtocol(FlowControlMixin, protocols.Protocol): client_connected_cb: _ClientConnectedCallback | None = ..., loop: events.AbstractEventLoop | None = ..., ) -> None: ... - def connection_made(self, transport: transports.BaseTransport) -> None: ... - def connection_lost(self, exc: Exception | None) -> None: ... - def data_received(self, data: bytes) -> None: ... - def eof_received(self) -> bool: ... class StreamWriter: def __init__( diff --git a/mypy/typeshed/stdlib/asyncio/subprocess.pyi b/mypy/typeshed/stdlib/asyncio/subprocess.pyi index 5b62c20bd07f..32fcf1a65491 100644 --- a/mypy/typeshed/stdlib/asyncio/subprocess.pyi +++ b/mypy/typeshed/stdlib/asyncio/subprocess.pyi @@ -22,10 +22,7 @@ class SubprocessStreamProtocol(streams.FlowControlMixin, protocols.SubprocessPro stdout: streams.StreamReader | None stderr: streams.StreamReader | None def __init__(self, limit: int, loop: events.AbstractEventLoop) -> None: ... - def connection_made(self, transport: transports.BaseTransport) -> None: ... def pipe_data_received(self, fd: int, data: bytes | str) -> None: ... - def pipe_connection_lost(self, fd: int, exc: Exception | None) -> None: ... - def process_exited(self) -> None: ... class Process: stdin: streams.StreamWriter | None diff --git a/mypy/typeshed/stdlib/asyncio/tasks.pyi b/mypy/typeshed/stdlib/asyncio/tasks.pyi index d919a0299b99..76755f1109c3 100644 --- a/mypy/typeshed/stdlib/asyncio/tasks.pyi +++ b/mypy/typeshed/stdlib/asyncio/tasks.pyi @@ -285,10 +285,6 @@ class Task(Future[_T], Generic[_T]): def get_stack(self, *, limit: int | None = ...) -> list[FrameType]: ... def print_stack(self, *, limit: int | None = ..., file: TextIO | None = ...) -> None: ... - if sys.version_info >= (3, 9): - def cancel(self, msg: Any | None = ...) -> bool: ... - else: - def cancel(self) -> bool: ... if sys.version_info >= (3, 11): def cancelling(self) -> int: ... def uncancel(self) -> int: ... diff --git a/mypy/typeshed/stdlib/asyncio/transports.pyi b/mypy/typeshed/stdlib/asyncio/transports.pyi index be68cad5f894..52937c9bcbdf 100644 --- a/mypy/typeshed/stdlib/asyncio/transports.pyi +++ b/mypy/typeshed/stdlib/asyncio/transports.pyi @@ -45,6 +45,3 @@ class SubprocessTransport(BaseTransport): class _FlowControlMixin(Transport): def __init__(self, extra: Mapping[Any, Any] | None = ..., loop: AbstractEventLoop | None = ...) -> None: ... - def set_write_buffer_limits(self, high: int | None = ..., low: int | None = ...) -> None: ... - def get_write_buffer_size(self) -> int: ... - def get_write_buffer_limits(self) -> tuple[int, int]: ... diff --git a/mypy/typeshed/stdlib/asyncio/unix_events.pyi b/mypy/typeshed/stdlib/asyncio/unix_events.pyi index 54e663ece192..f63011a373be 100644 --- a/mypy/typeshed/stdlib/asyncio/unix_events.pyi +++ b/mypy/typeshed/stdlib/asyncio/unix_events.pyi @@ -57,7 +57,6 @@ if sys.platform != "win32": # Doesn't actually have ABCMeta metaclass at runtime, but mypy complains if we don't have it in the stub. # See discussion in #7412 class BaseChildWatcher(AbstractChildWatcher, metaclass=ABCMeta): - def __init__(self) -> None: ... def close(self) -> None: ... if sys.version_info >= (3, 8): def is_active(self) -> bool: ... @@ -95,7 +94,6 @@ if sys.platform != "win32": ) -> object: ... class MultiLoopChildWatcher(AbstractChildWatcher): - def __init__(self) -> None: ... def is_active(self) -> bool: ... def close(self) -> None: ... def __enter__(self: Self) -> Self: ... @@ -107,7 +105,6 @@ if sys.platform != "win32": def attach_loop(self, loop: AbstractEventLoop | None) -> None: ... class ThreadedChildWatcher(AbstractChildWatcher): - def __init__(self) -> None: ... def is_active(self) -> Literal[True]: ... def close(self) -> None: ... def __enter__(self: Self) -> Self: ... diff --git a/mypy/typeshed/stdlib/asyncore.pyi b/mypy/typeshed/stdlib/asyncore.pyi index 8c3e03bc3eff..0025ec3f9b4e 100644 --- a/mypy/typeshed/stdlib/asyncore.pyi +++ b/mypy/typeshed/stdlib/asyncore.pyi @@ -63,9 +63,7 @@ class dispatcher: def handle_close(self) -> None: ... class dispatcher_with_send(dispatcher): - def __init__(self, sock: socket | None = ..., map: _MapType | None = ...) -> None: ... def initiate_send(self) -> None: ... - def handle_write(self) -> None: ... # incompatible signature: # def send(self, data: bytes) -> int | None: ... diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index e0d584a387fb..1bcd4746c7a3 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -53,8 +53,9 @@ from typing import ( # noqa: Y027 SupportsRound, TypeVar, overload, + type_check_only, ) -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 @@ -296,7 +297,6 @@ class int: def __float__(self) -> float: ... def __int__(self) -> int: ... def __abs__(self) -> int: ... - def __hash__(self) -> int: ... def __bool__(self) -> bool: ... def __index__(self) -> int: ... @@ -360,14 +360,27 @@ class float: def __int__(self) -> int: ... def __float__(self) -> float: ... def __abs__(self) -> float: ... - def __hash__(self) -> int: ... def __bool__(self) -> bool: ... class complex: - @overload - def __new__(cls: type[Self], real: float = ..., imag: float = ...) -> Self: ... - @overload - def __new__(cls: type[Self], real: str | SupportsComplex | SupportsIndex | complex) -> Self: ... + if sys.version_info >= (3, 8): + # Python doesn't currently accept SupportsComplex for the second argument + @overload + def __new__( + cls: type[Self], + real: complex | SupportsComplex | SupportsFloat | SupportsIndex = ..., + imag: complex | SupportsFloat | SupportsIndex = ..., + ) -> Self: ... + @overload + def __new__(cls: type[Self], real: str | SupportsComplex | SupportsFloat | SupportsIndex | complex) -> Self: ... + else: + @overload + def __new__( + cls: type[Self], real: complex | SupportsComplex | SupportsFloat = ..., imag: complex | SupportsFloat = ... + ) -> Self: ... + @overload + def __new__(cls: type[Self], real: str | SupportsComplex | SupportsFloat | complex) -> Self: ... + @property def real(self) -> float: ... @property @@ -388,7 +401,6 @@ class complex: def __neg__(self) -> complex: ... def __pos__(self) -> complex: ... def __abs__(self) -> float: ... - def __hash__(self) -> int: ... def __bool__(self) -> bool: ... if sys.version_info >= (3, 11): def __complex__(self) -> complex: ... @@ -401,21 +413,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: ... @@ -430,55 +460,128 @@ 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: ... def __ge__(self, __x: str) -> bool: ... 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): @@ -568,7 +671,6 @@ class bytes(ByteString): def maketrans(__frm: ReadableBuffer, __to: ReadableBuffer) -> bytes: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[int]: ... - def __hash__(self) -> int: ... @overload def __getitem__(self, __i: SupportsIndex) -> int: ... @overload @@ -837,6 +939,7 @@ class tuple(Sequence[_T_co], Generic[_T_co]): # Doesn't exist at runtime, but deleting this breaks mypy. See #2999 @final +@type_check_only class function: # Make sure this class definition stays roughly in line with `types.FunctionType` @property @@ -920,9 +1023,13 @@ class dict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @overload def __init__(self: dict[str, _VT], **kwargs: _VT) -> None: ... @overload - def __init__(self, __map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... + def __init__(self, __map: SupportsKeysAndGetItem[_KT, _VT]) -> None: ... + @overload + def __init__(self: dict[str, _VT], __map: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ... @overload - def __init__(self, __iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __init__(self: dict[str, _VT], __iterable: Iterable[tuple[str, _VT]], **kwargs: _VT) -> None: ... # Next overload is for dict(string.split(sep) for string in iterable) # Cannot be Iterable[Sequence[_T]] or otherwise dict(["foo", "bar", "baz"]) is not an error @overload @@ -1186,7 +1293,7 @@ class filter(Iterator[_T], Generic[_T]): def __iter__(self: Self) -> Self: ... def __next__(self) -> _T: ... -def format(__value: object, __format_spec: str = ...) -> str: ... # TODO unicode +def format(__value: object, __format_spec: str = ...) -> str: ... @overload def getattr(__o: object, __name: str) -> Any: ... @@ -1668,6 +1775,7 @@ def __build_class__(__func: Callable[[], _Cell | Any], __name: str, *bases: Any, # Actually the type of Ellipsis is , but since it's # not exposed anywhere under that name, we make it private here. @final +@type_check_only class ellipsis: ... Ellipsis: ellipsis diff --git a/mypy/typeshed/stdlib/codecs.pyi b/mypy/typeshed/stdlib/codecs.pyi index 64d1c93ba3a3..a7b60e38df11 100644 --- a/mypy/typeshed/stdlib/codecs.pyi +++ b/mypy/typeshed/stdlib/codecs.pyi @@ -75,7 +75,7 @@ class _Stream(_WritableStream, _ReadableStream, Protocol): ... # bytes is the raw form and str is the cooked form. # In the long run, both should become template parameters maybe? # There *are* bytes->bytes and str->str encodings in the standard library. -# They are much more common in Python 2 than in Python 3. +# They were much more common in Python 2 than in Python 3. class _Encoder(Protocol): def __call__(self, input: str, errors: str = ...) -> tuple[bytes, int]: ... # signature of Codec().encode diff --git a/mypy/typeshed/stdlib/collections/__init__.pyi b/mypy/typeshed/stdlib/collections/__init__.pyi index b546c45ab364..40cf999dfae1 100644 --- a/mypy/typeshed/stdlib/collections/__init__.pyi +++ b/mypy/typeshed/stdlib/collections/__init__.pyi @@ -41,9 +41,13 @@ class UserDict(MutableMapping[_KT, _VT], Generic[_KT, _VT]): @overload def __init__(self: UserDict[str, _VT], __dict: None = ..., **kwargs: _VT) -> None: ... @overload - def __init__(self, __dict: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> None: ... + def __init__(self, __dict: SupportsKeysAndGetItem[_KT, _VT]) -> None: ... @overload - def __init__(self, __iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> None: ... + def __init__(self: UserDict[str, _VT], __dict: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> None: ... + @overload + def __init__(self, __iterable: Iterable[tuple[_KT, _VT]]) -> None: ... + @overload + def __init__(self: UserDict[str, _VT], __iterable: Iterable[tuple[str, _VT]], **kwargs: _VT) -> None: ... @overload def __init__(self: UserDict[str, str], __iterable: Iterable[list[str]]) -> None: ... def __len__(self) -> int: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi b/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi index 3c9e53d62d6c..ff2e72bbf4fb 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/__init__.pyi @@ -32,3 +32,5 @@ __all__ = ( "ProcessPoolExecutor", "ThreadPoolExecutor", ) + +def __dir__() -> tuple[str, ...]: ... diff --git a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi index 9dd9be4d647e..3885abf8db91 100644 --- a/mypy/typeshed/stdlib/concurrent/futures/_base.pyi +++ b/mypy/typeshed/stdlib/concurrent/futures/_base.pyi @@ -1,11 +1,10 @@ import sys import threading from _typeshed import Self -from abc import abstractmethod -from collections.abc import Callable, Container, Iterable, Iterator, Sequence +from collections.abc import Callable, Iterable, Iterator, Sequence from logging import Logger from types import TracebackType -from typing import Any, Generic, Protocol, TypeVar, overload +from typing import Any, Generic, TypeVar, overload from typing_extensions import Literal, ParamSpec, SupportsIndex if sys.version_info >= (3, 9): @@ -33,16 +32,8 @@ if sys.version_info >= (3, 8): class BrokenExecutor(RuntimeError): ... _T = TypeVar("_T") -_T_co = TypeVar("_T_co", covariant=True) _P = ParamSpec("_P") -# Copied over Collection implementation as it does not exist in Python 2 and <3.6. -# Also to solve pytype issues with _Collection. -class _Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]): - # Implement Sized (but don't have it as a base class). - @abstractmethod - def __len__(self) -> int: ... - class Future(Generic[_T]): def __init__(self) -> None: ... def cancel(self) -> bool: ... diff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi index dde87c041b26..6a846ad618c3 100644 --- a/mypy/typeshed/stdlib/contextlib.pyi +++ b/mypy/typeshed/stdlib/contextlib.pyi @@ -1,8 +1,10 @@ +import abc import sys from _typeshed import Self, StrOrBytesPath +from abc import abstractmethod from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Generator, Iterator from types import TracebackType -from typing import IO, Any, AsyncContextManager, ContextManager, Generic, Protocol, TypeVar, overload # noqa: Y022,Y027 +from typing import IO, Any, Generic, Protocol, TypeVar, overload, runtime_checkable from typing_extensions import ParamSpec, TypeAlias __all__ = [ @@ -35,8 +37,21 @@ _P = ParamSpec("_P") _ExitFunc: TypeAlias = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], bool | None] _CM_EF = TypeVar("_CM_EF", bound=AbstractContextManager[Any] | _ExitFunc) -AbstractContextManager = ContextManager -AbstractAsyncContextManager = AsyncContextManager +@runtime_checkable +class AbstractContextManager(Protocol[_T_co]): + def __enter__(self) -> _T_co: ... + @abstractmethod + def __exit__( + self, __exc_type: type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None + ) -> bool | None: ... + +@runtime_checkable +class AbstractAsyncContextManager(Protocol[_T_co]): + async def __aenter__(self) -> _T_co: ... + @abstractmethod + async def __aexit__( + self, __exc_type: type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None + ) -> bool | None: ... class ContextDecorator: def __call__(self, func: _F) -> _F: ... @@ -119,7 +134,9 @@ class _RedirectStream(AbstractContextManager[_T_io]): class redirect_stdout(_RedirectStream[_T_io]): ... class redirect_stderr(_RedirectStream[_T_io]): ... -class ExitStack: +# In reality this is a subclass of `AbstractContextManager`; +# see #7961 for why we don't do that in the stub +class ExitStack(metaclass=abc.ABCMeta): def __init__(self) -> None: ... def enter_context(self, cm: AbstractContextManager[_T]) -> _T: ... def push(self, exit: _CM_EF) -> _CM_EF: ... @@ -134,7 +151,9 @@ class ExitStack: _ExitCoroFunc: TypeAlias = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], Awaitable[bool]] _ACM_EF = TypeVar("_ACM_EF", bound=AbstractAsyncContextManager[Any] | _ExitCoroFunc) -class AsyncExitStack: +# In reality this is a subclass of `AbstractAsyncContextManager`; +# see #7961 for why we don't do that in the stub +class AsyncExitStack(metaclass=abc.ABCMeta): 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/ctypes/__init__.pyi b/mypy/typeshed/stdlib/ctypes/__init__.pyi index 386c6a20cf3a..48694fc6cf8a 100644 --- a/mypy/typeshed/stdlib/ctypes/__init__.pyi +++ b/mypy/typeshed/stdlib/ctypes/__init__.pyi @@ -100,7 +100,7 @@ class _FuncPointer(_PointerLike, _CData): @overload def __init__(self, func_spec: tuple[str | int, CDLL], paramflags: tuple[_PF, ...] = ...) -> None: ... @overload - def __init__(self, vtlb_index: int, name: str, paramflags: tuple[_PF, ...] = ..., iid: pointer[c_int] = ...) -> None: ... + def __init__(self, vtlb_index: int, name: str, paramflags: tuple[_PF, ...] = ..., iid: _Pointer[c_int] = ...) -> None: ... def __call__(self, *args: Any, **kwargs: Any) -> Any: ... class _NamedFuncPointer(_FuncPointer): @@ -156,14 +156,14 @@ if sys.platform == "win32": def memmove(dst: _CVoidPLike, src: _CVoidConstPLike, count: int) -> int: ... def memset(dst: _CVoidPLike, c: int, count: int) -> int: ... -def POINTER(type: type[_CT]) -> type[pointer[_CT]]: ... +def POINTER(type: type[_CT]) -> type[_Pointer[_CT]]: ... -# The real ctypes.pointer is a function, not a class. The stub version of pointer behaves like -# ctypes._Pointer in that it is the base class for all pointer types. Unlike the real _Pointer, -# it can be instantiated directly (to mimic the behavior of the real pointer function). -class pointer(Generic[_CT], _PointerLike, _CData): +class _Pointer(Generic[_CT], _PointerLike, _CData): _type_: type[_CT] contents: _CT + @overload + def __init__(self) -> None: ... + @overload def __init__(self, arg: _CT) -> None: ... @overload def __getitem__(self, __i: int) -> _CT: ... @@ -174,6 +174,7 @@ class pointer(Generic[_CT], _PointerLike, _CData): @overload def __setitem__(self, __s: slice, __o: Iterable[_CT]) -> None: ... +def pointer(__arg: _CT) -> _Pointer[_CT]: ... def resize(obj: _CData, size: int) -> None: ... def set_errno(value: int) -> int: ... diff --git a/mypy/typeshed/stdlib/ctypes/wintypes.pyi b/mypy/typeshed/stdlib/ctypes/wintypes.pyi index 9536114b786a..3bd27934750a 100644 --- a/mypy/typeshed/stdlib/ctypes/wintypes.pyi +++ b/mypy/typeshed/stdlib/ctypes/wintypes.pyi @@ -1,6 +1,7 @@ from ctypes import ( Array, Structure, + _Pointer, _SimpleCData, c_byte, c_char, @@ -18,7 +19,6 @@ from ctypes import ( c_void_p, c_wchar, c_wchar_p, - pointer, ) from typing_extensions import TypeAlias @@ -181,55 +181,55 @@ class WIN32_FIND_DATAW(Structure): cFileName: Array[WCHAR] cAlternateFileName: Array[WCHAR] -# These pointer type definitions use pointer[...] instead of POINTER(...), to allow them +# These pointer type definitions use _Pointer[...] instead of POINTER(...), to allow them # to be used in type annotations. -PBOOL: TypeAlias = pointer[BOOL] -LPBOOL: TypeAlias = pointer[BOOL] -PBOOLEAN: TypeAlias = pointer[BOOLEAN] -PBYTE: TypeAlias = pointer[BYTE] -LPBYTE: TypeAlias = pointer[BYTE] -PCHAR: TypeAlias = pointer[CHAR] -LPCOLORREF: TypeAlias = pointer[COLORREF] -PDWORD: TypeAlias = pointer[DWORD] -LPDWORD: TypeAlias = pointer[DWORD] -PFILETIME: TypeAlias = pointer[FILETIME] -LPFILETIME: TypeAlias = pointer[FILETIME] -PFLOAT: TypeAlias = pointer[FLOAT] -PHANDLE: TypeAlias = pointer[HANDLE] -LPHANDLE: TypeAlias = pointer[HANDLE] -PHKEY: TypeAlias = pointer[HKEY] -LPHKL: TypeAlias = pointer[HKL] -PINT: TypeAlias = pointer[INT] -LPINT: TypeAlias = pointer[INT] -PLARGE_INTEGER: TypeAlias = pointer[LARGE_INTEGER] -PLCID: TypeAlias = pointer[LCID] -PLONG: TypeAlias = pointer[LONG] -LPLONG: TypeAlias = pointer[LONG] -PMSG: TypeAlias = pointer[MSG] -LPMSG: TypeAlias = pointer[MSG] -PPOINT: TypeAlias = pointer[POINT] -LPPOINT: TypeAlias = pointer[POINT] -PPOINTL: TypeAlias = pointer[POINTL] -PRECT: TypeAlias = pointer[RECT] -LPRECT: TypeAlias = pointer[RECT] -PRECTL: TypeAlias = pointer[RECTL] -LPRECTL: TypeAlias = pointer[RECTL] -LPSC_HANDLE: TypeAlias = pointer[SC_HANDLE] -PSHORT: TypeAlias = pointer[SHORT] -PSIZE: TypeAlias = pointer[SIZE] -LPSIZE: TypeAlias = pointer[SIZE] -PSIZEL: TypeAlias = pointer[SIZEL] -LPSIZEL: TypeAlias = pointer[SIZEL] -PSMALL_RECT: TypeAlias = pointer[SMALL_RECT] -PUINT: TypeAlias = pointer[UINT] -LPUINT: TypeAlias = pointer[UINT] -PULARGE_INTEGER: TypeAlias = pointer[ULARGE_INTEGER] -PULONG: TypeAlias = pointer[ULONG] -PUSHORT: TypeAlias = pointer[USHORT] -PWCHAR: TypeAlias = pointer[WCHAR] -PWIN32_FIND_DATAA: TypeAlias = pointer[WIN32_FIND_DATAA] -LPWIN32_FIND_DATAA: TypeAlias = pointer[WIN32_FIND_DATAA] -PWIN32_FIND_DATAW: TypeAlias = pointer[WIN32_FIND_DATAW] -LPWIN32_FIND_DATAW: TypeAlias = pointer[WIN32_FIND_DATAW] -PWORD: TypeAlias = pointer[WORD] -LPWORD: TypeAlias = pointer[WORD] +PBOOL: TypeAlias = _Pointer[BOOL] +LPBOOL: TypeAlias = _Pointer[BOOL] +PBOOLEAN: TypeAlias = _Pointer[BOOLEAN] +PBYTE: TypeAlias = _Pointer[BYTE] +LPBYTE: TypeAlias = _Pointer[BYTE] +PCHAR: TypeAlias = _Pointer[CHAR] +LPCOLORREF: TypeAlias = _Pointer[COLORREF] +PDWORD: TypeAlias = _Pointer[DWORD] +LPDWORD: TypeAlias = _Pointer[DWORD] +PFILETIME: TypeAlias = _Pointer[FILETIME] +LPFILETIME: TypeAlias = _Pointer[FILETIME] +PFLOAT: TypeAlias = _Pointer[FLOAT] +PHANDLE: TypeAlias = _Pointer[HANDLE] +LPHANDLE: TypeAlias = _Pointer[HANDLE] +PHKEY: TypeAlias = _Pointer[HKEY] +LPHKL: TypeAlias = _Pointer[HKL] +PINT: TypeAlias = _Pointer[INT] +LPINT: TypeAlias = _Pointer[INT] +PLARGE_INTEGER: TypeAlias = _Pointer[LARGE_INTEGER] +PLCID: TypeAlias = _Pointer[LCID] +PLONG: TypeAlias = _Pointer[LONG] +LPLONG: TypeAlias = _Pointer[LONG] +PMSG: TypeAlias = _Pointer[MSG] +LPMSG: TypeAlias = _Pointer[MSG] +PPOINT: TypeAlias = _Pointer[POINT] +LPPOINT: TypeAlias = _Pointer[POINT] +PPOINTL: TypeAlias = _Pointer[POINTL] +PRECT: TypeAlias = _Pointer[RECT] +LPRECT: TypeAlias = _Pointer[RECT] +PRECTL: TypeAlias = _Pointer[RECTL] +LPRECTL: TypeAlias = _Pointer[RECTL] +LPSC_HANDLE: TypeAlias = _Pointer[SC_HANDLE] +PSHORT: TypeAlias = _Pointer[SHORT] +PSIZE: TypeAlias = _Pointer[SIZE] +LPSIZE: TypeAlias = _Pointer[SIZE] +PSIZEL: TypeAlias = _Pointer[SIZEL] +LPSIZEL: TypeAlias = _Pointer[SIZEL] +PSMALL_RECT: TypeAlias = _Pointer[SMALL_RECT] +PUINT: TypeAlias = _Pointer[UINT] +LPUINT: TypeAlias = _Pointer[UINT] +PULARGE_INTEGER: TypeAlias = _Pointer[ULARGE_INTEGER] +PULONG: TypeAlias = _Pointer[ULONG] +PUSHORT: TypeAlias = _Pointer[USHORT] +PWCHAR: TypeAlias = _Pointer[WCHAR] +PWIN32_FIND_DATAA: TypeAlias = _Pointer[WIN32_FIND_DATAA] +LPWIN32_FIND_DATAA: TypeAlias = _Pointer[WIN32_FIND_DATAA] +PWIN32_FIND_DATAW: TypeAlias = _Pointer[WIN32_FIND_DATAW] +LPWIN32_FIND_DATAW: TypeAlias = _Pointer[WIN32_FIND_DATAW] +PWORD: TypeAlias = _Pointer[WORD] +LPWORD: TypeAlias = _Pointer[WORD] diff --git a/mypy/typeshed/stdlib/curses/__init__.pyi b/mypy/typeshed/stdlib/curses/__init__.pyi index f80ed442ea9c..db44fa6a6be7 100644 --- a/mypy/typeshed/stdlib/curses/__init__.pyi +++ b/mypy/typeshed/stdlib/curses/__init__.pyi @@ -1,12 +1,14 @@ import sys from collections.abc import Callable -from typing import Any, TypeVar +from typing import TypeVar +from typing_extensions import Concatenate, ParamSpec if sys.platform != "win32": from _curses import * from _curses import _CursesWindow as _CursesWindow _T = TypeVar("_T") + _P = ParamSpec("_P") # available after calling `curses.initscr()` LINES: int @@ -15,6 +17,5 @@ if sys.platform != "win32": # available after calling `curses.start_color()` COLORS: int COLOR_PAIRS: int - # TODO: wait for `Concatenate` support - # def wrapper(__func: Callable[Concatenate[_CursesWindow, _P], _T], *arg: _P.args, **kwds: _P.kwargs) -> _T: ... - def wrapper(__func: Callable[..., _T], *arg: Any, **kwds: Any) -> _T: ... + + def wrapper(__func: Callable[Concatenate[_CursesWindow, _P], _T], *arg: _P.args, **kwds: _P.kwargs) -> _T: ... diff --git a/mypy/typeshed/stdlib/curses/has_key.pyi b/mypy/typeshed/stdlib/curses/has_key.pyi new file mode 100644 index 000000000000..ff728aedf84b --- /dev/null +++ b/mypy/typeshed/stdlib/curses/has_key.pyi @@ -0,0 +1,4 @@ +import sys + +if sys.platform != "win32": + def has_key(ch: int | str) -> bool: ... diff --git a/mypy/typeshed/stdlib/datetime.pyi b/mypy/typeshed/stdlib/datetime.pyi index 4f93eb7205da..780ee941baa5 100644 --- a/mypy/typeshed/stdlib/datetime.pyi +++ b/mypy/typeshed/stdlib/datetime.pyi @@ -29,7 +29,6 @@ class timezone(tzinfo): min: ClassVar[timezone] max: ClassVar[timezone] def __init__(self, offset: timedelta, name: str = ...) -> None: ... - def __hash__(self) -> int: ... if sys.version_info >= (3, 11): UTC: timezone @@ -94,7 +93,6 @@ class date: @overload def __sub__(self, __other: date) -> timedelta: ... - def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... if sys.version_info >= (3, 9): @@ -132,7 +130,6 @@ class time: def __lt__(self, __other: time) -> bool: ... def __ge__(self, __other: time) -> bool: ... def __gt__(self, __other: time) -> bool: ... - def __hash__(self) -> int: ... def isoformat(self, timespec: str = ...) -> str: ... @classmethod def fromisoformat(cls: type[Self], __time_string: str) -> Self: ... @@ -200,7 +197,6 @@ class timedelta(SupportsAbs[timedelta]): def __ge__(self, __other: timedelta) -> bool: ... def __gt__(self, __other: timedelta) -> bool: ... def __bool__(self) -> bool: ... - def __hash__(self) -> int: ... class datetime(date): min: ClassVar[datetime] diff --git a/mypy/typeshed/stdlib/doctest.pyi b/mypy/typeshed/stdlib/doctest.pyi index 6bb1bf9d33c5..382d9578ce80 100644 --- a/mypy/typeshed/stdlib/doctest.pyi +++ b/mypy/typeshed/stdlib/doctest.pyi @@ -85,7 +85,6 @@ class Example: indent: int = ..., options: dict[int, bool] | None = ..., ) -> None: ... - def __hash__(self) -> int: ... def __eq__(self, other: object) -> bool: ... class DocTest: @@ -104,7 +103,6 @@ class DocTest: lineno: int | None, docstring: str | None, ) -> None: ... - def __hash__(self) -> int: ... def __lt__(self, other: DocTest) -> bool: ... def __eq__(self, other: object) -> bool: ... @@ -211,7 +209,6 @@ class DocTestCase(unittest.TestCase): def format_failure(self, err: str) -> str: ... def debug(self) -> None: ... def id(self) -> str: ... - def __hash__(self) -> int: ... def __eq__(self, other: object) -> bool: ... def shortDescription(self) -> str: ... diff --git a/mypy/typeshed/stdlib/email/__init__.pyi b/mypy/typeshed/stdlib/email/__init__.pyi index 78368a2cf4a0..4591b2c3340e 100644 --- a/mypy/typeshed/stdlib/email/__init__.pyi +++ b/mypy/typeshed/stdlib/email/__init__.pyi @@ -5,8 +5,8 @@ from typing import IO, Union from typing_extensions import TypeAlias # Definitions imported by multiple submodules in typeshed -_ParamType: TypeAlias = Union[str, tuple[str | None, str | None, str]] -_ParamsType: TypeAlias = Union[str, None, tuple[str, str | None, str]] +_ParamType: TypeAlias = Union[str, tuple[str | None, str | None, str]] # noqa: Y047 +_ParamsType: TypeAlias = Union[str, None, tuple[str, str | None, str]] # noqa: Y047 def message_from_string(s: str, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... def message_from_bytes(s: bytes, _class: Callable[[], Message] = ..., *, policy: Policy = ...) -> Message: ... diff --git a/mypy/typeshed/stdlib/email/headerregistry.pyi b/mypy/typeshed/stdlib/email/headerregistry.pyi index 7f1d86b985a1..b2b63c4ac72c 100644 --- a/mypy/typeshed/stdlib/email/headerregistry.pyi +++ b/mypy/typeshed/stdlib/email/headerregistry.pyi @@ -14,7 +14,7 @@ from email._header_value_parser import ( ) from email.errors import MessageDefect from email.policy import Policy -from typing import Any, ClassVar +from typing import Any, ClassVar, Protocol from typing_extensions import Literal class BaseHeader(str): @@ -141,9 +141,19 @@ if sys.version_info >= (3, 8): @staticmethod def value_parser(value: str) -> MessageID: ... +class _HeaderParser(Protocol): + max_count: ClassVar[Literal[1] | None] + @staticmethod + def value_parser(value: str) -> TokenList: ... + @classmethod + def parse(cls, value: str, kwds: dict[str, Any]) -> None: ... + class HeaderRegistry: + registry: dict[str, type[_HeaderParser]] + base_class: type[BaseHeader] + default_class: type[_HeaderParser] def __init__( - self, base_class: type[BaseHeader] = ..., default_class: type[BaseHeader] = ..., use_default_map: bool = ... + self, base_class: type[BaseHeader] = ..., default_class: type[_HeaderParser] = ..., use_default_map: bool = ... ) -> None: ... def map_to_type(self, name: str, cls: type[BaseHeader]) -> None: ... def __getitem__(self, name: str) -> type[BaseHeader]: ... diff --git a/mypy/typeshed/stdlib/enum.pyi b/mypy/typeshed/stdlib/enum.pyi index 2ec13714c99e..a14744f1ba8d 100644 --- a/mypy/typeshed/stdlib/enum.pyi +++ b/mypy/typeshed/stdlib/enum.pyi @@ -109,6 +109,7 @@ class EnumMeta(ABCMeta): def __members__(self: type[_EnumMemberT]) -> types.MappingProxyType[str, _EnumMemberT]: ... def __len__(self) -> int: ... def __bool__(self) -> Literal[True]: ... + def __dir__(self) -> list[str]: ... # Simple value lookup @overload # type: ignore[override] def __call__(cls: type[_EnumMemberT], value: Any, names: None = ...) -> _EnumMemberT: ... @@ -176,8 +177,7 @@ class Enum(metaclass=EnumMeta): def __new__(cls: type[Self], value: object) -> Self: ... def __dir__(self) -> list[str]: ... def __format__(self, format_spec: str) -> str: ... - def __hash__(self) -> Any: ... - def __reduce_ex__(self, proto: object) -> Any: ... + def __reduce_ex__(self, proto: object) -> tuple[Any, ...]: ... if sys.version_info >= (3, 11): class ReprEnum(Enum): ... diff --git a/mypy/typeshed/stdlib/http/client.pyi b/mypy/typeshed/stdlib/http/client.pyi index 2c75e7b37c2e..08c3f2c8be0b 100644 --- a/mypy/typeshed/stdlib/http/client.pyi +++ b/mypy/typeshed/stdlib/http/client.pyi @@ -5,7 +5,7 @@ import types from _typeshed import Self, WriteableBuffer from collections.abc import Callable, Iterable, Iterator, Mapping from socket import socket -from typing import IO, Any, BinaryIO, Protocol, TypeVar, overload +from typing import IO, Any, BinaryIO, TypeVar, overload from typing_extensions import TypeAlias __all__ = [ @@ -137,18 +137,6 @@ class HTTPResponse(io.BufferedIOBase, BinaryIO): def getcode(self) -> int: ... def begin(self) -> None: ... -# This is an API stub only for the class below, not a class itself. -# urllib.request uses it for a parameter. -class _HTTPConnectionProtocol(Protocol): - def __call__( - self, - host: str, - port: int | None = ..., - timeout: float = ..., - source_address: tuple[str, int] | None = ..., - blocksize: int = ..., - ) -> HTTPConnection: ... - class HTTPConnection: auto_open: int # undocumented debuglevel: int diff --git a/mypy/typeshed/stdlib/importlib/abc.pyi b/mypy/typeshed/stdlib/importlib/abc.pyi index 42b56d88d75b..b46d42a4199a 100644 --- a/mypy/typeshed/stdlib/importlib/abc.pyi +++ b/mypy/typeshed/stdlib/importlib/abc.pyi @@ -85,9 +85,6 @@ class Loader(metaclass=ABCMeta): # but expected in new code. def exec_module(self, module: types.ModuleType) -> None: ... -class _LoaderProtocol(Protocol): - def load_module(self, fullname: str) -> types.ModuleType: ... - class FileLoader(ResourceLoader, ExecutionLoader, metaclass=ABCMeta): name: str path: _Path diff --git a/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi b/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi index 6a7cd858c80b..e3504fe4036a 100644 --- a/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi +++ b/mypy/typeshed/stdlib/importlib/metadata/_meta.pyi @@ -1,4 +1,3 @@ -import sys from collections.abc import Iterator from typing import Any, Protocol, TypeVar @@ -17,7 +16,7 @@ class SimplePath(Protocol): def joinpath(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: ... + # There was a bug in `SimplePath` definition in cpython, see #8451 + # Strictly speaking `__div__` was defined in 3.10, not __truediv__, + # but it should have always been `__truediv__`. + def __truediv__(self) -> SimplePath: ... diff --git a/mypy/typeshed/stdlib/io.pyi b/mypy/typeshed/stdlib/io.pyi index c92fe1644053..f47a9ddf334c 100644 --- a/mypy/typeshed/stdlib/io.pyi +++ b/mypy/typeshed/stdlib/io.pyi @@ -1,3 +1,4 @@ +import abc import builtins import codecs import sys @@ -47,7 +48,7 @@ BlockingIOError = builtins.BlockingIOError class UnsupportedOperation(OSError, ValueError): ... -class IOBase: +class IOBase(metaclass=abc.ABCMeta): def __iter__(self) -> Iterator[bytes]: ... def __next__(self) -> bytes: ... def __enter__(self: Self) -> Self: ... diff --git a/mypy/typeshed/stdlib/ipaddress.pyi b/mypy/typeshed/stdlib/ipaddress.pyi index 4f9109363b53..d324f52ac25a 100644 --- a/mypy/typeshed/stdlib/ipaddress.pyi +++ b/mypy/typeshed/stdlib/ipaddress.pyi @@ -31,7 +31,6 @@ class _IPAddressBase: class _BaseAddress(_IPAddressBase, SupportsInt): def __init__(self, address: object) -> None: ... def __add__(self: Self, other: int) -> Self: ... - def __hash__(self) -> int: ... def __int__(self) -> int: ... def __sub__(self: Self, other: int) -> Self: ... def __format__(self, fmt: str) -> str: ... diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi index e69de29bb2d1..acc1cc429be9 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi @@ -0,0 +1,8 @@ +from collections.abc import Callable +from lib2to3.pgen2.grammar import Grammar +from lib2to3.pytree import _RawNode +from typing import Any +from typing_extensions import TypeAlias + +# This is imported in several lib2to3/pgen2 submodules +_Convert: TypeAlias = Callable[[Grammar, _RawNode], Any] # noqa: Y047 diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi index 61ec90b4d582..45c9aeaa5691 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi @@ -1,7 +1,8 @@ from _typeshed import StrPath from collections.abc import Iterable +from lib2to3.pgen2 import _Convert from lib2to3.pgen2.grammar import Grammar -from lib2to3.pytree import _NL, _Convert +from lib2to3.pytree import _NL from logging import Logger from typing import IO, Any diff --git a/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi b/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi index 14d6004d3423..6a07c4a4ad48 100644 --- a/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi @@ -1,6 +1,7 @@ from collections.abc import Sequence +from lib2to3.pgen2 import _Convert from lib2to3.pgen2.grammar import _DFAS, Grammar -from lib2to3.pytree import _NL, _Convert, _RawNode +from lib2to3.pytree import _NL, _RawNode from typing import Any from typing_extensions import TypeAlias diff --git a/mypy/typeshed/stdlib/lib2to3/pytree.pyi b/mypy/typeshed/stdlib/lib2to3/pytree.pyi index 208a87da8e4e..4db9ab99ba44 100644 --- a/mypy/typeshed/stdlib/lib2to3/pytree.pyi +++ b/mypy/typeshed/stdlib/lib2to3/pytree.pyi @@ -1,5 +1,5 @@ from _typeshed import Self -from collections.abc import Callable, Iterator +from collections.abc import Iterator from lib2to3.pgen2.grammar import Grammar from typing import Any from typing_extensions import TypeAlias @@ -8,9 +8,6 @@ _NL: TypeAlias = Node | Leaf _Context: TypeAlias = tuple[str, int, int] _Results: TypeAlias = dict[str, _NL] _RawNode: TypeAlias = tuple[int, str, _Context, list[_NL] | None] -# This alias isn't used in this file, -# but is imported in other lib2to3 submodules -_Convert: TypeAlias = Callable[[Grammar, _RawNode], Any] HUGE: int diff --git a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi index 4359b6c080aa..186bd54a021d 100644 --- a/mypy/typeshed/stdlib/multiprocessing/__init__.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/__init__.pyi @@ -1,5 +1,5 @@ import sys -from multiprocessing import context, reduction as reducer, synchronize +from multiprocessing import context, reduction as reducer from multiprocessing.context import ( AuthenticationError as AuthenticationError, BufferTooShort as BufferTooShort, @@ -10,12 +10,14 @@ from multiprocessing.context import ( from multiprocessing.process import active_children as active_children, current_process as current_process # These are technically functions that return instances of these Queue classes. -# Using them as annotations is deprecated. Either use imports from -# multiprocessing.queues or the aliases defined below. See #4266 for discussion. +# The stub here doesn't reflect reality exactly -- +# while e.g. `multiprocessing.queues.Queue` is a class, +# `multiprocessing.Queue` is actually a function at runtime. +# Avoid using `multiprocessing.Queue` as a type annotation; +# use imports from multiprocessing.queues instead. +# See #4266 and #8450 for discussion. from multiprocessing.queues import JoinableQueue as JoinableQueue, Queue as Queue, SimpleQueue as SimpleQueue from multiprocessing.spawn import freeze_support as freeze_support -from typing import TypeVar -from typing_extensions import TypeAlias if sys.version_info >= (3, 8): from multiprocessing.process import parent_process as parent_process @@ -62,27 +64,6 @@ __all__ = [ if sys.version_info >= (3, 8): __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. -# -# from multiprocessing import Lock -# from typing import TYPE_CHECKING -# if TYPE_CHECKING: -# from multiprocessing import _LockType -# lock: _LockType = Lock() - -_T = TypeVar("_T") -_QueueType: TypeAlias = Queue[_T] -_SimpleQueueType: TypeAlias = SimpleQueue[_T] -_JoinableQueueType: TypeAlias = JoinableQueue[_T] -_BarrierType: TypeAlias = synchronize.Barrier -_BoundedSemaphoreType: TypeAlias = synchronize.BoundedSemaphore -_ConditionType: TypeAlias = synchronize.Condition -_EventType: TypeAlias = synchronize.Event -_LockType: TypeAlias = synchronize.Lock -_RLockType: TypeAlias = synchronize.RLock -_SemaphoreType: TypeAlias = synchronize.Semaphore - # These functions (really bound methods) # are all autogenerated at runtime here: https://github.com/python/cpython/blob/600c65c094b0b48704d8ec2416930648052ba715/Lib/multiprocessing/__init__.py#L23 RawValue = context._default_context.RawValue diff --git a/mypy/typeshed/stdlib/multiprocessing/context.pyi b/mypy/typeshed/stdlib/multiprocessing/context.pyi index 7215955da535..16b7cfe9e890 100644 --- a/mypy/typeshed/stdlib/multiprocessing/context.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/context.pyi @@ -1,10 +1,9 @@ import ctypes -import multiprocessing import sys from collections.abc import Callable, Iterable, Sequence from ctypes import _CData from logging import Logger -from multiprocessing import queues, synchronize +from multiprocessing import popen_fork, popen_forkserver, popen_spawn_posix, popen_spawn_win32, queues, synchronize from multiprocessing.connection import _ConnectionBase from multiprocessing.managers import SyncManager from multiprocessing.pool import Pool as _Pool @@ -27,11 +26,10 @@ class TimeoutError(ProcessError): ... class AuthenticationError(ProcessError): ... class BaseContext: - Process: type[BaseProcess] - ProcessError: type[Exception] - BufferTooShort: type[Exception] - TimeoutError: type[Exception] - AuthenticationError: type[Exception] + ProcessError: ClassVar[type[ProcessError]] + BufferTooShort: ClassVar[type[BufferTooShort]] + TimeoutError: ClassVar[type[TimeoutError]] + AuthenticationError: ClassVar[type[AuthenticationError]] # N.B. The methods below are applied at runtime to generate # multiprocessing.*, so the signatures should be identical (modulo self). @@ -137,7 +135,7 @@ class Process(BaseProcess): def _Popen(process_obj: BaseProcess) -> DefaultContext: ... class DefaultContext(BaseContext): - Process: type[multiprocessing.Process] + Process: ClassVar[type[Process]] def __init__(self, context: BaseContext) -> None: ... def set_start_method(self, method: str | None, force: bool = ...) -> None: ... def get_start_method(self, allow_none: bool = ...) -> str: ... @@ -147,43 +145,37 @@ class DefaultContext(BaseContext): _default_context: DefaultContext -if sys.platform != "win32": - class ForkProcess(BaseProcess): - _start_method: str +class SpawnProcess(BaseProcess): + _start_method: str + if sys.platform != "win32": @staticmethod - def _Popen(process_obj: BaseProcess) -> Any: ... + def _Popen(process_obj: BaseProcess) -> popen_spawn_posix.Popen: ... + else: + @staticmethod + def _Popen(process_obj: BaseProcess) -> popen_spawn_win32.Popen: ... + +class SpawnContext(BaseContext): + _name: str + Process: ClassVar[type[SpawnProcess]] - class SpawnProcess(BaseProcess): +if sys.platform != "win32": + class ForkProcess(BaseProcess): _start_method: str @staticmethod - def _Popen(process_obj: BaseProcess) -> SpawnProcess: ... + def _Popen(process_obj: BaseProcess) -> popen_fork.Popen: ... class ForkServerProcess(BaseProcess): _start_method: str @staticmethod - def _Popen(process_obj: BaseProcess) -> Any: ... + def _Popen(process_obj: BaseProcess) -> popen_forkserver.Popen: ... class ForkContext(BaseContext): _name: str - Process: type[ForkProcess] - - class SpawnContext(BaseContext): - _name: str - Process: type[SpawnProcess] + Process: ClassVar[type[ForkProcess]] class ForkServerContext(BaseContext): _name: str - Process: type[ForkServerProcess] - -else: - class SpawnProcess(BaseProcess): - _start_method: str - @staticmethod - def _Popen(process_obj: BaseProcess) -> Any: ... - - class SpawnContext(BaseContext): - _name: str - Process: type[SpawnProcess] + Process: ClassVar[type[ForkServerProcess]] def _force_start_method(method: str) -> None: ... def get_spawning_popen() -> Any | None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/heap.pyi b/mypy/typeshed/stdlib/multiprocessing/heap.pyi new file mode 100644 index 000000000000..9c8f55604a64 --- /dev/null +++ b/mypy/typeshed/stdlib/multiprocessing/heap.pyi @@ -0,0 +1,36 @@ +import sys +from _typeshed import Incomplete +from collections.abc import Callable +from mmap import mmap +from typing import Protocol +from typing_extensions import TypeAlias + +__all__ = ["BufferWrapper"] + +class Arena: + size: int + buffer: mmap + if sys.platform == "win32": + name: str + def __init__(self, size: int) -> None: ... + else: + fd: int + def __init__(self, size: int, fd: int = ...) -> None: ... + +_Block: TypeAlias = tuple[Arena, int, int] + +if sys.platform != "win32": + class _SupportsDetach(Protocol): + def detach(self) -> int: ... + + def reduce_arena(a: Arena) -> tuple[Callable[[int, _SupportsDetach], Arena], tuple[int, Incomplete]]: ... + def rebuild_arena(size: int, dupfd: _SupportsDetach) -> Arena: ... + +class Heap: + def __init__(self, size: int = ...) -> None: ... + def free(self, block: _Block) -> None: ... + def malloc(self, size: int) -> _Block: ... + +class BufferWrapper: + def __init__(self, size: int) -> None: ... + def create_memoryview(self) -> memoryview: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/managers.pyi b/mypy/typeshed/stdlib/multiprocessing/managers.pyi index dfbcb395ef1a..d953785d81cb 100644 --- a/mypy/typeshed/stdlib/multiprocessing/managers.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/managers.pyi @@ -183,9 +183,13 @@ class SyncManager(BaseManager): @overload def dict(self, **kwargs: _VT) -> DictProxy[str, _VT]: ... @overload - def dict(self, __map: SupportsKeysAndGetItem[_KT, _VT], **kwargs: _VT) -> DictProxy[_KT, _VT]: ... + def dict(self, __map: SupportsKeysAndGetItem[_KT, _VT]) -> DictProxy[_KT, _VT]: ... @overload - def dict(self, __iterable: Iterable[tuple[_KT, _VT]], **kwargs: _VT) -> DictProxy[_KT, _VT]: ... + def dict(self, __map: SupportsKeysAndGetItem[str, _VT], **kwargs: _VT) -> DictProxy[str, _VT]: ... + @overload + def dict(self, __iterable: Iterable[tuple[_KT, _VT]]) -> DictProxy[_KT, _VT]: ... + @overload + def dict(self, __iterable: Iterable[tuple[str, _VT]], **kwargs: _VT) -> DictProxy[str, _VT]: ... @overload def dict(self, __iterable: Iterable[list[str]]) -> DictProxy[str, str]: ... @overload diff --git a/mypy/typeshed/stdlib/multiprocessing/popen_fork.pyi b/mypy/typeshed/stdlib/multiprocessing/popen_fork.pyi new file mode 100644 index 000000000000..3db6a84394b9 --- /dev/null +++ b/mypy/typeshed/stdlib/multiprocessing/popen_fork.pyi @@ -0,0 +1,23 @@ +import sys +from typing import ClassVar + +from .process import BaseProcess +from .util import Finalize + +if sys.platform != "win32": + __all__ = ["Popen"] + + class Popen: + finalizer: Finalize | None + method: ClassVar[str] + pid: int + returncode: int | None + sentinel: int # doesn't exist if os.fork in _launch returns 0 + + def __init__(self, process_obj: BaseProcess) -> None: ... + def duplicate_for_child(self, fd: int) -> int: ... + def poll(self, flag: int = ...) -> int | None: ... + def wait(self, timeout: float | None = ...) -> int | None: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... + def close(self) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/popen_forkserver.pyi b/mypy/typeshed/stdlib/multiprocessing/popen_forkserver.pyi new file mode 100644 index 000000000000..d28c7245fd54 --- /dev/null +++ b/mypy/typeshed/stdlib/multiprocessing/popen_forkserver.pyi @@ -0,0 +1,22 @@ +import sys +from multiprocessing.process import BaseProcess +from typing import ClassVar + +from . import popen_fork +from .util import Finalize + +if sys.platform != "win32": + __all__ = ["Popen"] + + class _DupFd: + def __init__(self, ind: int) -> None: ... + def detach(self) -> int: ... + + class Popen(popen_fork.Popen): + DupFd: ClassVar[type[_DupFd]] + finalizer: Finalize + sentinel: int + + def __init__(self, process_obj: BaseProcess) -> None: ... + def duplicate_for_child(self, fd: int) -> int: ... + def poll(self, flag: int = ...) -> int | None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/popen_spawn_posix.pyi b/mypy/typeshed/stdlib/multiprocessing/popen_spawn_posix.pyi new file mode 100644 index 000000000000..81aaac7ca459 --- /dev/null +++ b/mypy/typeshed/stdlib/multiprocessing/popen_spawn_posix.pyi @@ -0,0 +1,24 @@ +import sys +from multiprocessing.process import BaseProcess +from typing import ClassVar + +from . import popen_fork +from .util import Finalize + +if sys.platform != "win32": + __all__ = ["Popen"] + + class _DupFd: + fd: int + + def __init__(self, fd: int) -> None: ... + def detach(self) -> int: ... + + class Popen(popen_fork.Popen): + DupFd: ClassVar[type[_DupFd]] + finalizer: Finalize + pid: int # may not exist if _launch raises in second try / except + sentinel: int # may not exist if _launch raises in second try / except + + def __init__(self, process_obj: BaseProcess) -> None: ... + def duplicate_for_child(self, fd: int) -> int: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/popen_spawn_win32.pyi b/mypy/typeshed/stdlib/multiprocessing/popen_spawn_win32.pyi new file mode 100644 index 000000000000..f5cb0a6c4844 --- /dev/null +++ b/mypy/typeshed/stdlib/multiprocessing/popen_spawn_win32.pyi @@ -0,0 +1,30 @@ +import sys +from multiprocessing.process import BaseProcess +from typing import ClassVar + +from .util import Finalize + +if sys.platform == "win32": + __all__ = ["Popen"] + + TERMINATE: int + WINEXE: bool + WINSERVICE: bool + WINENV: bool + + class Popen: + finalizer: Finalize + method: ClassVar[str] + pid: int + returncode: int | None + sentinel: int + + def __init__(self, process_obj: BaseProcess) -> None: ... + def duplicate_for_child(self, handle: int) -> int: ... + def wait(self, timeout: float | None = ...) -> int | None: ... + def poll(self) -> int | None: ... + def terminate(self) -> None: ... + + kill = terminate + + def close(self) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/reduction.pyi b/mypy/typeshed/stdlib/multiprocessing/reduction.pyi index 9e7387da64a5..a22c16828780 100644 --- a/mypy/typeshed/stdlib/multiprocessing/reduction.pyi +++ b/mypy/typeshed/stdlib/multiprocessing/reduction.pyi @@ -1,7 +1,9 @@ import pickle import sys +from _typeshed import HasFileno from abc import ABCMeta from copyreg import _DispatchTableType +from socket import socket from typing import Any from typing_extensions import Literal @@ -25,9 +27,11 @@ def dump(obj, file, protocol: Any | None = ...) -> None: ... if sys.platform == "win32": if sys.version_info >= (3, 8): - def duplicate(handle, target_process: Any | None = ..., inheritable: bool = ..., *, source_process: Any | None = ...): ... + def duplicate( + handle: int, target_process: int | None = ..., inheritable: bool = ..., *, source_process: int | None = ... + ) -> int: ... else: - def duplicate(handle, target_process: Any | None = ..., inheritable: bool = ...): ... + def duplicate(handle: int, target_process: int | None = ..., inheritable: bool = ...) -> int: ... def steal_handle(source_pid, handle): ... def send_handle(conn, handle, destination_pid) -> None: ... @@ -43,9 +47,9 @@ else: else: ACKNOWLEDGE: Literal[False] - def recvfds(sock, size): ... + def recvfds(sock: socket, size: int) -> list[int]: ... def send_handle(conn, handle, destination_pid) -> None: ... - def recv_handle(conn) -> None: ... + def recv_handle(conn: HasFileno) -> int: ... def sendfds(sock, fds) -> None: ... def DupFd(fd): ... diff --git a/mypy/typeshed/stdlib/multiprocessing/resource_sharer.pyi b/mypy/typeshed/stdlib/multiprocessing/resource_sharer.pyi new file mode 100644 index 000000000000..7708df9b6f3c --- /dev/null +++ b/mypy/typeshed/stdlib/multiprocessing/resource_sharer.pyi @@ -0,0 +1,20 @@ +import sys +from socket import socket + +__all__ = ["stop"] + +if sys.platform == "win32": + __all__ += ["DupSocket"] + + class DupSocket: + def __init__(self, sock: socket) -> None: ... + def detach(self) -> socket: ... + +else: + __all__ += ["DupFd"] + + class DupFd: + def __init__(self, fd: int) -> None: ... + def detach(self) -> int: ... + +def stop(timeout: float | None = ...) -> None: ... diff --git a/mypy/typeshed/stdlib/multiprocessing/util.pyi b/mypy/typeshed/stdlib/multiprocessing/util.pyi new file mode 100644 index 000000000000..e89b4a71cad4 --- /dev/null +++ b/mypy/typeshed/stdlib/multiprocessing/util.pyi @@ -0,0 +1,87 @@ +import threading +from _typeshed import Incomplete, ReadableBuffer, SupportsTrunc +from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence +from logging import Logger +from typing import Any, SupportsInt +from typing_extensions import SupportsIndex + +__all__ = [ + "sub_debug", + "debug", + "info", + "sub_warning", + "get_logger", + "log_to_stderr", + "get_temp_dir", + "register_after_fork", + "is_exiting", + "Finalize", + "ForkAwareThreadLock", + "ForkAwareLocal", + "close_all_fds_except", + "SUBDEBUG", + "SUBWARNING", +] + +NOTSET: int +SUBDEBUG: int +DEBUG: int +INFO: int +SUBWARNING: int + +LOGGER_NAME: str +DEFAULT_LOGGING_FORMAT: str + +def sub_debug(msg: object, *args: object) -> None: ... +def debug(msg: object, *args: object) -> None: ... +def info(msg: object, *args: object) -> None: ... +def sub_warning(msg: object, *args: object) -> None: ... +def get_logger() -> Logger: ... +def log_to_stderr(level: int | None = ...) -> Logger: ... +def is_abstract_socket_namespace(address: str | bytes | None) -> bool: ... + +abstract_sockets_supported: bool + +def get_temp_dir() -> str: ... +def register_after_fork(obj: Incomplete, func: Callable[[Incomplete], object]) -> None: ... + +class Finalize: + def __init__( + self, + obj: Incomplete | None, + callback: Callable[..., Incomplete], + args: Sequence[Any] = ..., + kwargs: Mapping[str, Any] | None = ..., + exitpriority: int | None = ..., + ) -> None: ... + def __call__( + self, + wr: object = ..., + _finalizer_registry: MutableMapping[Incomplete, Incomplete] = ..., + sub_debug: Callable[..., object] = ..., + getpid: Callable[[], int] = ..., + ) -> Incomplete: ... + def cancel(self) -> None: ... + def still_active(self) -> bool: ... + +def is_exiting() -> bool: ... + +class ForkAwareThreadLock: + acquire: Callable[[bool, float], bool] + release: Callable[[], None] + def __init__(self) -> None: ... + def __enter__(self) -> bool: ... + def __exit__(self, *args: object) -> None: ... + +class ForkAwareLocal(threading.local): + def __init__(self) -> None: ... + +MAXFD: int + +def close_all_fds_except(fds: Iterable[int]) -> None: ... +def spawnv_passfds( + path: bytes, + # args is anything that can be passed to the int constructor + args: Sequence[str | ReadableBuffer | SupportsInt | SupportsIndex | SupportsTrunc], + passfds: Sequence[int], +) -> int: ... diff --git a/mypy/typeshed/stdlib/pathlib.pyi b/mypy/typeshed/stdlib/pathlib.pyi index 05ad3c55086b..2a0f1760cae5 100644 --- a/mypy/typeshed/stdlib/pathlib.pyi +++ b/mypy/typeshed/stdlib/pathlib.pyi @@ -38,7 +38,6 @@ class PurePath(PathLike[str]): @property def stem(self) -> str: ... def __new__(cls: type[Self], *args: StrPath) -> Self: ... - def __hash__(self) -> int: ... def __eq__(self, other: object) -> bool: ... def __fspath__(self) -> str: ... def __lt__(self, other: PurePath) -> bool: ... diff --git a/mypy/typeshed/stdlib/plistlib.pyi b/mypy/typeshed/stdlib/plistlib.pyi index 89acc5b53851..9dcfcdb126cb 100644 --- a/mypy/typeshed/stdlib/plistlib.pyi +++ b/mypy/typeshed/stdlib/plistlib.pyi @@ -99,7 +99,6 @@ if sys.version_info >= (3, 8): def __init__(self, data: int) -> None: ... def __index__(self) -> int: ... def __reduce__(self: Self) -> tuple[type[Self], tuple[int]]: ... - def __hash__(self) -> int: ... def __eq__(self, other: object) -> bool: ... class InvalidFileException(ValueError): diff --git a/mypy/typeshed/stdlib/re.pyi b/mypy/typeshed/stdlib/re.pyi index 17b2ec011168..3e52d209eb87 100644 --- a/mypy/typeshed/stdlib/re.pyi +++ b/mypy/typeshed/stdlib/re.pyi @@ -2,10 +2,13 @@ import enum import sre_compile import sys from _typeshed import ReadableBuffer -from collections.abc import Callable, Iterator +from collections.abc import Callable, Iterator, Mapping from sre_constants import error as error -from typing import Any, AnyStr, Match as Match, Pattern as Pattern, overload -from typing_extensions import TypeAlias +from typing import Any, AnyStr, Generic, TypeVar, overload +from typing_extensions import Literal, TypeAlias, final + +if sys.version_info >= (3, 9): + from types import GenericAlias __all__ = [ "match", @@ -42,6 +45,121 @@ __all__ = [ if sys.version_info >= (3, 11): __all__ += ["NOFLAG", "RegexFlag"] +_T = TypeVar("_T") + +@final +class Match(Generic[AnyStr]): + @property + def pos(self) -> int: ... + @property + def endpos(self) -> int: ... + @property + def lastindex(self) -> int | None: ... + @property + def lastgroup(self) -> str | None: ... + @property + def string(self) -> AnyStr: ... + + # The regular expression object whose match() or search() method produced + # this match instance. + @property + def re(self) -> Pattern[AnyStr]: ... + @overload + def expand(self: Match[str], template: str) -> str: ... + @overload + def expand(self: Match[bytes], template: ReadableBuffer) -> bytes: ... + # group() returns "AnyStr" or "AnyStr | None", depending on the pattern. + @overload + def group(self, __group: Literal[0] = ...) -> AnyStr: ... + @overload + def group(self, __group: str | int) -> AnyStr | Any: ... + @overload + def group(self, __group1: str | int, __group2: str | int, *groups: str | int) -> tuple[AnyStr | Any, ...]: ... + # Each item of groups()'s return tuple is either "AnyStr" or + # "AnyStr | None", depending on the pattern. + @overload + def groups(self) -> tuple[AnyStr | Any, ...]: ... + @overload + def groups(self, default: _T) -> tuple[AnyStr | _T, ...]: ... + # Each value in groupdict()'s return dict is either "AnyStr" or + # "AnyStr | None", depending on the pattern. + @overload + def groupdict(self) -> dict[str, AnyStr | Any]: ... + @overload + def groupdict(self, default: _T) -> dict[str, AnyStr | _T]: ... + def start(self, __group: int | str = ...) -> int: ... + def end(self, __group: int | str = ...) -> int: ... + def span(self, __group: int | str = ...) -> tuple[int, int]: ... + @property + def regs(self) -> tuple[tuple[int, int], ...]: ... # undocumented + # __getitem__() returns "AnyStr" or "AnyStr | None", depending on the pattern. + @overload + def __getitem__(self, __key: Literal[0]) -> AnyStr: ... + @overload + def __getitem__(self, __key: int | str) -> AnyStr | Any: ... + def __copy__(self) -> Match[AnyStr]: ... + def __deepcopy__(self, __memo: Any) -> Match[AnyStr]: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + +@final +class Pattern(Generic[AnyStr]): + @property + def flags(self) -> int: ... + @property + def groupindex(self) -> Mapping[str, int]: ... + @property + def groups(self) -> int: ... + @property + def pattern(self) -> AnyStr: ... + @overload + def search(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> Match[str] | None: ... + @overload + def search(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> Match[bytes] | None: ... + @overload + def match(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> Match[str] | None: ... + @overload + def match(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> Match[bytes] | None: ... + @overload + def fullmatch(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> Match[str] | None: ... + @overload + def fullmatch(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> Match[bytes] | None: ... + @overload + def split(self: Pattern[str], string: str, maxsplit: int = ...) -> list[str | Any]: ... + @overload + def split(self: Pattern[bytes], string: ReadableBuffer, maxsplit: int = ...) -> list[bytes | Any]: ... + # return type depends on the number of groups in the pattern + @overload + def findall(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> list[Any]: ... + @overload + def findall(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> list[Any]: ... + @overload + def finditer(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> Iterator[Match[str]]: ... + @overload + def finditer(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> Iterator[Match[bytes]]: ... + @overload + def sub(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = ...) -> str: ... + @overload + def sub( + self: Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = ..., + ) -> bytes: ... + @overload + def subn(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = ...) -> tuple[str, int]: ... + @overload + def subn( + self: Pattern[bytes], + repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], + string: ReadableBuffer, + count: int = ..., + ) -> tuple[bytes, int]: ... + def __copy__(self) -> Pattern[AnyStr]: ... + def __deepcopy__(self, __memo: Any) -> Pattern[AnyStr]: ... + if sys.version_info >= (3, 9): + def __class_getitem__(cls, item: Any) -> GenericAlias: ... + # ----- re variables and constants ----- class RegexFlag(enum.IntFlag): diff --git a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi index 44595d5ae556..83d2df1e6da9 100644 --- a/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi +++ b/mypy/typeshed/stdlib/sqlite3/dbapi2.pyi @@ -14,7 +14,6 @@ _SqliteData: TypeAlias = str | ReadableBuffer | int | float | None _AdaptedInputData: TypeAlias = _SqliteData | Any # The Mapping must really be a dict, but making it invariant is too annoying. _Parameters: TypeAlias = SupportsLenAndGetItem[_AdaptedInputData] | Mapping[str, _AdaptedInputData] -_SqliteOutputData: TypeAlias = str | bytes | int | float | None _Adapter: TypeAlias = Callable[[_T], _SqliteData] _Converter: TypeAlias = Callable[[bytes], Any] @@ -421,7 +420,6 @@ class Row: def __getitem__(self, __index: int | str) -> Any: ... @overload def __getitem__(self, __index: slice) -> tuple[Any, ...]: ... - def __hash__(self) -> int: ... def __iter__(self) -> Iterator[Any]: ... def __len__(self) -> int: ... # These return NotImplemented for anything that is not a Row. diff --git a/mypy/typeshed/stdlib/statistics.pyi b/mypy/typeshed/stdlib/statistics.pyi index 58e7fd909f1f..a01665ad8227 100644 --- a/mypy/typeshed/stdlib/statistics.pyi +++ b/mypy/typeshed/stdlib/statistics.pyi @@ -113,7 +113,6 @@ if sys.version_info >= (3, 8): __radd__ = __add__ def __rsub__(self, x2: float | NormalDist) -> NormalDist: ... __rmul__ = __mul__ - def __hash__(self) -> int: ... if sys.version_info >= (3, 10): def correlation(__x: Sequence[_Number], __y: Sequence[_Number]) -> float: ... diff --git a/mypy/typeshed/stdlib/sys.pyi b/mypy/typeshed/stdlib/sys.pyi index 9b113e5ef674..a1c875561a87 100644 --- a/mypy/typeshed/stdlib/sys.pyi +++ b/mypy/typeshed/stdlib/sys.pyi @@ -11,7 +11,7 @@ from typing_extensions import Literal, TypeAlias, final _T = TypeVar("_T") -_OptExcInfo: TypeAlias = OptExcInfo # TODO: obsolete, remove fall 2022 or later +_OptExcInfo: TypeAlias = OptExcInfo # noqa: Y047 # TODO: obsolete, remove fall 2022 or later # Intentionally omits one deprecated and one optional method of `importlib.abc.MetaPathFinder` class _MetaPathFinder(Protocol): diff --git a/mypy/typeshed/stdlib/tkinter/__init__.pyi b/mypy/typeshed/stdlib/tkinter/__init__.pyi index 0955992d2688..d8dd463b5a8c 100644 --- a/mypy/typeshed/stdlib/tkinter/__init__.pyi +++ b/mypy/typeshed/stdlib/tkinter/__init__.pyi @@ -1,6 +1,6 @@ import _tkinter import sys -from _typeshed import StrOrBytesPath +from _typeshed import Incomplete, StrOrBytesPath from collections.abc import Callable, Mapping, Sequence from enum import Enum from tkinter.constants import * @@ -186,16 +186,10 @@ _EntryValidateCommand: TypeAlias = ( ) # example when it's sequence: entry['invalidcommand'] = [entry.register(print), '%P'] _GridIndex: TypeAlias = int | str | Literal["all"] _ImageSpec: TypeAlias = _Image | str # str can be from e.g. tkinter.image_names() -_Padding: TypeAlias = Union[ - _ScreenUnits, - tuple[_ScreenUnits], - tuple[_ScreenUnits, _ScreenUnits], - tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits], - tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits], -] _Relief: TypeAlias = Literal["raised", "sunken", "flat", "ridge", "solid", "groove"] # manual page: Tk_GetRelief _ScreenUnits: TypeAlias = str | float # Often the right type instead of int. Manual page: Tk_GetPixels -_XYScrollCommand: TypeAlias = str | Callable[[float, float], Any] # -xscrollcommand and -yscrollcommand in 'options' manual page +# -xscrollcommand and -yscrollcommand in 'options' manual page +_XYScrollCommand: TypeAlias = str | Callable[[float, float], object] _TakeFocusValue: TypeAlias = Union[int, Literal[""], Callable[[str], bool | None]] # -takefocus in manual page named 'options' if sys.version_info >= (3, 11): @@ -277,11 +271,11 @@ def NoDefaultRoot() -> None: ... _TraceMode: TypeAlias = Literal["array", "read", "write", "unset"] class Variable: - def __init__(self, master: Misc | None = ..., value: Any | None = ..., name: str | None = ...) -> None: ... - def set(self, value: Any) -> None: ... + def __init__(self, master: Misc | None = ..., value: Incomplete | None = ..., name: str | None = ...) -> None: ... + def set(self, value) -> None: ... initialize = set - def get(self) -> Any: ... - def trace_add(self, mode: _TraceMode, callback: Callable[[str, str, str], Any]) -> str: ... + def get(self): ... + def trace_add(self, mode: _TraceMode, callback: Callable[[str, str, str], object]) -> str: ... def trace_remove(self, mode: _TraceMode, cbname: str) -> None: ... def trace_info(self) -> list[tuple[tuple[_TraceMode, ...], str]]: ... def trace_variable(self, mode, callback): ... # deprecated @@ -316,8 +310,8 @@ class BooleanVar(Variable): def mainloop(n: int = ...) -> None: ... -getint: Any -getdouble: Any +getint: Incomplete +getdouble: Incomplete def getboolean(s): ... @@ -333,7 +327,7 @@ class Misc: children: dict[str, Widget] def destroy(self) -> None: ... def deletecommand(self, name: str) -> None: ... - def tk_strictMotif(self, boolean: Any | None = ...): ... + def tk_strictMotif(self, boolean: Incomplete | None = ...): ... def tk_bisque(self) -> None: ... def tk_setPalette(self, *args, **kw) -> None: ... def wait_variable(self, name: str | Variable = ...) -> None: ... @@ -357,9 +351,9 @@ class Misc: @overload def after(self, ms: int, func: None = ...) -> None: ... @overload - def after(self, ms: int | Literal["idle"], func: Callable[..., Any], *args: Any) -> str: ... + def after(self, ms: int | Literal["idle"], func: Callable[..., object], *args: Any) -> str: ... # after_idle is essentially partialmethod(after, "idle") - def after_idle(self, func: Callable[..., Any], *args: Any) -> str: ... + def after_idle(self, func: Callable[..., object], *args: Any) -> str: ... def after_cancel(self, id: str) -> None: ... def bell(self, displayof: Literal[0] | Misc | None = ...) -> None: ... def clipboard_get(self, *, displayof: Misc = ..., type: str = ...) -> str: ... @@ -375,15 +369,15 @@ class Misc: ) -> None: ... def option_clear(self) -> None: ... def option_get(self, name, className): ... - def option_readfile(self, fileName, priority: Any | None = ...) -> None: ... + def option_readfile(self, fileName, priority: Incomplete | None = ...) -> None: ... def selection_clear(self, **kw) -> None: ... def selection_get(self, **kw): ... def selection_handle(self, command, **kw) -> None: ... def selection_own(self, **kw) -> None: ... def selection_own_get(self, **kw): ... def send(self, interp, cmd, *args): ... - def lower(self, belowThis: Any | None = ...) -> None: ... - def tkraise(self, aboveThis: Any | None = ...) -> None: ... + def lower(self, belowThis: Incomplete | None = ...) -> None: ... + def tkraise(self, aboveThis: Incomplete | None = ...) -> None: ... lift = tkraise if sys.version_info >= (3, 11): def info_patchlevel(self) -> _VersionInfoType: ... @@ -449,7 +443,7 @@ class Misc: def bind( self, sequence: str | None = ..., - func: Callable[[Event[Misc]], Any] | None = ..., + func: Callable[[Event[Misc]], object] | None = ..., add: Literal["", "+"] | bool | None = ..., ) -> str: ... @overload @@ -462,7 +456,7 @@ class Misc: def bind_all( self, sequence: str | None = ..., - func: Callable[[Event[Misc]], Any] | None = ..., + func: Callable[[Event[Misc]], object] | None = ..., add: Literal["", "+"] | bool | None = ..., ) -> str: ... @overload @@ -474,7 +468,7 @@ class Misc: self, className: str, sequence: str | None = ..., - func: Callable[[Event[Misc]], Any] | None = ..., + func: Callable[[Event[Misc]], object] | None = ..., add: Literal["", "+"] | bool | None = ..., ) -> str: ... @overload @@ -490,7 +484,7 @@ class Misc: def _windowingsystem(self) -> Literal["win32", "aqua", "x11"]: ... def nametowidget(self, name: str | Misc | _tkinter.Tcl_Obj) -> Any: ... def register( - self, func: Callable[..., Any], subst: Callable[..., Sequence[Any]] | None = ..., needcleanup: int = ... + self, func: Callable[..., object], subst: Callable[..., Sequence[Any]] | None = ..., needcleanup: int = ... ) -> str: ... def keys(self) -> list[str]: ... @overload @@ -588,9 +582,9 @@ class Misc: # TODO: config is an alias of configure, but adding that here creates lots of mypy errors class CallWrapper: - func: Any - subst: Any - widget: Any + func: Incomplete + subst: Incomplete + widget: Incomplete def __init__(self, func, subst, widget) -> None: ... def __call__(self, *args): ... @@ -598,7 +592,7 @@ class XView: @overload def xview(self) -> tuple[float, float]: ... @overload - def xview(self, *args: Any) -> Any: ... + def xview(self, *args): ... def xview_moveto(self, fraction: float) -> None: ... @overload def xview_scroll(self, number: int, what: Literal["units", "pages"]) -> None: ... @@ -609,7 +603,7 @@ class YView: @overload def yview(self) -> tuple[float, float]: ... @overload - def yview(self, *args: Any) -> Any: ... + def yview(self, *args): ... def yview_moveto(self, fraction: float) -> None: ... @overload def yview_scroll(self, number: int, what: Literal["units", "pages"]) -> None: ... @@ -627,9 +621,9 @@ class Wm: @overload def wm_attributes(self) -> tuple[Any, ...]: ... @overload - def wm_attributes(self, __option: str) -> Any: ... + def wm_attributes(self, __option: str): ... @overload - def wm_attributes(self, __option: str, __value: Any, *__other_option_value_pairs: Any) -> None: ... + def wm_attributes(self, __option: str, __value, *__other_option_value_pairs: Any) -> None: ... attributes = wm_attributes def wm_client(self, name: str | None = ...) -> str: ... client = wm_client @@ -657,24 +651,28 @@ class Wm: def wm_geometry(self, newGeometry: str) -> None: ... geometry = wm_geometry def wm_grid( - self, baseWidth: Any | None = ..., baseHeight: Any | None = ..., widthInc: Any | None = ..., heightInc: Any | None = ... + self, + baseWidth: Incomplete | None = ..., + baseHeight: Incomplete | None = ..., + widthInc: Incomplete | None = ..., + heightInc: Incomplete | None = ..., ): ... grid = wm_grid - def wm_group(self, pathName: Any | None = ...): ... + def wm_group(self, pathName: Incomplete | None = ...): ... group = wm_group - def wm_iconbitmap(self, bitmap: Any | None = ..., default: Any | None = ...): ... + def wm_iconbitmap(self, bitmap: Incomplete | None = ..., default: Incomplete | None = ...): ... iconbitmap = wm_iconbitmap def wm_iconify(self) -> None: ... iconify = wm_iconify - def wm_iconmask(self, bitmap: Any | None = ...): ... + def wm_iconmask(self, bitmap: Incomplete | None = ...): ... iconmask = wm_iconmask - def wm_iconname(self, newName: Any | None = ...) -> str: ... + def wm_iconname(self, newName: Incomplete | None = ...) -> str: ... iconname = wm_iconname def wm_iconphoto(self, default: bool, __image1: Image, *args: Image) -> None: ... iconphoto = wm_iconphoto def wm_iconposition(self, x: int | None = ..., y: int | None = ...) -> tuple[int, int] | None: ... iconposition = wm_iconposition - def wm_iconwindow(self, pathName: Any | None = ...): ... + def wm_iconwindow(self, pathName: Incomplete | None = ...): ... iconwindow = wm_iconwindow def wm_manage(self, widget) -> None: ... manage = wm_manage @@ -696,7 +694,7 @@ class Wm: def wm_positionfrom(self, who: Literal["program", "user"] | None = ...) -> Literal["", "program", "user"]: ... positionfrom = wm_positionfrom @overload - def wm_protocol(self, name: str, func: Callable[[], Any] | str) -> None: ... + def wm_protocol(self, name: str, func: Callable[[], object] | str) -> None: ... @overload def wm_protocol(self, name: str, func: None = ...) -> str: ... @overload @@ -728,7 +726,7 @@ class Wm: withdraw = wm_withdraw class _ExceptionReportingCallback(Protocol): - def __call__(self, __exc: type[BaseException], __val: BaseException, __tb: TracebackType | None) -> Any: ... + def __call__(self, __exc: type[BaseException], __val: BaseException, __tb: TracebackType | None) -> object: ... class Tk(Misc, Wm): master: None @@ -923,7 +921,7 @@ class Grid: class BaseWidget(Misc): master: Misc - widgetName: Any + widgetName: Incomplete def __init__(self, master, widgetName, cnf=..., kw=..., extra=...) -> None: ... def destroy(self) -> None: ... @@ -936,7 +934,7 @@ class Widget(BaseWidget, Pack, Place, Grid): def bind( self: _W, sequence: str | None = ..., - func: Callable[[Event[_W]], Any] | None = ..., + func: Callable[[Event[_W]], object] | None = ..., add: Literal["", "+"] | bool | None = ..., ) -> str: ... @overload @@ -1126,7 +1124,7 @@ class Canvas(Widget, XView, YView): insertontime: int = ..., insertwidth: _ScreenUnits = ..., name: str = ..., - offset: Any = ..., # undocumented + offset=..., # undocumented relief: _Relief = ..., # Setting scrollregion to None doesn't reset it back to empty, # but setting it to () does. @@ -1165,7 +1163,7 @@ class Canvas(Widget, XView, YView): insertofftime: int = ..., insertontime: int = ..., insertwidth: _ScreenUnits = ..., - offset: Any = ..., # undocumented + offset=..., # undocumented relief: _Relief = ..., scrollregion: tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits] | tuple[()] = ..., selectbackground: _Color = ..., @@ -1216,7 +1214,7 @@ class Canvas(Widget, XView, YView): self, tagOrId: str | _CanvasItemId, sequence: str | None = ..., - func: Callable[[Event[Canvas]], Any] | None = ..., + func: Callable[[Event[Canvas]], object] | None = ..., add: Literal["", "+"] | bool | None = ..., ) -> str: ... @overload @@ -1226,8 +1224,8 @@ class Canvas(Widget, XView, YView): @overload def tag_bind(self, tagOrId: str | _CanvasItemId, *, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... def tag_unbind(self, tagOrId: str | _CanvasItemId, sequence: str, funcid: str | None = ...) -> None: ... - def canvasx(self, screenx, gridspacing: Any | None = ...): ... - def canvasy(self, screeny, gridspacing: Any | None = ...): ... + def canvasx(self, screenx, gridspacing: Incomplete | None = ...): ... + def canvasy(self, screeny, gridspacing: Incomplete | None = ...): ... @overload def coords(self, __tagOrId: str | _CanvasItemId) -> list[float]: ... @overload @@ -2218,7 +2216,7 @@ class Listbox(Widget, XView, YView): select_set = selection_set def size(self) -> int: ... # type: ignore[override] def itemcget(self, index: str | int, option): ... - def itemconfigure(self, index: str | int, cnf: Any | None = ..., **kw): ... + def itemconfigure(self, index: str | int, cnf: Incomplete | None = ..., **kw): ... itemconfig = itemconfigure class Menu(Widget): @@ -2241,7 +2239,7 @@ class Menu(Widget): font: _FontDescription = ..., foreground: _Color = ..., name: str = ..., - postcommand: Callable[[], Any] | str = ..., + postcommand: Callable[[], object] | str = ..., relief: _Relief = ..., selectcolor: _Color = ..., takefocus: _TakeFocusValue = ..., @@ -2249,7 +2247,7 @@ class Menu(Widget): # I guess tearoffcommand arguments are supposed to be widget objects, # but they are widget name strings. Use nametowidget() to handle the # arguments of tearoffcommand. - tearoffcommand: Callable[[str, str], Any] | str = ..., + tearoffcommand: Callable[[str, str], object] | str = ..., title: str = ..., type: Literal["menubar", "tearoff", "normal"] = ..., ) -> None: ... @@ -2271,12 +2269,12 @@ class Menu(Widget): fg: _Color = ..., font: _FontDescription = ..., foreground: _Color = ..., - postcommand: Callable[[], Any] | str = ..., + postcommand: Callable[[], object] | str = ..., relief: _Relief = ..., selectcolor: _Color = ..., takefocus: _TakeFocusValue = ..., tearoff: bool = ..., - tearoffcommand: Callable[[str, str], Any] | str = ..., + tearoffcommand: Callable[[str, str], object] | str = ..., title: str = ..., type: Literal["menubar", "tearoff", "normal"] = ..., ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @@ -2297,7 +2295,7 @@ class Menu(Widget): background: _Color = ..., bitmap: _Bitmap = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., + command: Callable[[], object] | str = ..., compound: _Compound = ..., font: _FontDescription = ..., foreground: _Color = ..., @@ -2318,7 +2316,7 @@ class Menu(Widget): background: _Color = ..., bitmap: _Bitmap = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., + command: Callable[[], object] | str = ..., compound: _Compound = ..., font: _FontDescription = ..., foreground: _Color = ..., @@ -2344,7 +2342,7 @@ class Menu(Widget): background: _Color = ..., bitmap: _Bitmap = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., + command: Callable[[], object] | str = ..., compound: _Compound = ..., font: _FontDescription = ..., foreground: _Color = ..., @@ -2364,7 +2362,7 @@ class Menu(Widget): background: _Color = ..., bitmap: _Bitmap = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., + command: Callable[[], object] | str = ..., compound: _Compound = ..., font: _FontDescription = ..., foreground: _Color = ..., @@ -2391,7 +2389,7 @@ class Menu(Widget): background: _Color = ..., bitmap: _Bitmap = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., + command: Callable[[], object] | str = ..., compound: _Compound = ..., font: _FontDescription = ..., foreground: _Color = ..., @@ -2413,7 +2411,7 @@ class Menu(Widget): background: _Color = ..., bitmap: _Bitmap = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., + command: Callable[[], object] | str = ..., compound: _Compound = ..., font: _FontDescription = ..., foreground: _Color = ..., @@ -2440,7 +2438,7 @@ class Menu(Widget): background: _Color = ..., bitmap: _Bitmap = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., + command: Callable[[], object] | str = ..., compound: _Compound = ..., font: _FontDescription = ..., foreground: _Color = ..., @@ -2461,7 +2459,7 @@ class Menu(Widget): background: _Color = ..., bitmap: _Bitmap = ..., columnbreak: int = ..., - command: Callable[[], Any] | str = ..., + command: Callable[[], object] | str = ..., compound: _Compound = ..., font: _FontDescription = ..., foreground: _Color = ..., @@ -2758,7 +2756,7 @@ class Scale(Widget): border: _ScreenUnits = ..., borderwidth: _ScreenUnits = ..., # don't know why the callback gets string instead of float - command: str | Callable[[str], Any] = ..., + command: str | Callable[[str], object] = ..., cursor: _Cursor = ..., digits: int = ..., fg: _Color = ..., @@ -2799,7 +2797,7 @@ class Scale(Widget): bigincrement: float = ..., border: _ScreenUnits = ..., borderwidth: _ScreenUnits = ..., - command: str | Callable[[str], Any] = ..., + command: str | Callable[[str], object] = ..., cursor: _Cursor = ..., digits: int = ..., fg: _Color = ..., @@ -2898,7 +2896,7 @@ class Scrollbar(Widget): @overload def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure - def activate(self, index: Any | None = ...): ... + def activate(self, index: Incomplete | None = ...): ... def delta(self, deltax: int, deltay: int) -> float: ... def fraction(self, x: int, y: int) -> float: ... def identify(self, x: int, y: int) -> Literal["arrow1", "arrow2", "slider", "trough1", "trough2", ""]: ... @@ -3046,7 +3044,7 @@ class Text(Widget, XView, YView): self, index1: _TextIndex, index2: _TextIndex | None, - command: Callable[[str, str, str], Any] | str, + command: Callable[[str, str, str], object] | str, *, all: bool = ..., image: bool = ..., @@ -3061,7 +3059,7 @@ class Text(Widget, XView, YView): index1: _TextIndex, index2: _TextIndex | None = ..., *, - command: Callable[[str, str, str], Any] | str, + command: Callable[[str, str, str], object] | str, all: bool = ..., image: bool = ..., mark: bool = ..., @@ -3081,7 +3079,7 @@ class Text(Widget, XView, YView): def get(self, index1: _TextIndex, index2: _TextIndex | None = ...) -> str: ... # TODO: image_* methods def image_cget(self, index, option): ... - def image_configure(self, index, cnf: Any | None = ..., **kw): ... + def image_configure(self, index, cnf: Incomplete | None = ..., **kw): ... def image_create(self, index, cnf=..., **kw): ... def image_names(self): ... def index(self, index: _TextIndex) -> str: ... @@ -3096,7 +3094,7 @@ class Text(Widget, XView, YView): def mark_next(self, index: _TextIndex) -> str | None: ... def mark_previous(self, index: _TextIndex) -> str | None: ... # **kw of peer_create is same as the kwargs of Text.__init__ - def peer_create(self, newPathName: str | Text, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def peer_create(self, newPathName: str | Text, cnf: dict[str, Any] = ..., **kw) -> None: ... def peer_names(self) -> tuple[_tkinter.Tcl_Obj, ...]: ... def replace(self, index1: _TextIndex, index2: _TextIndex, chars: str, *args: str | list[str] | tuple[str, ...]) -> None: ... def scan_mark(self, x: int, y: int) -> None: ... @@ -3122,14 +3120,14 @@ class Text(Widget, XView, YView): self, tagName: str, sequence: str | None, - func: Callable[[Event[Text]], Any] | None, + func: Callable[[Event[Text]], object] | None, add: Literal["", "+"] | bool | None = ..., ) -> str: ... @overload def tag_bind(self, tagName: str, sequence: str | None, func: str, add: Literal["", "+"] | bool | None = ...) -> None: ... def tag_unbind(self, tagName: str, sequence: str, funcid: str | None = ...) -> None: ... # allowing any string for cget instead of just Literals because there's no other way to look up tag options - def tag_cget(self, tagName: str, option: str) -> Any: ... + def tag_cget(self, tagName: str, option: str): ... @overload def tag_configure( self, @@ -3179,20 +3177,20 @@ class Text(Widget, XView, YView): def tag_remove(self, tagName: str, index1: _TextIndex, index2: _TextIndex | None = ...) -> None: ... # TODO: window_* methods def window_cget(self, index, option): ... - def window_configure(self, index, cnf: Any | None = ..., **kw): ... + def window_configure(self, index, cnf: Incomplete | None = ..., **kw): ... window_config = window_configure def window_create(self, index, cnf=..., **kw) -> None: ... def window_names(self): ... def yview_pickplace(self, *what): ... # deprecated class _setit: - def __init__(self, var, value, callback: Any | None = ...) -> None: ... + def __init__(self, var, value, callback: Incomplete | None = ...) -> None: ... def __call__(self, *args) -> None: ... # manual page: tk_optionMenu class OptionMenu(Menubutton): - widgetName: Any - menuname: Any + widgetName: Incomplete + menuname: Incomplete def __init__( # differs from other widgets self, @@ -3201,7 +3199,7 @@ class OptionMenu(Menubutton): value: str, *values: str, # kwarg only from now on - command: Callable[[StringVar], Any] | None = ..., + command: Callable[[StringVar], object] | None = ..., ) -> None: ... # configure, config, cget are inherited from Menubutton # destroy and __getitem__ are overridden, signature does not change @@ -3212,16 +3210,16 @@ class _Image(Protocol): def width(self) -> int: ... class Image: - name: Any + name: Incomplete tk: _tkinter.TkappType def __init__( - self, imgtype, name: Any | None = ..., cnf=..., master: Misc | _tkinter.TkappType | None = ..., **kw + self, imgtype, name: Incomplete | None = ..., cnf=..., master: Misc | _tkinter.TkappType | None = ..., **kw ) -> None: ... def __del__(self) -> None: ... def __setitem__(self, key, value) -> None: ... def __getitem__(self, key): ... - configure: Any - config: Any + configure: Incomplete + config: Incomplete def height(self) -> int: ... def type(self): ... def width(self) -> int: ... @@ -3281,7 +3279,7 @@ class PhotoImage(Image): class BitmapImage(Image): def __init__( self, - name: Any | None = ..., + name: Incomplete | None = ..., cnf: dict[str, Any] = ..., master: Misc | _tkinter.TkappType | None = ..., *, @@ -3313,7 +3311,7 @@ class Spinbox(Widget, XView): buttondownrelief: _Relief = ..., buttonuprelief: _Relief = ..., # percent substitutions don't seem to be supported, it's similar to Entry's validation stuff - command: Callable[[], Any] | str | list[str] | tuple[str, ...] = ..., + command: Callable[[], object] | str | list[str] | tuple[str, ...] = ..., cursor: _Cursor = ..., disabledbackground: _Color = ..., disabledforeground: _Color = ..., @@ -3370,7 +3368,7 @@ class Spinbox(Widget, XView): buttoncursor: _Cursor = ..., buttondownrelief: _Relief = ..., buttonuprelief: _Relief = ..., - command: Callable[[], Any] | str | list[str] | tuple[str, ...] = ..., + command: Callable[[], object] | str | list[str] | tuple[str, ...] = ..., cursor: _Cursor = ..., disabledbackground: _Color = ..., disabledforeground: _Color = ..., @@ -3415,7 +3413,7 @@ class Spinbox(Widget, XView): def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... config = configure def bbox(self, index) -> tuple[int, int, int, int] | None: ... # type: ignore[override] - def delete(self, first, last: Any | None = ...) -> Literal[""]: ... + def delete(self, first, last: Incomplete | None = ...) -> Literal[""]: ... def get(self) -> str: ... def icursor(self, index): ... def identify(self, x: int, y: int) -> Literal["", "buttondown", "buttonup", "entry"]: ... @@ -3426,10 +3424,10 @@ class Spinbox(Widget, XView): def scan(self, *args): ... def scan_mark(self, x): ... def scan_dragto(self, x): ... - def selection(self, *args: Any) -> tuple[int, ...]: ... + def selection(self, *args) -> tuple[int, ...]: ... def selection_adjust(self, index): ... def selection_clear(self): ... - def selection_element(self, element: Any | None = ...): ... + def selection_element(self, element: Incomplete | None = ...): ... if sys.version_info >= (3, 8): def selection_from(self, index: int) -> None: ... def selection_present(self) -> None: ... @@ -3562,7 +3560,7 @@ class PanedWindow(Widget): config = configure def add(self, child: Widget, **kw) -> None: ... def remove(self, child) -> None: ... - forget: Any + forget: Incomplete def identify(self, x: int, y: int): ... def proxy(self, *args): ... def proxy_coord(self): ... @@ -3573,8 +3571,8 @@ class PanedWindow(Widget): def sash_mark(self, index): ... def sash_place(self, index, x, y): ... def panecget(self, child, option): ... - def paneconfigure(self, tagOrId, cnf: Any | None = ..., **kw): ... - paneconfig: Any + def paneconfigure(self, tagOrId, cnf: Incomplete | None = ..., **kw): ... + paneconfig: Incomplete def panes(self): ... def _test() -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/colorchooser.pyi b/mypy/typeshed/stdlib/tkinter/colorchooser.pyi index e0473afa5a7a..ac2ea187bdd5 100644 --- a/mypy/typeshed/stdlib/tkinter/colorchooser.pyi +++ b/mypy/typeshed/stdlib/tkinter/colorchooser.pyi @@ -1,6 +1,6 @@ import sys from tkinter.commondialog import Dialog -from typing import Any, ClassVar +from typing import ClassVar if sys.version_info >= (3, 9): __all__ = ["Chooser", "askcolor"] @@ -8,4 +8,4 @@ if sys.version_info >= (3, 9): class Chooser(Dialog): command: ClassVar[str] -def askcolor(color: str | bytes | None = ..., **options: Any) -> tuple[None, None] | tuple[tuple[float, float, float], str]: ... +def askcolor(color: str | bytes | None = ..., **options) -> tuple[None, None] | tuple[tuple[float, float, float], str]: ... diff --git a/mypy/typeshed/stdlib/tkinter/commondialog.pyi b/mypy/typeshed/stdlib/tkinter/commondialog.pyi index faebcc33955e..49101c7e6089 100644 --- a/mypy/typeshed/stdlib/tkinter/commondialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/commondialog.pyi @@ -1,13 +1,14 @@ import sys +from _typeshed import Incomplete from collections.abc import Mapping -from typing import Any, ClassVar +from typing import ClassVar if sys.version_info >= (3, 9): __all__ = ["Dialog"] class Dialog: command: ClassVar[str | None] - master: Any | None - options: Mapping[str, Any] - def __init__(self, master: Any | None = ..., **options) -> None: ... - def show(self, **options) -> Any: ... + master: Incomplete | None + options: Mapping[str, Incomplete] + def __init__(self, master: Incomplete | None = ..., **options) -> None: ... + def show(self, **options): ... diff --git a/mypy/typeshed/stdlib/tkinter/dialog.pyi b/mypy/typeshed/stdlib/tkinter/dialog.pyi index 9ced7a208808..ef7713f40994 100644 --- a/mypy/typeshed/stdlib/tkinter/dialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/dialog.pyi @@ -1,4 +1,5 @@ import sys +from _typeshed import Incomplete from collections.abc import Mapping from tkinter import Widget from typing import Any @@ -11,5 +12,5 @@ DIALOG_ICON: str class Dialog(Widget): widgetName: str num: int - def __init__(self, master: Any | None = ..., cnf: Mapping[str, Any] = ..., **kw) -> None: ... + def __init__(self, master: Incomplete | None = ..., cnf: Mapping[str, Any] = ..., **kw) -> None: ... def destroy(self) -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/filedialog.pyi b/mypy/typeshed/stdlib/tkinter/filedialog.pyi index 2815289e81c3..d0b7e451f72c 100644 --- a/mypy/typeshed/stdlib/tkinter/filedialog.pyi +++ b/mypy/typeshed/stdlib/tkinter/filedialog.pyi @@ -1,8 +1,8 @@ import sys -from _typeshed import StrOrBytesPath +from _typeshed import Incomplete, StrOrBytesPath from collections.abc import Iterable from tkinter import Button, Entry, Frame, Listbox, Misc, Scrollbar, StringVar, Toplevel, commondialog -from typing import IO, Any, ClassVar +from typing import IO, ClassVar from typing_extensions import Literal if sys.version_info >= (3, 9): @@ -22,12 +22,12 @@ if sys.version_info >= (3, 9): "askdirectory", ] -dialogstates: dict[Any, tuple[Any, Any]] +dialogstates: dict[Incomplete, tuple[Incomplete, Incomplete]] class FileDialog: title: str - master: Any - directory: Any | None + master: Incomplete + directory: Incomplete | None top: Toplevel botframe: Frame selection: Entry @@ -41,21 +41,21 @@ class FileDialog: filter_button: Button cancel_button: Button def __init__( - self, master, title: Any | None = ... + self, master, title: Incomplete | None = ... ) -> None: ... # title is usually a str or None, but e.g. int doesn't raise en exception either - how: Any | None - def go(self, dir_or_file: Any = ..., pattern: str = ..., default: str = ..., key: Any | None = ...): ... - def quit(self, how: Any | None = ...) -> None: ... + how: Incomplete | None + def go(self, dir_or_file=..., pattern: str = ..., default: str = ..., key: Incomplete | None = ...): ... + def quit(self, how: Incomplete | None = ...) -> None: ... def dirs_double_event(self, event) -> None: ... def dirs_select_event(self, event) -> None: ... def files_double_event(self, event) -> None: ... def files_select_event(self, event) -> None: ... def ok_event(self, event) -> None: ... def ok_command(self) -> None: ... - def filter_command(self, event: Any | None = ...) -> None: ... + def filter_command(self, event: Incomplete | None = ...) -> None: ... def get_filter(self): ... def get_selection(self): ... - def cancel_command(self, event: Any | None = ...) -> None: ... + def cancel_command(self, event: Incomplete | None = ...) -> None: ... def set_filter(self, dir, pat) -> None: ... def set_selection(self, file) -> None: ... @@ -126,7 +126,7 @@ def asksaveasfile( parent: Misc | None = ..., title: str | None = ..., typevariable: StringVar | str | None = ..., -) -> IO[Any] | None: ... +) -> IO[Incomplete] | None: ... def askopenfile( mode: str = ..., *, @@ -137,7 +137,7 @@ def askopenfile( parent: Misc | None = ..., title: str | None = ..., typevariable: StringVar | str | None = ..., -) -> IO[Any] | None: ... +) -> IO[Incomplete] | None: ... def askopenfiles( mode: str = ..., *, @@ -148,5 +148,5 @@ def askopenfiles( parent: Misc | None = ..., title: str | None = ..., typevariable: StringVar | str | None = ..., -) -> tuple[IO[Any], ...]: ... # can be empty tuple +) -> tuple[IO[Incomplete], ...]: ... # can be empty tuple def test() -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/messagebox.pyi b/mypy/typeshed/stdlib/tkinter/messagebox.pyi index 96109b116786..d99c588e3cd3 100644 --- a/mypy/typeshed/stdlib/tkinter/messagebox.pyi +++ b/mypy/typeshed/stdlib/tkinter/messagebox.pyi @@ -1,6 +1,6 @@ import sys from tkinter.commondialog import Dialog -from typing import Any, ClassVar +from typing import ClassVar if sys.version_info >= (3, 9): __all__ = [ @@ -34,11 +34,11 @@ NO: str class Message(Dialog): command: ClassVar[str] -def showinfo(title: str | None = ..., message: str | None = ..., **options: Any) -> str: ... -def showwarning(title: str | None = ..., message: str | None = ..., **options: Any) -> str: ... -def showerror(title: str | None = ..., message: str | None = ..., **options: Any) -> str: ... -def askquestion(title: str | None = ..., message: str | None = ..., **options: Any) -> str: ... -def askokcancel(title: str | None = ..., message: str | None = ..., **options: Any) -> bool: ... -def askyesno(title: str | None = ..., message: str | None = ..., **options: Any) -> bool: ... -def askyesnocancel(title: str | None = ..., message: str | None = ..., **options: Any) -> bool | None: ... -def askretrycancel(title: str | None = ..., message: str | None = ..., **options: Any) -> bool: ... +def showinfo(title: str | None = ..., message: str | None = ..., **options) -> str: ... +def showwarning(title: str | None = ..., message: str | None = ..., **options) -> str: ... +def showerror(title: str | None = ..., message: str | None = ..., **options) -> str: ... +def askquestion(title: str | None = ..., message: str | None = ..., **options) -> str: ... +def askokcancel(title: str | None = ..., message: str | None = ..., **options) -> bool: ... +def askyesno(title: str | None = ..., message: str | None = ..., **options) -> bool: ... +def askyesnocancel(title: str | None = ..., message: str | None = ..., **options) -> bool | None: ... +def askretrycancel(title: str | None = ..., message: str | None = ..., **options) -> bool: ... diff --git a/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi b/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi index 00309431d457..72f6ca8c0687 100644 --- a/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi +++ b/mypy/typeshed/stdlib/tkinter/scrolledtext.pyi @@ -1,5 +1,4 @@ from tkinter import Frame, Misc, Scrollbar, Text -from typing import Any __all__ = ["ScrolledText"] @@ -7,4 +6,4 @@ __all__ = ["ScrolledText"] class ScrolledText(Text): frame: Frame vbar: Scrollbar - def __init__(self, master: Misc | None = ..., **kwargs: Any) -> None: ... + def __init__(self, master: Misc | None = ..., **kwargs) -> None: ... diff --git a/mypy/typeshed/stdlib/tkinter/tix.pyi b/mypy/typeshed/stdlib/tkinter/tix.pyi index 6f9201a1bdf9..db568bc4abef 100644 --- a/mypy/typeshed/stdlib/tkinter/tix.pyi +++ b/mypy/typeshed/stdlib/tkinter/tix.pyi @@ -1,4 +1,5 @@ import tkinter +from _typeshed import Incomplete from typing import Any from typing_extensions import Literal @@ -56,12 +57,12 @@ class TixWidget(tkinter.Widget): cnf: dict[str, Any] = ..., kw: dict[str, Any] = ..., ) -> None: ... - def __getattr__(self, name: str) -> Any: ... + def __getattr__(self, name: str): ... def set_silent(self, value: str) -> None: ... def subwidget(self, name: str) -> tkinter.Widget: ... def subwidgets_all(self) -> list[tkinter.Widget]: ... def config_all(self, option: Any, value: Any) -> None: ... - def image_create(self, imgtype: str, cnf: dict[str, Any] = ..., master: tkinter.Widget | None = ..., **kw: Any) -> None: ... + def image_create(self, imgtype: str, cnf: dict[str, Any] = ..., master: tkinter.Widget | None = ..., **kw) -> None: ... def image_delete(self, imgname: str) -> None: ... class TixSubWidget(TixWidget): @@ -70,102 +71,102 @@ class TixSubWidget(TixWidget): ) -> None: ... class DisplayStyle: - def __init__(self, itemtype: str, cnf: dict[str, Any] = ..., *, master: tkinter.Widget | None = ..., **kw: Any) -> None: ... - def __getitem__(self, key: str) -> Any: ... + def __init__(self, itemtype: str, cnf: dict[str, Any] = ..., *, master: tkinter.Widget | None = ..., **kw) -> None: ... + def __getitem__(self, key: str): ... def __setitem__(self, key: str, value: Any) -> None: ... def delete(self) -> None: ... - def config(self, cnf: dict[str, Any] = ..., **kw: Any) -> Any: ... + def config(self, cnf: dict[str, Any] = ..., **kw): ... class Balloon(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def bind_widget(self, widget: tkinter.Widget, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw) -> None: ... + def bind_widget(self, widget: tkinter.Widget, cnf: dict[str, Any] = ..., **kw) -> None: ... def unbind_widget(self, widget: tkinter.Widget) -> None: ... class ButtonBox(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> tkinter.Widget: ... + def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = ..., **kw) -> tkinter.Widget: ... def invoke(self, name: str) -> None: ... class ComboBox(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw) -> None: ... def add_history(self, str: str) -> None: ... def append_history(self, str: str) -> None: ... def insert(self, index: int, str: str) -> None: ... def pick(self, index: int) -> None: ... class Control(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw) -> None: ... def decrement(self) -> None: ... def increment(self) -> None: ... def invoke(self) -> None: ... class LabelEntry(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw) -> None: ... class LabelFrame(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw) -> None: ... class Meter(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw) -> None: ... class OptionMenu(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add_command(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add_separator(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw) -> None: ... + def add_command(self, name: str, cnf: dict[str, Any] = ..., **kw) -> None: ... + def add_separator(self, name: str, cnf: dict[str, Any] = ..., **kw) -> None: ... def delete(self, name: str) -> None: ... def disable(self, name: str) -> None: ... def enable(self, name: str) -> None: ... class PopupMenu(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw) -> None: ... def bind_widget(self, widget: tkinter.Widget) -> None: ... def unbind_widget(self, widget: tkinter.Widget) -> None: ... def post_widget(self, widget: tkinter.Widget, x: int, y: int) -> None: ... class Select(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> tkinter.Widget: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = ..., **kw) -> tkinter.Widget: ... def invoke(self, name: str) -> None: ... class StdButtonBox(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw) -> None: ... def invoke(self, name: str) -> None: ... class DirList(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw) -> None: ... def chdir(self, dir: str) -> None: ... class DirTree(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw) -> None: ... def chdir(self, dir: str) -> None: ... class DirSelectDialog(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw) -> None: ... def popup(self) -> None: ... def popdown(self) -> None: ... class DirSelectBox(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw) -> None: ... class ExFileSelectBox(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw) -> None: ... def filter(self) -> None: ... def invoke(self) -> None: ... class FileSelectBox(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw) -> None: ... def apply_filter(self) -> None: ... def invoke(self) -> None: ... class FileEntry(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw) -> None: ... def invoke(self) -> None: ... def file_dialog(self) -> None: ... class HList(TixWidget, tkinter.XView, tkinter.YView): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add(self, entry: str, cnf: dict[str, Any] = ..., **kw: Any) -> tkinter.Widget: ... - def add_child(self, parent: str | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> tkinter.Widget: ... + def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw) -> None: ... + def add(self, entry: str, cnf: dict[str, Any] = ..., **kw) -> tkinter.Widget: ... + def add_child(self, parent: str | None = ..., cnf: dict[str, Any] = ..., **kw) -> tkinter.Widget: ... def anchor_set(self, entry: str) -> None: ... def anchor_clear(self) -> None: ... # FIXME: Overload, certain combos return, others don't @@ -178,17 +179,17 @@ class HList(TixWidget, tkinter.XView, tkinter.YView): def dragsite_clear(self) -> None: ... def dropsite_set(self, index: int) -> None: ... def dropsite_clear(self) -> None: ... - def header_create(self, col: int, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def header_configure(self, col: int, cnf: dict[str, Any] = ..., **kw: Any) -> Any | None: ... - def header_cget(self, col: int, opt: Any) -> Any: ... + def header_create(self, col: int, cnf: dict[str, Any] = ..., **kw) -> None: ... + def header_configure(self, col: int, cnf: dict[str, Any] = ..., **kw) -> Incomplete | None: ... + def header_cget(self, col: int, opt): ... def header_exists(self, col: int) -> bool: ... def header_exist(self, col: int) -> bool: ... def header_delete(self, col: int) -> None: ... def header_size(self, col: int) -> int: ... def hide_entry(self, entry: str) -> None: ... - def indicator_create(self, entry: str, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def indicator_configure(self, entry: str, cnf: dict[str, Any] = ..., **kw: Any) -> Any | None: ... - def indicator_cget(self, entry: str, opt: Any) -> Any: ... + def indicator_create(self, entry: str, cnf: dict[str, Any] = ..., **kw) -> None: ... + def indicator_configure(self, entry: str, cnf: dict[str, Any] = ..., **kw) -> Incomplete | None: ... + def indicator_cget(self, entry: str, opt): ... def indicator_exists(self, entry: str) -> bool: ... def indicator_delete(self, entry: str) -> None: ... def indicator_size(self, entry: str) -> int: ... @@ -204,22 +205,22 @@ class HList(TixWidget, tkinter.XView, tkinter.YView): def info_parent(self, entry: str) -> str: ... def info_prev(self, entry: str) -> str: ... def info_selection(self) -> tuple[str, ...]: ... - def item_cget(self, entry: str, col: int, opt: Any) -> Any: ... - def item_configure(self, entry: str, col: int, cnf: dict[str, Any] = ..., **kw: Any) -> Any | None: ... - def item_create(self, entry: str, col: int, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def item_cget(self, entry: str, col: int, opt): ... + def item_configure(self, entry: str, col: int, cnf: dict[str, Any] = ..., **kw) -> Incomplete | None: ... + def item_create(self, entry: str, col: int, cnf: dict[str, Any] = ..., **kw) -> None: ... def item_exists(self, entry: str, col: int) -> bool: ... def item_delete(self, entry: str, col: int) -> None: ... - def entrycget(self, entry: str, opt: Any) -> Any: ... - def entryconfigure(self, entry: str, cnf: dict[str, Any] = ..., **kw: Any) -> Any | None: ... + def entrycget(self, entry: str, opt): ... + def entryconfigure(self, entry: str, cnf: dict[str, Any] = ..., **kw) -> Incomplete | None: ... def nearest(self, y: int) -> str: ... def see(self, entry: str) -> None: ... - def selection_clear(self, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def selection_clear(self, cnf: dict[str, Any] = ..., **kw) -> None: ... def selection_includes(self, entry: str) -> bool: ... def selection_set(self, first: str, last: str | None = ...) -> None: ... def show_entry(self, entry: str) -> None: ... class CheckList(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw) -> None: ... def autosetmode(self) -> None: ... def close(self, entrypath: str) -> None: ... def getmode(self, entrypath: str) -> str: ... @@ -229,7 +230,7 @@ class CheckList(TixWidget): def setstatus(self, entrypath: str, mode: str = ...) -> None: ... class Tree(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw) -> None: ... def autosetmode(self) -> None: ... def close(self, entrypath: str) -> None: ... def getmode(self, entrypath: str) -> str: ... @@ -237,7 +238,7 @@ class Tree(TixWidget): def setmode(self, entrypath: str, mode: str = ...) -> None: ... class TList(TixWidget, tkinter.XView, tkinter.YView): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw) -> None: ... def active_set(self, index: int) -> None: ... def active_clear(self) -> None: ... def anchor_set(self, index: int) -> None: ... @@ -247,7 +248,7 @@ class TList(TixWidget, tkinter.XView, tkinter.YView): def dragsite_clear(self) -> None: ... def dropsite_set(self, index: int) -> None: ... def dropsite_clear(self) -> None: ... - def insert(self, index: int, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def insert(self, index: int, cnf: dict[str, Any] = ..., **kw) -> None: ... def info_active(self) -> int: ... def info_anchor(self) -> int: ... def info_down(self, index: int) -> int: ... @@ -258,29 +259,29 @@ class TList(TixWidget, tkinter.XView, tkinter.YView): def info_up(self, index: int) -> int: ... def nearest(self, x: int, y: int) -> int: ... def see(self, index: int) -> None: ... - def selection_clear(self, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def selection_clear(self, cnf: dict[str, Any] = ..., **kw) -> None: ... def selection_includes(self, index: int) -> bool: ... def selection_set(self, first: int, last: int | None = ...) -> None: ... class PanedWindow(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = ..., **kw) -> None: ... def delete(self, name: str) -> None: ... def forget(self, name: str) -> None: ... # type: ignore[override] - def panecget(self, entry: str, opt: Any) -> Any: ... - def paneconfigure(self, entry: str, cnf: dict[str, Any] = ..., **kw: Any) -> Any | None: ... + def panecget(self, entry: str, opt): ... + def paneconfigure(self, entry: str, cnf: dict[str, Any] = ..., **kw) -> Incomplete | None: ... def panes(self) -> list[tkinter.Widget]: ... class ListNoteBook(TixWidget): - def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = ..., **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = ..., **kw) -> None: ... def page(self, name: str) -> tkinter.Widget: ... def pages(self) -> list[tkinter.Widget]: ... def raise_page(self, name: str) -> None: ... class NoteBook(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def add(self, name: str, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw) -> None: ... + def add(self, name: str, cnf: dict[str, Any] = ..., **kw) -> None: ... def delete(self, name: str) -> None: ... def page(self, name: str) -> tkinter.Widget: ... def pages(self) -> list[tkinter.Widget]: ... @@ -288,14 +289,14 @@ class NoteBook(TixWidget): def raised(self) -> bool: ... class InputOnly(TixWidget): - def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def __init__(self, master: tkinter.Widget | None = ..., cnf: dict[str, Any] = ..., **kw) -> None: ... class Form: def __setitem__(self, key: str, value: Any) -> None: ... - def config(self, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... - def form(self, cnf: dict[str, Any] = ..., **kw: Any) -> None: ... + def config(self, cnf: dict[str, Any] = ..., **kw) -> None: ... + def form(self, cnf: dict[str, Any] = ..., **kw) -> None: ... def check(self) -> bool: ... def forget(self) -> None: ... def grid(self, xsize: int = ..., ysize: int = ...) -> tuple[int, int] | None: ... - def info(self, option: str | None = ...) -> Any: ... + def info(self, option: str | None = ...): ... def slaves(self) -> list[tkinter.Widget]: ... diff --git a/mypy/typeshed/stdlib/tkinter/ttk.pyi b/mypy/typeshed/stdlib/tkinter/ttk.pyi index 81077200289f..a191b3be281a 100644 --- a/mypy/typeshed/stdlib/tkinter/ttk.pyi +++ b/mypy/typeshed/stdlib/tkinter/ttk.pyi @@ -1,9 +1,10 @@ import _tkinter import sys import tkinter +from _typeshed import Incomplete from collections.abc import Callable from tkinter.font import _FontDescription -from typing import Any, overload +from typing import Any, Union, overload from typing_extensions import Literal, TypeAlias, TypedDict __all__ = [ @@ -35,23 +36,31 @@ __all__ = [ ] def tclobjs_to_py(adict: dict[Any, Any]) -> dict[Any, Any]: ... -def setup_master(master: Any | None = ...): ... +def setup_master(master: Incomplete | None = ...): ... + +_Padding: TypeAlias = Union[ + tkinter._ScreenUnits, + tuple[tkinter._ScreenUnits], + tuple[tkinter._ScreenUnits, tkinter._ScreenUnits], + tuple[tkinter._ScreenUnits, tkinter._ScreenUnits, tkinter._ScreenUnits], + tuple[tkinter._ScreenUnits, tkinter._ScreenUnits, tkinter._ScreenUnits, tkinter._ScreenUnits], +] # from ttk_widget (aka ttk::widget) manual page, differs from tkinter._Compound _TtkCompound: TypeAlias = Literal["text", "image", tkinter._Compound] class Style: - master: Any + master: Incomplete tk: _tkinter.TkappType def __init__(self, master: tkinter.Misc | None = ...) -> None: ... - def configure(self, style, query_opt: Any | None = ..., **kw): ... - def map(self, style, query_opt: Any | None = ..., **kw): ... - def lookup(self, style, option, state: Any | None = ..., default: Any | None = ...): ... - def layout(self, style, layoutspec: Any | None = ...): ... + def configure(self, style, query_opt: Incomplete | None = ..., **kw): ... + def map(self, style, query_opt: Incomplete | None = ..., **kw): ... + def lookup(self, style, option, state: Incomplete | None = ..., default: Incomplete | None = ...): ... + def layout(self, style, layoutspec: Incomplete | None = ...): ... def element_create(self, elementname, etype, *args, **kw) -> None: ... def element_names(self): ... def element_options(self, elementname): ... - def theme_create(self, themename, parent: Any | None = ..., settings: Any | None = ...) -> None: ... + def theme_create(self, themename, parent: Incomplete | None = ..., settings: Incomplete | None = ...) -> None: ... def theme_settings(self, themename, settings) -> None: ... def theme_names(self) -> tuple[str, ...]: ... @overload @@ -60,10 +69,10 @@ class Style: def theme_use(self, themename: None = ...) -> str: ... class Widget(tkinter.Widget): - def __init__(self, master: tkinter.Misc | None, widgetname, kw: Any | None = ...) -> None: ... + def __init__(self, master: tkinter.Misc | None, widgetname, kw: Incomplete | None = ...) -> None: ... def identify(self, x: int, y: int) -> str: ... - def instate(self, statespec, callback: Any | None = ..., *args, **kw): ... - def state(self, statespec: Any | None = ...): ... + def instate(self, statespec, callback: Incomplete | None = ..., *args, **kw): ... + def state(self, statespec: Incomplete | None = ...): ... class Button(Widget): def __init__( @@ -77,7 +86,7 @@ class Button(Widget): default: Literal["normal", "active", "disabled"] = ..., image: tkinter._ImageSpec = ..., name: str = ..., - padding: Any = ..., # undocumented + padding=..., # undocumented state: str = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -96,7 +105,7 @@ class Button(Widget): cursor: tkinter._Cursor = ..., default: Literal["normal", "active", "disabled"] = ..., image: tkinter._ImageSpec = ..., - padding: Any = ..., + padding=..., state: str = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -123,7 +132,7 @@ class Checkbutton(Widget): name: str = ..., offvalue: Any = ..., onvalue: Any = ..., - padding: Any = ..., # undocumented + padding=..., # undocumented state: str = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -147,7 +156,7 @@ class Checkbutton(Widget): image: tkinter._ImageSpec = ..., offvalue: Any = ..., onvalue: Any = ..., - padding: Any = ..., + padding=..., state: str = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -255,8 +264,8 @@ class Combobox(Entry): invalidcommand: tkinter._EntryValidateCommand = ..., # undocumented justify: Literal["left", "center", "right"] = ..., name: str = ..., - postcommand: Callable[[], Any] | str = ..., - show: Any = ..., # undocumented + postcommand: Callable[[], object] | str = ..., + show=..., # undocumented state: str = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -280,8 +289,8 @@ class Combobox(Entry): height: int = ..., invalidcommand: tkinter._EntryValidateCommand = ..., justify: Literal["left", "center", "right"] = ..., - postcommand: Callable[[], Any] | str = ..., - show: Any = ..., + postcommand: Callable[[], object] | str = ..., + show=..., state: str = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -308,8 +317,8 @@ class Combobox(Entry): height: int = ..., invalidcommand: tkinter._EntryValidateCommand = ..., justify: Literal["left", "center", "right"] = ..., - postcommand: Callable[[], Any] | str = ..., - show: Any = ..., + postcommand: Callable[[], object] | str = ..., + show=..., state: str = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -336,7 +345,7 @@ class Frame(Widget): cursor: tkinter._Cursor = ..., height: tkinter._ScreenUnits = ..., name: str = ..., - padding: tkinter._Padding = ..., + padding: _Padding = ..., relief: tkinter._Relief = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -351,7 +360,7 @@ class Frame(Widget): borderwidth: tkinter._ScreenUnits = ..., cursor: tkinter._Cursor = ..., height: tkinter._ScreenUnits = ..., - padding: tkinter._Padding = ..., + padding: _Padding = ..., relief: tkinter._Relief = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -378,7 +387,7 @@ class Label(Widget): image: tkinter._ImageSpec = ..., justify: Literal["left", "center", "right"] = ..., name: str = ..., - padding: tkinter._Padding = ..., + padding: _Padding = ..., relief: tkinter._Relief = ..., state: str = ..., style: str = ..., @@ -404,7 +413,7 @@ class Label(Widget): foreground: tkinter._Color = ..., image: tkinter._ImageSpec = ..., justify: Literal["left", "center", "right"] = ..., - padding: tkinter._Padding = ..., + padding: _Padding = ..., relief: tkinter._Relief = ..., state: str = ..., style: str = ..., @@ -432,7 +441,7 @@ class Labelframe(Widget): labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., labelwidget: tkinter.Misc = ..., name: str = ..., - padding: tkinter._Padding = ..., + padding: _Padding = ..., relief: tkinter._Relief = ..., # undocumented style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -451,7 +460,7 @@ class Labelframe(Widget): height: tkinter._ScreenUnits = ..., labelanchor: Literal["nw", "n", "ne", "en", "e", "es", "se", "s", "sw", "ws", "w", "wn"] = ..., labelwidget: tkinter.Misc = ..., - padding: tkinter._Padding = ..., + padding: _Padding = ..., relief: tkinter._Relief = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -477,7 +486,7 @@ class Menubutton(Widget): image: tkinter._ImageSpec = ..., menu: tkinter.Menu = ..., name: str = ..., - padding: Any = ..., # undocumented + padding=..., # undocumented state: str = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -496,7 +505,7 @@ class Menubutton(Widget): direction: Literal["above", "below", "left", "right", "flush"] = ..., image: tkinter._ImageSpec = ..., menu: tkinter.Menu = ..., - padding: Any = ..., + padding=..., state: str = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -518,7 +527,7 @@ class Notebook(Widget): cursor: tkinter._Cursor = ..., height: int = ..., name: str = ..., - padding: tkinter._Padding = ..., + padding: _Padding = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., width: int = ..., @@ -530,7 +539,7 @@ class Notebook(Widget): *, cursor: tkinter._Cursor = ..., height: int = ..., - padding: tkinter._Padding = ..., + padding: _Padding = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., width: int = ..., @@ -544,9 +553,9 @@ class Notebook(Widget): *, state: Literal["normal", "disabled", "hidden"] = ..., sticky: str = ..., # consists of letters 'n', 's', 'w', 'e', no repeats, may be empty - padding: tkinter._Padding = ..., + padding: _Padding = ..., text: str = ..., - image: Any = ..., # Sequence of an image name, followed by zero or more (sequences of one or more state names followed by an image name) + image=..., # Sequence of an image name, followed by zero or more (sequences of one or more state names followed by an image name) compound: tkinter._Compound = ..., underline: int = ..., ) -> None: ... @@ -555,8 +564,8 @@ class Notebook(Widget): def identify(self, x: int, y: int) -> str: ... def index(self, tab_id): ... def insert(self, pos, child, **kw) -> None: ... - def select(self, tab_id: Any | None = ...): ... - def tab(self, tab_id, option: Any | None = ..., **kw): ... + def select(self, tab_id: Incomplete | None = ...): ... + def tab(self, tab_id, option: Incomplete | None = ..., **kw): ... def tabs(self): ... def enable_traversal(self) -> None: ... @@ -603,10 +612,10 @@ class Panedwindow(Widget, tkinter.PanedWindow): ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ... @overload def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ... - forget: Any + forget: Incomplete def insert(self, pos, child, **kw) -> None: ... - def pane(self, pane, option: Any | None = ..., **kw): ... - def sashpos(self, index, newpos: Any | None = ...): ... + def pane(self, pane, option: Incomplete | None = ..., **kw): ... + def sashpos(self, index, newpos: Incomplete | None = ...): ... PanedWindow = Panedwindow @@ -662,7 +671,7 @@ class Radiobutton(Widget): cursor: tkinter._Cursor = ..., image: tkinter._ImageSpec = ..., name: str = ..., - padding: Any = ..., # undocumented + padding=..., # undocumented state: str = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -682,7 +691,7 @@ class Radiobutton(Widget): compound: _TtkCompound = ..., cursor: tkinter._Cursor = ..., image: tkinter._ImageSpec = ..., - padding: Any = ..., + padding=..., state: str = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -705,7 +714,7 @@ class Scale(Widget, tkinter.Scale): # type: ignore[misc] master: tkinter.Misc | None = ..., *, class_: str = ..., - command: str | Callable[[str], Any] = ..., + command: str | Callable[[str], object] = ..., cursor: tkinter._Cursor = ..., from_: float = ..., length: tkinter._ScreenUnits = ..., @@ -723,7 +732,7 @@ class Scale(Widget, tkinter.Scale): # type: ignore[misc] self, cnf: dict[str, Any] | None = ..., *, - command: str | Callable[[str], Any] = ..., + command: str | Callable[[str], object] = ..., cursor: tkinter._Cursor = ..., from_: float = ..., length: tkinter._ScreenUnits = ..., @@ -743,7 +752,7 @@ class Scale(Widget, tkinter.Scale): # type: ignore[misc] self, cnf: dict[str, Any] | None = ..., *, - command: str | Callable[[str], Any] = ..., + command: str | Callable[[str], object] = ..., cursor: tkinter._Cursor = ..., from_: float = ..., length: tkinter._ScreenUnits = ..., @@ -858,7 +867,7 @@ class Spinbox(Entry): *, background: tkinter._Color = ..., # undocumented class_: str = ..., - command: Callable[[], Any] | str | list[str] | tuple[str, ...] = ..., + command: Callable[[], object] | str | list[str] | tuple[str, ...] = ..., cursor: tkinter._Cursor = ..., exportselection: bool = ..., # undocumented font: _FontDescription = ..., # undocumented @@ -869,7 +878,7 @@ class Spinbox(Entry): invalidcommand: tkinter._EntryValidateCommand = ..., # undocumented justify: Literal["left", "center", "right"] = ..., # undocumented name: str = ..., - show: Any = ..., # undocumented + show=..., # undocumented state: str = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -888,7 +897,7 @@ class Spinbox(Entry): cnf: dict[str, Any] | None = ..., *, background: tkinter._Color = ..., - command: Callable[[], Any] | str | list[str] | tuple[str, ...] = ..., + command: Callable[[], object] | str | list[str] | tuple[str, ...] = ..., cursor: tkinter._Cursor = ..., exportselection: bool = ..., font: _FontDescription = ..., @@ -898,7 +907,7 @@ class Spinbox(Entry): increment: float = ..., invalidcommand: tkinter._EntryValidateCommand = ..., justify: Literal["left", "center", "right"] = ..., - show: Any = ..., + show=..., state: str = ..., style: str = ..., takefocus: tkinter._TakeFocusValue = ..., @@ -957,7 +966,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): displaycolumns: str | list[str] | tuple[str, ...] | list[int] | tuple[int, ...] | Literal["#all"] = ..., height: int = ..., name: str = ..., - padding: tkinter._Padding = ..., + padding: _Padding = ..., selectmode: Literal["extended", "browse", "none"] = ..., # list/tuple of Literal don't actually work in mypy # @@ -978,7 +987,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): cursor: tkinter._Cursor = ..., displaycolumns: str | list[str] | tuple[str, ...] | list[int] | tuple[int, ...] | Literal["#all"] = ..., height: int = ..., - padding: tkinter._Padding = ..., + padding: _Padding = ..., selectmode: Literal["extended", "browse", "none"] = ..., show: Literal["tree", "headings", "tree headings", ""] | list[str] | tuple[str, ...] = ..., style: str = ..., @@ -1042,7 +1051,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): text: str = ..., image: tkinter._ImageSpec = ..., anchor: tkinter._Anchor = ..., - command: str | Callable[[], Any] = ..., + command: str | Callable[[], object] = ..., ) -> None: ... def identify(self, component, x, y): ... # Internal Method. Leave untyped def identify_row(self, y: int) -> str: ... @@ -1098,7 +1107,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): if sys.version_info >= (3, 8): def selection(self) -> tuple[str, ...]: ... else: - def selection(self, selop: Any | None = ..., items: Any | None = ...) -> tuple[str, ...]: ... + def selection(self, selop: Incomplete | None = ..., items: Incomplete | None = ...) -> tuple[str, ...]: ... def selection_set(self, items: str | list[str] | tuple[str, ...]) -> None: ... def selection_add(self, items: str | list[str] | tuple[str, ...]) -> None: ... @@ -1114,7 +1123,7 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): # Also, it's 'callback' instead of 'func' here. @overload def tag_bind( - self, tagname: str, sequence: str | None = ..., callback: Callable[[tkinter.Event[Treeview]], Any] | None = ... + self, tagname: str, sequence: str | None = ..., callback: Callable[[tkinter.Event[Treeview]], object] | None = ... ) -> str: ... @overload def tag_bind(self, tagname: str, sequence: str | None, callback: str) -> None: ... @@ -1144,8 +1153,8 @@ class Treeview(Widget, tkinter.XView, tkinter.YView): def tag_has(self, tagname: str, item: str) -> bool: ... class LabeledScale(Frame): - label: Any - scale: Any + label: Incomplete + scale: Incomplete # TODO: don't any-type **kw. That goes to Frame.__init__. def __init__( self, @@ -1155,7 +1164,7 @@ class LabeledScale(Frame): to: float = ..., *, compound: Literal["top", "bottom"] = ..., - **kw: Any, + **kw, ) -> None: ... # destroy is overridden, signature does not change value: Any @@ -1170,8 +1179,8 @@ class OptionMenu(Menubutton): # rest of these are keyword-only because *args syntax used above style: str = ..., direction: Literal["above", "below", "left", "right", "flush"] = ..., - command: Callable[[tkinter.StringVar], Any] | None = ..., + command: Callable[[tkinter.StringVar], object] | None = ..., ) -> None: ... # configure, config, cget, destroy are inherited from Menubutton # destroy and __setitem__ are overridden, signature does not change - def set_menu(self, default: Any | None = ..., *values) -> None: ... + def set_menu(self, default: Incomplete | None = ..., *values) -> None: ... diff --git a/mypy/typeshed/stdlib/traceback.pyi b/mypy/typeshed/stdlib/traceback.pyi index dbbcc824a04c..fcaa39bf42f7 100644 --- a/mypy/typeshed/stdlib/traceback.pyi +++ b/mypy/typeshed/stdlib/traceback.pyi @@ -2,7 +2,7 @@ import sys from _typeshed import Self, SupportsWrite from collections.abc import Generator, Iterable, Iterator, Mapping from types import FrameType, TracebackType -from typing import IO, Any, overload +from typing import Any, overload from typing_extensions import Literal, TypeAlias __all__ = [ @@ -29,7 +29,7 @@ __all__ = [ _PT: TypeAlias = tuple[str, int, str, str | None] -def print_tb(tb: TracebackType | None, limit: int | None = ..., file: IO[str] | None = ...) -> None: ... +def print_tb(tb: TracebackType | None, limit: int | None = ..., file: SupportsWrite[str] | None = ...) -> None: ... if sys.version_info >= (3, 10): @overload @@ -38,12 +38,12 @@ if sys.version_info >= (3, 10): value: BaseException | None = ..., tb: TracebackType | None = ..., limit: int | None = ..., - file: IO[str] | None = ..., + file: SupportsWrite[str] | None = ..., chain: bool = ..., ) -> None: ... @overload def print_exception( - __exc: BaseException, *, limit: int | None = ..., file: IO[str] | None = ..., chain: bool = ... + __exc: BaseException, *, limit: int | None = ..., file: SupportsWrite[str] | None = ..., chain: bool = ... ) -> None: ... @overload def format_exception( @@ -62,7 +62,7 @@ else: value: BaseException | None, tb: TracebackType | None, limit: int | None = ..., - file: IO[str] | None = ..., + file: SupportsWrite[str] | None = ..., chain: bool = ..., ) -> None: ... def format_exception( @@ -73,9 +73,9 @@ else: chain: bool = ..., ) -> list[str]: ... -def print_exc(limit: int | None = ..., file: IO[str] | None = ..., chain: bool = ...) -> None: ... -def print_last(limit: int | None = ..., file: IO[str] | None = ..., chain: bool = ...) -> None: ... -def print_stack(f: FrameType | None = ..., limit: int | None = ..., file: IO[str] | None = ...) -> None: ... +def print_exc(limit: int | None = ..., file: SupportsWrite[str] | None = ..., chain: bool = ...) -> None: ... +def print_last(limit: int | None = ..., file: SupportsWrite[str] | None = ..., chain: bool = ...) -> None: ... +def print_stack(f: FrameType | None = ..., limit: int | None = ..., file: SupportsWrite[str] | None = ...) -> None: ... def extract_tb(tb: TracebackType | None, limit: int | None = ...) -> StackSummary: ... def extract_stack(f: FrameType | None = ..., limit: int | None = ...) -> StackSummary: ... def format_list(extracted_list: list[FrameSummary]) -> list[str]: ... diff --git a/mypy/typeshed/stdlib/types.pyi b/mypy/typeshed/stdlib/types.pyi index 1af4420e684d..28fce697f2ca 100644 --- a/mypy/typeshed/stdlib/types.pyi +++ b/mypy/typeshed/stdlib/types.pyi @@ -13,11 +13,10 @@ from collections.abc import ( MutableSequence, ValuesView, ) -from importlib.abc import _LoaderProtocol from importlib.machinery import ModuleSpec # pytype crashes if types.MappingProxyType inherits from collections.abc.Mapping instead of typing.Mapping -from typing import Any, ClassVar, Generic, Mapping, TypeVar, overload # noqa: Y027 +from typing import Any, ClassVar, Generic, Mapping, Protocol, TypeVar, overload # noqa: Y027 from typing_extensions import Literal, ParamSpec, final __all__ = [ @@ -325,6 +324,9 @@ class SimpleNamespace: def __setattr__(self, __name: str, __value: Any) -> None: ... def __delattr__(self, __name: str) -> None: ... +class _LoaderProtocol(Protocol): + def load_module(self, fullname: str) -> ModuleType: ... + class ModuleType: __name__: str __file__: str | None diff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi index 980505271e66..a186bb92bf00 100644 --- a/mypy/typeshed/stdlib/typing.pyi +++ b/mypy/typeshed/stdlib/typing.pyi @@ -1,7 +1,10 @@ +import _typeshed import collections # Needed by aliases like DefaultDict, see mypy issue 2986 import sys -from _typeshed import IdentityFunction, Incomplete, ReadableBuffer, Self as TypeshedSelf, SupportsKeysAndGetItem +from _typeshed import IdentityFunction, Incomplete, SupportsKeysAndGetItem from abc import ABCMeta, abstractmethod +from contextlib import AbstractAsyncContextManager, AbstractContextManager +from re import Match as Match, Pattern as Pattern from types import ( BuiltinFunctionType, CodeType, @@ -14,10 +17,7 @@ from types import ( TracebackType, WrapperDescriptorType, ) -from typing_extensions import Literal as _Literal, ParamSpec as _ParamSpec, final as _final - -if sys.version_info >= (3, 9): - from types import GenericAlias +from typing_extensions import ParamSpec as _ParamSpec, final as _final __all__ = [ "AbstractSet", @@ -120,6 +120,9 @@ if sys.version_info >= (3, 11): "reveal_type", ] +ContextManager = AbstractContextManager +AsyncContextManager = AbstractAsyncContextManager + # This itself is only available during type checking def type_check_only(func_or_cls: _F) -> _F: ... @@ -171,10 +174,10 @@ Protocol: _SpecialForm = ... Callable: _SpecialForm = ... Type: _SpecialForm = ... NoReturn: _SpecialForm = ... +ClassVar: _SpecialForm = ... Optional: _SpecialForm Tuple: _SpecialForm -ClassVar: _SpecialForm if sys.version_info >= (3, 8): Final: _SpecialForm def final(f: _T) -> _T: ... @@ -494,7 +497,7 @@ class MutableSequence(Sequence[_T], Generic[_T]): def reverse(self) -> None: ... def pop(self, index: int = ...) -> _T: ... def remove(self, value: _T) -> None: ... - def __iadd__(self: TypeshedSelf, values: Iterable[_T]) -> TypeshedSelf: ... + def __iadd__(self: _typeshed.Self, values: Iterable[_T]) -> _typeshed.Self: ... class AbstractSet(Collection[_T_co], Generic[_T_co]): @abstractmethod @@ -520,10 +523,10 @@ class MutableSet(AbstractSet[_T], Generic[_T]): def clear(self) -> None: ... def pop(self) -> _T: ... def remove(self, value: _T) -> None: ... - def __ior__(self: TypeshedSelf, it: AbstractSet[_T]) -> TypeshedSelf: ... # type: ignore[override,misc] - def __iand__(self: TypeshedSelf, it: AbstractSet[Any]) -> TypeshedSelf: ... - def __ixor__(self: TypeshedSelf, it: AbstractSet[_T]) -> TypeshedSelf: ... # type: ignore[override,misc] - def __isub__(self: TypeshedSelf, it: AbstractSet[Any]) -> TypeshedSelf: ... + def __ior__(self: _typeshed.Self, it: AbstractSet[_T]) -> _typeshed.Self: ... # type: ignore[override,misc] + def __iand__(self: _typeshed.Self, it: AbstractSet[Any]) -> _typeshed.Self: ... + def __ixor__(self: _typeshed.Self, it: AbstractSet[_T]) -> _typeshed.Self: ... # type: ignore[override,misc] + def __isub__(self: _typeshed.Self, it: AbstractSet[Any]) -> _typeshed.Self: ... class MappingView(Sized): def __init__(self, mapping: Mapping[Any, Any]) -> None: ... # undocumented @@ -568,22 +571,6 @@ class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]): if sys.version_info >= (3, 8): def __reversed__(self) -> Iterator[_VT_co]: ... -@runtime_checkable -class ContextManager(Protocol[_T_co]): - def __enter__(self) -> _T_co: ... - @abstractmethod - def __exit__( - self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None - ) -> bool | None: ... - -@runtime_checkable -class AsyncContextManager(Protocol[_T_co]): - async def __aenter__(self) -> _T_co: ... - @abstractmethod - async def __aexit__( - self, __exc_type: Type[BaseException] | None, __exc_value: BaseException | None, __traceback: TracebackType | None - ) -> bool | None: ... - class Mapping(Collection[_KT], Generic[_KT, _VT_co]): # TODO: We wish the key type could also be covariant, but that doesn't work, # see discussion in https://github.com/python/typing/pull/273. @@ -718,119 +705,6 @@ class TextIO(IO[str]): class ByteString(Sequence[int], metaclass=ABCMeta): ... -@_final -class Match(Generic[AnyStr]): - @property - def pos(self) -> int: ... - @property - def endpos(self) -> int: ... - @property - def lastindex(self) -> int | None: ... - @property - def lastgroup(self) -> str | None: ... - @property - def string(self) -> AnyStr: ... - - # The regular expression object whose match() or search() method produced - # this match instance. - @property - def re(self) -> Pattern[AnyStr]: ... - @overload - def expand(self: Match[str], template: str) -> str: ... - @overload - def expand(self: Match[bytes], template: ReadableBuffer) -> bytes: ... - # group() returns "AnyStr" or "AnyStr | None", depending on the pattern. - @overload - def group(self, __group: _Literal[0] = ...) -> AnyStr: ... - @overload - def group(self, __group: str | int) -> AnyStr | Any: ... - @overload - def group(self, __group1: str | int, __group2: str | int, *groups: str | int) -> tuple[AnyStr | Any, ...]: ... - # Each item of groups()'s return tuple is either "AnyStr" or - # "AnyStr | None", depending on the pattern. - @overload - def groups(self) -> tuple[AnyStr | Any, ...]: ... - @overload - def groups(self, default: _T) -> tuple[AnyStr | _T, ...]: ... - # Each value in groupdict()'s return dict is either "AnyStr" or - # "AnyStr | None", depending on the pattern. - @overload - def groupdict(self) -> dict[str, AnyStr | Any]: ... - @overload - def groupdict(self, default: _T) -> dict[str, AnyStr | _T]: ... - def start(self, __group: int | str = ...) -> int: ... - def end(self, __group: int | str = ...) -> int: ... - def span(self, __group: int | str = ...) -> tuple[int, int]: ... - @property - def regs(self) -> tuple[tuple[int, int], ...]: ... # undocumented - # __getitem__() returns "AnyStr" or "AnyStr | None", depending on the pattern. - @overload - def __getitem__(self, __key: _Literal[0]) -> AnyStr: ... - @overload - def __getitem__(self, __key: int | str) -> AnyStr | Any: ... - def __copy__(self) -> Match[AnyStr]: ... - def __deepcopy__(self, __memo: Any) -> Match[AnyStr]: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - -@_final -class Pattern(Generic[AnyStr]): - @property - def flags(self) -> int: ... - @property - def groupindex(self) -> Mapping[str, int]: ... - @property - def groups(self) -> int: ... - @property - def pattern(self) -> AnyStr: ... - @overload - def search(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> Match[str] | None: ... - @overload - def search(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> Match[bytes] | None: ... - @overload - def match(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> Match[str] | None: ... - @overload - def match(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> Match[bytes] | None: ... - @overload - def fullmatch(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> Match[str] | None: ... - @overload - def fullmatch(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> Match[bytes] | None: ... - @overload - def split(self: Pattern[str], string: str, maxsplit: int = ...) -> list[str | Any]: ... - @overload - def split(self: Pattern[bytes], string: ReadableBuffer, maxsplit: int = ...) -> list[bytes | Any]: ... - # return type depends on the number of groups in the pattern - @overload - def findall(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> list[Any]: ... - @overload - def findall(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> list[Any]: ... - @overload - def finditer(self: Pattern[str], string: str, pos: int = ..., endpos: int = ...) -> Iterator[Match[str]]: ... - @overload - def finditer(self: Pattern[bytes], string: ReadableBuffer, pos: int = ..., endpos: int = ...) -> Iterator[Match[bytes]]: ... - @overload - def sub(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = ...) -> str: ... - @overload - def sub( - self: Pattern[bytes], - repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], - string: ReadableBuffer, - count: int = ..., - ) -> bytes: ... - @overload - def subn(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = ...) -> tuple[str, int]: ... - @overload - def subn( - self: Pattern[bytes], - repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer], - string: ReadableBuffer, - count: int = ..., - ) -> tuple[bytes, int]: ... - def __copy__(self) -> Pattern[AnyStr]: ... - def __deepcopy__(self, __memo: Any) -> Pattern[AnyStr]: ... - if sys.version_info >= (3, 9): - def __class_getitem__(cls, item: Any) -> GenericAlias: ... - # Functions _get_type_hints_obj_allowed_types = ( # noqa: Y026 # TODO: Use TypeAlias once mypy bugs are fixed @@ -905,11 +779,17 @@ class NamedTuple(tuple[Any, ...]): else: def _asdict(self) -> collections.OrderedDict[str, Any]: ... - def _replace(self: TypeshedSelf, **kwargs: Any) -> TypeshedSelf: ... + def _replace(self: _typeshed.Self, **kwargs: Any) -> _typeshed.Self: ... # Internal mypy fallback type for all typed dicts (does not exist at runtime) +# N.B. Keep this mostly in sync with typing_extensions._TypedDict/mypy_extensions._TypedDict +@type_check_only class _TypedDict(Mapping[str, object], metaclass=ABCMeta): - def copy(self: TypeshedSelf) -> TypeshedSelf: ... + __total__: ClassVar[bool] + if sys.version_info >= (3, 9): + __required_keys__: ClassVar[frozenset[str]] + __optional_keys__: ClassVar[frozenset[str]] + def copy(self: _typeshed.Self) -> _typeshed.Self: ... # Using NoReturn so that only calls using mypy plugin hook that specialize the signature # can go through. def setdefault(self, k: NoReturn, default: object) -> object: ... @@ -920,8 +800,9 @@ class _TypedDict(Mapping[str, object], metaclass=ABCMeta): def items(self) -> ItemsView[str, object]: ... def keys(self) -> KeysView[str]: ... def values(self) -> ValuesView[object]: ... - def __or__(self: TypeshedSelf, __value: TypeshedSelf) -> TypeshedSelf: ... - def __ior__(self: TypeshedSelf, __value: TypeshedSelf) -> TypeshedSelf: ... + if sys.version_info >= (3, 9): + def __or__(self: _typeshed.Self, __value: _typeshed.Self) -> _typeshed.Self: ... + def __ior__(self: _typeshed.Self, __value: _typeshed.Self) -> _typeshed.Self: ... @_final class ForwardRef: @@ -940,7 +821,6 @@ class ForwardRef: def _evaluate(self, globalns: dict[str, Any] | None, localns: dict[str, Any] | None) -> Any | None: ... def __eq__(self, other: object) -> bool: ... - def __hash__(self) -> int: ... if sys.version_info >= (3, 11): def __or__(self, other: Any) -> _SpecialForm: ... def __ror__(self, other: Any) -> _SpecialForm: ... diff --git a/mypy/typeshed/stdlib/typing_extensions.pyi b/mypy/typeshed/stdlib/typing_extensions.pyi index 0d82ec720c25..edc0d228e7a1 100644 --- a/mypy/typeshed/stdlib/typing_extensions.pyi +++ b/mypy/typeshed/stdlib/typing_extensions.pyi @@ -1,7 +1,8 @@ +import _typeshed import abc import collections import sys -from _typeshed import IdentityFunction, Self as TypeshedSelf # see #6932 for why the Self alias cannot have a leading underscore +from _typeshed import IdentityFunction from collections.abc import Iterable from typing import ( # noqa: Y022,Y027,Y039 TYPE_CHECKING as TYPE_CHECKING, @@ -31,6 +32,7 @@ from typing import ( # noqa: Y022,Y027,Y039 ValuesView, _Alias, overload as overload, + type_check_only, ) __all__ = [ @@ -120,11 +122,13 @@ Literal: _SpecialForm def IntVar(name: str) -> Any: ... # returns a new TypeVar # Internal mypy fallback type for all typed dicts (does not exist at runtime) +# N.B. Keep this mostly in sync with typing._TypedDict/mypy_extensions._TypedDict +@type_check_only class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): - __required_keys__: frozenset[str] - __optional_keys__: frozenset[str] - __total__: bool - def copy(self: TypeshedSelf) -> TypeshedSelf: ... + __required_keys__: ClassVar[frozenset[str]] + __optional_keys__: ClassVar[frozenset[str]] + __total__: ClassVar[bool] + def copy(self: _typeshed.Self) -> _typeshed.Self: ... # Using NoReturn so that only calls using mypy plugin hook that specialize the signature # can go through. def setdefault(self, k: NoReturn, default: object) -> object: ... @@ -135,6 +139,9 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): def keys(self) -> KeysView[str]: ... def values(self) -> ValuesView[object]: ... def __delitem__(self, k: NoReturn) -> None: ... + if sys.version_info >= (3, 9): + def __or__(self: _typeshed.Self, __value: _typeshed.Self) -> _typeshed.Self: ... + def __ior__(self: _typeshed.Self, __value: _typeshed.Self) -> _typeshed.Self: ... # TypedDict is a (non-subscriptable) special form. TypedDict: object @@ -256,10 +263,10 @@ else: @overload def __init__(self, typename: str, fields: None = ..., **kwargs: Any) -> None: ... @classmethod - def _make(cls: type[TypeshedSelf], iterable: Iterable[Any]) -> TypeshedSelf: ... + def _make(cls: type[_typeshed.Self], iterable: Iterable[Any]) -> _typeshed.Self: ... if sys.version_info >= (3, 8): def _asdict(self) -> dict[str, Any]: ... else: def _asdict(self) -> collections.OrderedDict[str, Any]: ... - def _replace(self: TypeshedSelf, **kwargs: Any) -> TypeshedSelf: ... + def _replace(self: _typeshed.Self, **kwargs: Any) -> _typeshed.Self: ... diff --git a/mypy/typeshed/stdlib/unittest/__init__.pyi b/mypy/typeshed/stdlib/unittest/__init__.pyi index 673597275b33..33820c793fa5 100644 --- a/mypy/typeshed/stdlib/unittest/__init__.pyi +++ b/mypy/typeshed/stdlib/unittest/__init__.pyi @@ -66,3 +66,4 @@ if sys.version_info >= (3, 11): __all__ += ["enterModuleContext", "doModuleCleanups"] def load_tests(loader: TestLoader, tests: TestSuite, pattern: str | None) -> TestSuite: ... +def __dir__() -> set[str]: ... diff --git a/mypy/typeshed/stdlib/unittest/mock.pyi b/mypy/typeshed/stdlib/unittest/mock.pyi index 4aa67f4995cd..4732994594f8 100644 --- a/mypy/typeshed/stdlib/unittest/mock.pyi +++ b/mypy/typeshed/stdlib/unittest/mock.pyi @@ -121,6 +121,7 @@ class NonCallableMock(Base, Any): def __getattr__(self, name: str) -> Any: ... def __delattr__(self, name: str) -> None: ... def __setattr__(self, name: str, value: Any) -> None: ... + def __dir__(self) -> list[str]: ... if sys.version_info >= (3, 8): def _calls_repr(self, prefix: str = ...) -> str: ... def assert_called_with(self, *args: Any, **kwargs: Any) -> None: ... diff --git a/mypy/typeshed/stdlib/urllib/request.pyi b/mypy/typeshed/stdlib/urllib/request.pyi index 0ad10a218680..88f4f5250e67 100644 --- a/mypy/typeshed/stdlib/urllib/request.pyi +++ b/mypy/typeshed/stdlib/urllib/request.pyi @@ -3,10 +3,10 @@ import sys from _typeshed import StrOrBytesPath, SupportsRead from collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence from email.message import Message -from http.client import HTTPMessage, HTTPResponse, _HTTPConnectionProtocol +from http.client import HTTPConnection, HTTPMessage, HTTPResponse from http.cookiejar import CookieJar from re import Pattern -from typing import IO, Any, ClassVar, NoReturn, TypeVar, overload +from typing import IO, Any, ClassVar, NoReturn, Protocol, TypeVar, overload from typing_extensions import TypeAlias from urllib.error import HTTPError as HTTPError from urllib.response import addclosehook, addinfourl @@ -224,6 +224,16 @@ class ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler): auth_header: ClassVar[str] # undocumented def http_error_407(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ... +class _HTTPConnectionProtocol(Protocol): + def __call__( + self, + host: str, + port: int | None = ..., + timeout: float = ..., + source_address: tuple[str, int] | None = ..., + blocksize: int = ..., + ) -> HTTPConnection: ... + class AbstractHTTPHandler(BaseHandler): # undocumented def __init__(self, debuglevel: int = ...) -> None: ... def set_http_debuglevel(self, level: int) -> None: ... diff --git a/mypy/typeshed/stdlib/xml/dom/minidom.pyi b/mypy/typeshed/stdlib/xml/dom/minidom.pyi index 92da20832fd6..7645bd79e9c1 100644 --- a/mypy/typeshed/stdlib/xml/dom/minidom.pyi +++ b/mypy/typeshed/stdlib/xml/dom/minidom.pyi @@ -2,6 +2,7 @@ import sys import xml.dom from _typeshed import Self, SupportsRead from typing import Any +from typing_extensions import Literal from xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS from xml.sax.xmlreader import XMLReader @@ -22,7 +23,7 @@ class Node(xml.dom.Node): def lastChild(self) -> Node | None: ... @property def localName(self) -> str | None: ... - def __bool__(self) -> bool: ... + def __bool__(self) -> Literal[True]: ... if sys.version_info >= (3, 9): def toxml(self, encoding: Any | None = ..., standalone: Any | None = ...): ... def toprettyxml(self, indent: str = ..., newl: str = ..., encoding: Any | None = ..., standalone: Any | None = ...): ... diff --git a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi index 0e898cb29740..1a0760862733 100644 --- a/mypy/typeshed/stdlib/zoneinfo/__init__.pyi +++ b/mypy/typeshed/stdlib/zoneinfo/__init__.pyi @@ -30,3 +30,5 @@ TZPATH: Sequence[str] class ZoneInfoNotFoundError(KeyError): ... class InvalidTZPathWarning(RuntimeWarning): ... + +def __dir__() -> list[str]: ... diff --git a/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi b/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi index 85c828e8a8a8..edefcc318176 100644 --- a/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi +++ b/mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi @@ -1,13 +1,19 @@ import abc +import sys from _typeshed import IdentityFunction, Self from collections.abc import ItemsView, KeysView, Mapping, ValuesView -from typing import Any, Generic, TypeVar, overload +from typing import Any, ClassVar, Generic, TypeVar, overload, type_check_only _T = TypeVar("_T") _U = TypeVar("_U") # Internal mypy fallback type for all typed dicts (does not exist at runtime) +# N.B. Keep this mostly in sync with typing(_extensions)._TypedDict +@type_check_only class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): + __total__: ClassVar[bool] + # Unlike typing(_extensions).TypedDict, + # subclasses of mypy_extensions.TypedDict do NOT have the __required_keys__ and __optional_keys__ ClassVars def copy(self: Self) -> Self: ... # Using NoReturn so that only calls using mypy plugin hook that specialize the signature # can go through. @@ -19,6 +25,9 @@ class _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta): def keys(self) -> KeysView[str]: ... def values(self) -> ValuesView[object]: ... def __delitem__(self, k: NoReturn) -> None: ... + if sys.version_info >= (3, 9): + def __or__(self: Self, __other: Self) -> Self: ... + def __ior__(self: Self, __other: Self) -> Self: ... def TypedDict(typename: str, fields: dict[str, type[Any]], total: bool = ...) -> type[dict[str, Any]]: ... @overload From 6bc2771e54c861a98f0ffa86a74355152029b38f Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Fri, 8 Jul 2022 14:15:39 +0100 Subject: [PATCH 2/3] Remove use of LiteralString in builtins (#13093) Fixes #13091 Co-authored-by: Ivan Levkivskyi --- mypy/typeshed/stdlib/builtins.pyi | 155 ++++++------------------------ 1 file changed, 32 insertions(+), 123 deletions(-) diff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi index 1bcd4746c7a3..6992dc8e2674 100644 --- a/mypy/typeshed/stdlib/builtins.pyi +++ b/mypy/typeshed/stdlib/builtins.pyi @@ -55,7 +55,7 @@ from typing import ( # noqa: Y027 overload, type_check_only, ) -from typing_extensions import Literal, LiteralString, SupportsIndex, TypeAlias, TypeGuard, final +from typing_extensions import Literal, SupportsIndex, TypeAlias, TypeGuard, final if sys.version_info >= (3, 9): from types import GenericAlias @@ -413,39 +413,21 @@ 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: ... - @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 capitalize(self) -> str: ... + def casefold(self) -> str: ... + def center(self, __width: SupportsIndex, __fillchar: str = ...) -> str: ... def count(self, x: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def encode(self, encoding: str = ..., errors: str = ...) -> bytes: ... def endswith( self, __suffix: str | tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> bool: ... if sys.version_info >= (3, 8): - @overload - def expandtabs(self: LiteralString, tabsize: SupportsIndex = ...) -> LiteralString: ... - @overload - def expandtabs(self, tabsize: SupportsIndex = ...) -> str: ... # type: ignore[misc] + def expandtabs(self, tabsize: SupportsIndex = ...) -> str: ... else: - @overload - def expandtabs(self: LiteralString, tabsize: int = ...) -> LiteralString: ... - @overload - def expandtabs(self, tabsize: int = ...) -> str: ... # type: ignore[misc] + def expandtabs(self, tabsize: int = ...) -> str: ... def find(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... - @overload - def format(self: LiteralString, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ... - @overload - def format(self, *args: object, **kwargs: object) -> str: ... # type: ignore[misc] + def format(self, *args: object, **kwargs: object) -> str: ... def format_map(self, map: _FormatMapMapping) -> str: ... def index(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def isalnum(self) -> bool: ... @@ -460,128 +442,55 @@ class str(Sequence[str]): def isspace(self) -> bool: ... def istitle(self) -> bool: ... def isupper(self) -> bool: ... - @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] + 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: ... if sys.version_info >= (3, 9): - @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 removeprefix(self, __prefix: str) -> str: ... + def removesuffix(self, __suffix: str) -> str: ... def rfind(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... def rindex(self, __sub: str, __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ...) -> int: ... - @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 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]: ... def startswith( self, __prefix: str | tuple[str, ...], __start: SupportsIndex | None = ..., __end: SupportsIndex | None = ... ) -> bool: ... - @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 strip(self, __chars: str | None = ...) -> str: ... + def swapcase(self) -> str: ... + def title(self) -> str: ... def translate(self, __table: Mapping[int, int | str | None] | Sequence[int | str | None]) -> 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] + def upper(self) -> str: ... + def zfill(self, __width: SupportsIndex) -> str: ... @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]: ... - @overload - def __add__(self: LiteralString, __s: LiteralString) -> LiteralString: ... - @overload - def __add__(self, __s: str) -> str: ... # type: ignore[misc] + def __add__(self, __s: str) -> str: ... # Incompatible with Sequence.__contains__ def __contains__(self, __o: str) -> bool: ... # type: ignore[override] def __eq__(self, __x: object) -> bool: ... def __ge__(self, __x: str) -> bool: ... def __getitem__(self, __i: SupportsIndex | slice) -> str: ... def __gt__(self, __x: str) -> bool: ... - @overload - def __iter__(self: LiteralString) -> Iterator[LiteralString]: ... - @overload - def __iter__(self) -> Iterator[str]: ... # type: ignore[misc] + def __hash__(self) -> int: ... + def __iter__(self) -> Iterator[str]: ... def __le__(self, __x: str) -> bool: ... def __len__(self) -> int: ... def __lt__(self, __x: str) -> bool: ... - @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 __mod__(self, __x: Any) -> str: ... + def __mul__(self, __n: SupportsIndex) -> str: ... def __ne__(self, __x: object) -> bool: ... - @overload - def __rmul__(self: LiteralString, __n: SupportsIndex) -> LiteralString: ... - @overload - def __rmul__(self, __n: SupportsIndex) -> str: ... # type: ignore[misc] + def __rmul__(self, __n: SupportsIndex) -> str: ... def __getnewargs__(self) -> tuple[str]: ... class bytes(ByteString): From 2ec37f59f0f2c3663b86d416285671be343275a2 Mon Sep 17 00:00:00 2001 From: Alex Waygood Date: Fri, 19 Aug 2022 04:54:08 +0200 Subject: [PATCH 3/3] Fix `teststubtest` (#13447) --- mypy/test/teststubtest.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mypy/test/teststubtest.py b/mypy/test/teststubtest.py index b82e77386c7a..1db2645e3a86 100644 --- a/mypy/test/teststubtest.py +++ b/mypy/test/teststubtest.py @@ -52,6 +52,7 @@ def __init__(self, name, covariant: bool = ..., contravariant: bool = ...) -> No class ParamSpec: def __init__(self, name: str) -> None: ... +AnyStr = TypeVar("AnyStr", str, bytes) _T = TypeVar("_T") _T_co = TypeVar("_T_co", covariant=True) _K = TypeVar("_K") @@ -62,7 +63,7 @@ def __init__(self, name: str) -> None: ... class Coroutine(Generic[_T_co, _S, _R]): ... class Iterable(Generic[_T_co]): ... class Mapping(Generic[_K, _V]): ... -class Match(Generic[_T]): ... +class Match(Generic[AnyStr]): ... class Sequence(Iterable[_T_co]): ... class Tuple(Sequence[_T_co]): ... def overload(func: _T) -> _T: ...