diff --git a/python/helpers/typeshed/CONTRIBUTING.md b/python/helpers/typeshed/CONTRIBUTING.md index d7fba6c402ad..232b830135ab 100644 --- a/python/helpers/typeshed/CONTRIBUTING.md +++ b/python/helpers/typeshed/CONTRIBUTING.md @@ -320,6 +320,25 @@ documentation. Whenever you find them disagreeing, model the type information after the actual implementation and file an issue on the project's tracker to fix their documentation. +### Deprecations (using the `@deprecated` decorator) + +Generally deprecactions using the `@deprecated` decorator are added more +liberally in typeshed than runtime deprecation warnings. Here are some +guidelines that can be deviated from in special cases. + +Use `@deprecated` if and only if + +- a feature is deprecated at runtime (either using `@deprecated` or with a + runtime warning); or +- a feature is documented to be deprecated (e.g. in API documention, + docstrings, or comments). + +For standard library features that are not deprecated in all Python versions +currently supported by typeshed use `@deprecated` for + +- all versions starting with the "Deprecated since" version, plus +- all versions for which an alternative is available. + ### Docstrings Typeshed stubs should not include duplicated docstrings from the source code. diff --git a/python/helpers/typeshed/pyrightconfig.stricter.json b/python/helpers/typeshed/pyrightconfig.stricter.json index 8f32cb3e46fa..5cd12e0013b6 100644 --- a/python/helpers/typeshed/pyrightconfig.stricter.json +++ b/python/helpers/typeshed/pyrightconfig.stricter.json @@ -73,13 +73,17 @@ "stubs/parsimonious/parsimonious/nodes.pyi", "stubs/peewee", "stubs/pexpect", - "stubs/pika", + "stubs/pika/pika/adapters/twisted_connection.pyi", + "stubs/pika/pika/adapters/utils/connection_workflow.pyi", + "stubs/pika/pika/callback.pyi", + "stubs/pika/pika/channel.pyi", "stubs/pony", "stubs/protobuf", "stubs/psutil/psutil/__init__.pyi", "stubs/psycopg2", "stubs/punq", "stubs/pyasn1", + "stubs/pycups", "stubs/Pygments", "stubs/PyMySQL", "stubs/pyogrio", diff --git a/python/helpers/typeshed/stdlib/@tests/test_cases/builtins/check_pow.py b/python/helpers/typeshed/stdlib/@tests/test_cases/builtins/check_pow.py index 6ad6116cf578..01de2eb5fc8b 100644 --- a/python/helpers/typeshed/stdlib/@tests/test_cases/builtins/check_pow.py +++ b/python/helpers/typeshed/stdlib/@tests/test_cases/builtins/check_pow.py @@ -15,7 +15,7 @@ assert_type(pow(1, 0, None), Literal[1]) # that passing 0 for the third argument will lead to an exception being raised # (see discussion in #8566) # -# assert_type(pow(2, 4, 0), NoReturn) +# assert_type(pow(2, 4, 0), Never) assert_type(pow(2, 4), int) # pyright infers a literal type here, but mypy does not. diff --git a/python/helpers/typeshed/stdlib/@tests/test_cases/builtins/check_reversed.py b/python/helpers/typeshed/stdlib/@tests/test_cases/builtins/check_reversed.py index 2a43a57deb4e..d89ebf3a0ca7 100644 --- a/python/helpers/typeshed/stdlib/@tests/test_cases/builtins/check_reversed.py +++ b/python/helpers/typeshed/stdlib/@tests/test_cases/builtins/check_reversed.py @@ -31,4 +31,18 @@ class MyLenAndGetItem(Generic[_T]): len_and_get_item: MyLenAndGetItem[int] = MyLenAndGetItem() -assert_type(list(reversed(len_and_get_item)), "list[int]") +assert_type(reversed(len_and_get_item), "reversed[int]") + + +class UnTrue: + def __reversed__(self) -> UnFalse: + return UnFalse() + + +class UnFalse: + def __reversed__(self) -> UnTrue: + return UnTrue() + + +assert_type(reversed(UnTrue()), "UnFalse") +assert_type(reversed(reversed(UnTrue())), "UnTrue") diff --git a/python/helpers/typeshed/stdlib/__main__.pyi b/python/helpers/typeshed/stdlib/__main__.pyi index 5b0f74feb261..3536a6f021c5 100644 --- a/python/helpers/typeshed/stdlib/__main__.pyi +++ b/python/helpers/typeshed/stdlib/__main__.pyi @@ -1 +1 @@ -def __getattr__(name: str): ... # incomplete module +def __getattr__(name: str, /): ... # incomplete module diff --git a/python/helpers/typeshed/stdlib/_ctypes.pyi b/python/helpers/typeshed/stdlib/_ctypes.pyi index d800ac5c20d0..36365cea3aa8 100644 --- a/python/helpers/typeshed/stdlib/_ctypes.pyi +++ b/python/helpers/typeshed/stdlib/_ctypes.pyi @@ -249,7 +249,7 @@ class _UnionType(_CTypeBaseType): # At runtime, various attributes are created on a Union subclass based # on its _fields_. This method doesn't exist, but represents those # dynamically created attributes. - def __getattr__(self, name: str) -> _CField[Any, Any, Any]: ... + def __getattr__(self, name: str, /) -> _CField[Any, Any, Any]: ... if sys.version_info < (3, 13): # Inherited from CType_Type starting on 3.13 def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] @@ -263,8 +263,8 @@ class Union(_CData, metaclass=_UnionType): _align_: ClassVar[int] def __init__(self, *args: Any, **kw: Any) -> None: ... - def __getattr__(self, name: str) -> Any: ... - def __setattr__(self, name: str, value: Any) -> None: ... + def __getattr__(self, name: str, /) -> Any: ... + def __setattr__(self, name: str, value: Any, /) -> None: ... # This class is not exposed. It calls itself _ctypes.PyCStructType. @type_check_only @@ -277,7 +277,7 @@ class _PyCStructType(_CTypeBaseType): # At runtime, various attributes are created on a Structure subclass based # on its _fields_. This method doesn't exist, but represents those # dynamically created attributes. - def __getattr__(self, name: str) -> _CField[Any, Any, Any]: ... + def __getattr__(self, name: str, /) -> _CField[Any, Any, Any]: ... if sys.version_info < (3, 13): # Inherited from CType_Type starting on 3.13 def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ... # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] @@ -295,7 +295,7 @@ class Structure(_CData, metaclass=_PyCStructType): _layout_: ClassVar[Literal["ms", "gcc-sysv"]] def __init__(self, *args: Any, **kw: Any) -> None: ... - def __getattr__(self, name: str) -> Any: ... + def __getattr__(self, name: str, /) -> Any: ... def __setattr__(self, name: str, value: Any) -> None: ... # This class is not exposed. It calls itself _ctypes.PyCArrayType. diff --git a/python/helpers/typeshed/stdlib/_sitebuiltins.pyi b/python/helpers/typeshed/stdlib/_sitebuiltins.pyi index eb6c81129421..99abd02386b2 100644 --- a/python/helpers/typeshed/stdlib/_sitebuiltins.pyi +++ b/python/helpers/typeshed/stdlib/_sitebuiltins.pyi @@ -1,12 +1,13 @@ import sys from collections.abc import Iterable -from typing import ClassVar, Literal, NoReturn +from typing import ClassVar, Literal +from typing_extensions import Never class Quitter: name: str eof: str def __init__(self, name: str, eof: str) -> None: ... - def __call__(self, code: sys._ExitCode = None) -> NoReturn: ... + def __call__(self, code: sys._ExitCode = None) -> Never: ... class _Printer: MAXLINES: ClassVar[Literal[23]] diff --git a/python/helpers/typeshed/stdlib/_thread.pyi b/python/helpers/typeshed/stdlib/_thread.pyi index e2d257c9ec0b..57622e936a3b 100644 --- a/python/helpers/typeshed/stdlib/_thread.pyi +++ b/python/helpers/typeshed/stdlib/_thread.pyi @@ -4,8 +4,8 @@ from _typeshed import structseq from collections.abc import Callable from threading import Thread from types import TracebackType -from typing import Any, Final, NoReturn, final, overload -from typing_extensions import TypeVarTuple, Unpack, deprecated, disjoint_base +from typing import Any, Final, final, overload +from typing_extensions import Never, TypeVarTuple, Unpack, deprecated, disjoint_base _Ts = TypeVarTuple("_Ts") @@ -82,9 +82,9 @@ def start_new(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts] def start_new(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ... # undocumented def interrupt_main(signum: signal.Signals = signal.SIGINT, /) -> None: ... -def exit() -> NoReturn: ... +def exit() -> Never: ... @deprecated("Obsolete synonym. Use `exit()` instead.") -def exit_thread() -> NoReturn: ... # undocumented +def exit_thread() -> Never: ... # undocumented def allocate_lock() -> LockType: ... @deprecated("Obsolete synonym. Use `allocate_lock()` instead.") def allocate() -> LockType: ... # undocumented diff --git a/python/helpers/typeshed/stdlib/_typeshed/__init__.pyi b/python/helpers/typeshed/stdlib/_typeshed/__init__.pyi index 2f65d8aab9c5..5b2d7f7c549f 100644 --- a/python/helpers/typeshed/stdlib/_typeshed/__init__.pyi +++ b/python/helpers/typeshed/stdlib/_typeshed/__init__.pyi @@ -58,6 +58,14 @@ Unused: TypeAlias = object # stable # for more information. MaybeNone: TypeAlias = Any # stable +# typeshed-internal type aliases to facilitate transition from +# `float` to either `float | int` or `float` (and similar for `complex`). +# When you encounter one of these type aliases, you are encouraged to +# replace them with the correct type. Please don't use them outside typeshed. +# See https://github.com/python/typeshed/issues/16059 for details. +FloatInt: TypeAlias = float | int +ComplexInt: TypeAlias = complex | float | int + # Used to mark arguments that default to a sentinel value. This prevents # stubtest from complaining about the default value not matching. # diff --git a/python/helpers/typeshed/stdlib/_winapi.pyi b/python/helpers/typeshed/stdlib/_winapi.pyi index 7fd918d9b1e9..a9ad4f19a62e 100644 --- a/python/helpers/typeshed/stdlib/_winapi.pyi +++ b/python/helpers/typeshed/stdlib/_winapi.pyi @@ -1,7 +1,8 @@ import sys from _typeshed import ReadableBuffer from collections.abc import Sequence -from typing import Any, Final, Literal, NoReturn, final, overload +from typing import Any, Final, Literal, final, overload +from typing_extensions import Never if sys.platform == "win32": ABOVE_NORMAL_PRIORITY_CLASS: Final = 0x8000 @@ -238,7 +239,7 @@ if sys.platform == "win32": options: int = 0, /, ) -> int: ... - def ExitProcess(ExitCode: int, /) -> NoReturn: ... + def ExitProcess(ExitCode: int, /) -> Never: ... def GetACP() -> int: ... if sys.version_info >= (3, 15): def DeregisterEventSource(handle: int, /) -> None: ... @@ -312,3 +313,6 @@ if sys.platform == "win32": if sys.version_info >= (3, 12): def CopyFile2(existing_file_name: str, new_file_name: str, flags: int, progress_routine: int | None = None) -> int: ... def NeedCurrentDirectoryForExePath(exe_name: str, /) -> bool: ... + + if sys.version_info >= (3, 15): + def GetTickCount64() -> int: ... diff --git a/python/helpers/typeshed/stdlib/argparse.pyi b/python/helpers/typeshed/stdlib/argparse.pyi index 22d330a089ef..36ea1981af3f 100644 --- a/python/helpers/typeshed/stdlib/argparse.pyi +++ b/python/helpers/typeshed/stdlib/argparse.pyi @@ -2,8 +2,8 @@ import sys from _typeshed import SupportsWrite, sentinel from collections.abc import Callable, Generator, Iterable, Sequence from re import Pattern -from typing import IO, Any, ClassVar, Final, Generic, NoReturn, Protocol, TypeAlias, TypeVar, overload, type_check_only -from typing_extensions import Self, deprecated +from typing import IO, Any, ClassVar, Final, Generic, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, Self, deprecated __all__ = [ "ArgumentParser", @@ -103,7 +103,7 @@ class _ActionsContainer: conflict_handler: str = ..., ) -> _ArgumentGroup: ... @overload - @deprecated("The `prefix_chars` parameter deprecated since Python 3.14.") + @deprecated("The `prefix_chars` parameter is deprecated.") def add_argument_group( self, title: str | None = None, @@ -123,7 +123,7 @@ class _ActionsContainer: def _pop_action_class(self, kwargs: Any, default: type[Action] | None = None) -> type[Action]: ... def _get_handler(self) -> Callable[[Action, Iterable[tuple[str, Action]]], Any]: ... def _check_conflict(self, action: Action) -> None: ... - def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> NoReturn: ... + def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> Never: ... def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> None: ... @type_check_only @@ -264,8 +264,8 @@ class ArgumentParser(_AttributeHolder, _ActionsContainer): def parse_known_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ... def convert_arg_line_to_args(self, arg_line: str) -> list[str]: ... - def exit(self, status: int = 0, message: str | None = None) -> NoReturn: ... - def error(self, message: str) -> NoReturn: ... + def exit(self, status: int = 0, message: str | None = None) -> Never: ... + def error(self, message: str) -> Never: ... @overload def parse_intermixed_args(self, args: Iterable[str] | None = None, namespace: None = None) -> Namespace: ... @@ -530,7 +530,7 @@ class Namespace(_AttributeHolder): def __eq__(self, other: object) -> bool: ... __hash__: ClassVar[None] # type: ignore[assignment] -@deprecated("Deprecated since Python 3.14. Open files after parsing arguments instead.") +@deprecated("Deprecated; may leave files open. Open files after parsing arguments instead.") class FileType: # undocumented _mode: str @@ -556,7 +556,7 @@ class _ArgumentGroup(_ActionsContainer): conflict_handler: str = ..., ) -> None: ... @overload - @deprecated("Undocumented `prefix_chars` parameter is deprecated since Python 3.14.") + @deprecated("Undocumented `prefix_chars` parameter is deprecated.") def __init__( self, container: _ActionsContainer, diff --git a/python/helpers/typeshed/stdlib/asyncio/coroutines.pyi b/python/helpers/typeshed/stdlib/asyncio/coroutines.pyi index 7599c692949b..8fafa2e75716 100644 --- a/python/helpers/typeshed/stdlib/asyncio/coroutines.pyi +++ b/python/helpers/typeshed/stdlib/asyncio/coroutines.pyi @@ -21,16 +21,16 @@ def iscoroutine(obj: object) -> TypeIs[Coroutine[Any, Any, Any]]: ... if sys.version_info >= (3, 11): @overload - @deprecated("Deprecated since Python 3.14. Use `inspect.iscoroutinefunction()` instead.") + @deprecated("Deprecated; will be removed in Python 3.16. Use `inspect.iscoroutinefunction()` instead.") def iscoroutinefunction(func: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ... @overload - @deprecated("Deprecated since Python 3.14. Use `inspect.iscoroutinefunction()` instead.") + @deprecated("Deprecated; will be removed in Python 3.16. Use `inspect.iscoroutinefunction()` instead.") def iscoroutinefunction(func: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, _T]]]: ... @overload - @deprecated("Deprecated since Python 3.14. Use `inspect.iscoroutinefunction()` instead.") + @deprecated("Deprecated; will be removed in Python 3.16. Use `inspect.iscoroutinefunction()` instead.") def iscoroutinefunction(func: Callable[_P, object]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, Any]]]: ... @overload - @deprecated("Deprecated since Python 3.14. Use `inspect.iscoroutinefunction()` instead.") + @deprecated("Deprecated; will be removed in Python 3.16. Use `inspect.iscoroutinefunction()` instead.") def iscoroutinefunction(func: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ... else: # Sometimes needed in Python < 3.11 due to the fact that it supports @coroutine diff --git a/python/helpers/typeshed/stdlib/asyncio/events.pyi b/python/helpers/typeshed/stdlib/asyncio/events.pyi index 89da5dece907..db826ff1c2e5 100644 --- a/python/helpers/typeshed/stdlib/asyncio/events.pyi +++ b/python/helpers/typeshed/stdlib/asyncio/events.pyi @@ -633,10 +633,10 @@ else: def new_event_loop(self) -> AbstractEventLoop: ... # Child processes handling (Unix only). @abstractmethod - @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + @deprecated("Deprecated; removed in Python 3.14.") def get_child_watcher(self) -> AbstractChildWatcher: ... @abstractmethod - @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + @deprecated("Deprecated; removed in Python 3.14.") def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ... AbstractEventLoopPolicy = _AbstractEventLoopPolicy @@ -657,15 +657,15 @@ if sys.version_info >= (3, 14): def _get_event_loop_policy() -> _AbstractEventLoopPolicy: ... def _set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ... -@deprecated("Deprecated since Python 3.14; will be removed in Python 3.16.") +@deprecated("Deprecated; will be removed in Python 3.16.") def get_event_loop_policy() -> _AbstractEventLoopPolicy: ... -@deprecated("Deprecated since Python 3.14; will be removed in Python 3.16.") +@deprecated("Deprecated; will be removed in Python 3.16.") def set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ... def set_event_loop(loop: AbstractEventLoop | None) -> None: ... def new_event_loop() -> AbstractEventLoop: ... if sys.version_info < (3, 14): - @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + @deprecated("Deprecated; removed in Python 3.14.") def get_child_watcher() -> AbstractChildWatcher: ... - @deprecated("Deprecated since Python 3.12; removed in Python 3.14.") + @deprecated("Deprecated; removed in Python 3.14.") def set_child_watcher(watcher: AbstractChildWatcher) -> None: ... diff --git a/python/helpers/typeshed/stdlib/asyncio/trsock.pyi b/python/helpers/typeshed/stdlib/asyncio/trsock.pyi index f621240d668a..d2e972fee49c 100644 --- a/python/helpers/typeshed/stdlib/asyncio/trsock.pyi +++ b/python/helpers/typeshed/stdlib/asyncio/trsock.pyi @@ -4,8 +4,8 @@ from _typeshed import ReadableBuffer from builtins import type as Type # alias to avoid name clashes with property named "type" from collections.abc import Iterable from types import TracebackType -from typing import Any, BinaryIO, NoReturn, TypeAlias, overload -from typing_extensions import deprecated +from typing import Any, BinaryIO, TypeAlias, overload +from typing_extensions import Never, deprecated # These are based in socket, maybe move them out into _typeshed.pyi or such _Address: TypeAlias = socket._Address @@ -22,7 +22,7 @@ class TransportSocket: def type(self) -> int: ... @property def proto(self) -> int: ... - def __getstate__(self) -> NoReturn: ... + def __getstate__(self) -> Never: ... def fileno(self) -> int: ... def dup(self) -> socket.socket: ... def get_inheritable(self) -> bool: ... @@ -40,7 +40,7 @@ class TransportSocket: def getpeername(self) -> _RetAddress: ... def getsockname(self) -> _RetAddress: ... - def getsockbyname(self) -> NoReturn: ... # This method doesn't exist on socket, yet is passed through? + def getsockbyname(self) -> Never: ... # This method doesn't exist on socket, yet is passed through? def settimeout(self, value: float | None) -> None: ... def gettimeout(self) -> float | None: ... def setblocking(self, flag: bool) -> None: ... @@ -60,7 +60,7 @@ class TransportSocket: def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> None: ... else: @deprecated("Removed in Python 3.11") - def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> NoReturn: ... + def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> Never: ... @deprecated("Removed in Python 3.11") def listen(self, backlog: int = ..., /) -> None: ... @@ -82,7 +82,7 @@ class TransportSocket: @deprecated("Removed in Python 3.11.") def sendmsg_afalg( self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = 0 - ) -> NoReturn: ... + ) -> Never: ... @deprecated("Removed in Python 3.11.") def sendmsg( @@ -113,7 +113,7 @@ class TransportSocket: def share(self, process_id: int) -> bytes: ... else: @deprecated("Removed in Python 3.11.") - def share(self, process_id: int) -> NoReturn: ... + def share(self, process_id: int) -> Never: ... @deprecated("Removed in Python 3.11.") def recv_into(self, buffer: _WriteBuffer, nbytes: int = 0, flags: int = 0) -> int: ... diff --git a/python/helpers/typeshed/stdlib/asyncio/windows_events.pyi b/python/helpers/typeshed/stdlib/asyncio/windows_events.pyi index a32381bfb3e6..a2428e425f2f 100644 --- a/python/helpers/typeshed/stdlib/asyncio/windows_events.pyi +++ b/python/helpers/typeshed/stdlib/asyncio/windows_events.pyi @@ -2,7 +2,8 @@ import socket import sys from _typeshed import Incomplete, ReadableBuffer, WriteableBuffer from collections.abc import Callable -from typing import IO, Any, ClassVar, Final, NoReturn +from typing import IO, Any, ClassVar, Final +from typing_extensions import Never from . import events, futures, proactor_events, selector_events, streams, windows_utils @@ -105,13 +106,13 @@ if sys.platform == "win32": else: class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): _loop_factory: ClassVar[type[SelectorEventLoop]] - def get_child_watcher(self) -> NoReturn: ... - def set_child_watcher(self, watcher: Any) -> NoReturn: ... + def get_child_watcher(self) -> Never: ... + def set_child_watcher(self, watcher: Any) -> Never: ... class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy): _loop_factory: ClassVar[type[ProactorEventLoop]] - def get_child_watcher(self) -> NoReturn: ... - def set_child_watcher(self, watcher: Any) -> NoReturn: ... + def get_child_watcher(self) -> Never: ... + def set_child_watcher(self, watcher: Any) -> Never: ... if sys.version_info >= (3, 14): _DefaultEventLoopPolicy = _WindowsProactorEventLoopPolicy diff --git a/python/helpers/typeshed/stdlib/builtins.pyi b/python/helpers/typeshed/stdlib/builtins.pyi index 096d440ac38c..3c549d97316c 100644 --- a/python/helpers/typeshed/stdlib/builtins.pyi +++ b/python/helpers/typeshed/stdlib/builtins.pyi @@ -30,7 +30,7 @@ from _typeshed import ( SupportsRichComparisonT, SupportsWrite, ) -from collections.abc import Awaitable, Callable, Iterable, Iterator, MutableSet, Reversible, Set as AbstractSet, Sized +from collections.abc import Awaitable, Callable, Iterable, Iterator, MutableSet, Set as AbstractSet, Sized from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper from os import PathLike from types import CellType, CodeType, EllipsisType, GenericAlias, NotImplementedType, TracebackType, UnionType @@ -281,6 +281,7 @@ class int: *, signed: bool = False, ) -> Self: ... + else: def to_bytes(self, length: SupportsIndex, byteorder: Literal["little", "big"], *, signed: bool = False) -> bytes: ... @classmethod @@ -344,6 +345,7 @@ class int: def __floor__(self) -> int: ... if sys.version_info >= (3, 14): def __round__(self, ndigits: SupportsIndex | None = None, /) -> int: ... + else: def __round__(self, ndigits: SupportsIndex = ..., /) -> int: ... @@ -770,6 +772,7 @@ class bytes(Sequence[int]): def partition(self, sep: ReadableBuffer, /) -> tuple[bytes, bytes, bytes]: ... if sys.version_info >= (3, 15): def replace(self, old: ReadableBuffer, new: ReadableBuffer, /, count: SupportsIndex = -1) -> bytes: ... + else: def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytes: ... @@ -890,6 +893,7 @@ class bytearray(MutableSequence[int]): def removesuffix(self, suffix: ReadableBuffer, /) -> bytearray: ... if sys.version_info >= (3, 15): def replace(self, old: ReadableBuffer, new: ReadableBuffer, /, count: SupportsIndex = -1) -> bytearray: ... + else: def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytearray: ... @@ -1042,6 +1046,7 @@ class memoryview(Sequence[_I]): if sys.version_info >= (3, 14): def index(self, value: object, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ... def count(self, value: object, /) -> int: ... + else: # These are inherited from the Sequence ABC, but don't actually exist on memoryview. # See https://github.com/python/cpython/issues/125420 @@ -1128,6 +1133,7 @@ class slice(Generic[_StartT_co, _StopT_co, _StepT_co]): def __eq__(self, value: object, /) -> bool: ... if sys.version_info >= (3, 12): def __hash__(self) -> int: ... + else: __hash__: ClassVar[None] # type: ignore[assignment] @@ -1202,6 +1208,7 @@ class function: closure: tuple[CellType, ...] | None = None, kwdefaults: dict[str, object] | None = None, ) -> Self: ... + else: def __new__( cls, @@ -1359,6 +1366,7 @@ class dict(MutableMapping[_KT, _VT]): def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... @overload def __ror__(self, value: frozendict[_T1, _T2], /) -> frozendict[_KT | _T1, _VT | _T2]: ... + else: def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ... @@ -2104,7 +2112,7 @@ _SupportsSomeKindOfPow = ( # noqa: Y026 # TODO: Use TypeAlias once mypy bugs a ) # TODO: `pow(int, int, Literal[0])` fails at runtime, -# but adding a `NoReturn` overload isn't a good solution for expressing that (see #8566). +# but adding a `Never` overload isn't a good solution for expressing that (see #8566). @overload def pow(base: int, exp: int, mod: int) -> int: ... @overload @@ -2145,15 +2153,19 @@ def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex quit: _sitebuiltins.Quitter +@type_check_only +class _SupportsReversed(Protocol[_T_co]): + def __reversed__(self) -> _T_co: ... + @disjoint_base -class reversed(Generic[_T]): +class reversed(Generic[_T_co]): @overload - def __new__(cls, sequence: Reversible[_T], /) -> Iterator[_T]: ... # type: ignore[misc] + def __new__(cls, sequence: _SupportsReversed[_T], /) -> _T: ... # type: ignore[misc] @overload - def __new__(cls, sequence: SupportsLenAndGetItem[_T], /) -> Iterator[_T]: ... # type: ignore[misc] + def __new__(cls, sequence: SupportsLenAndGetItem[_T_co], /) -> Self: ... def __iter__(self) -> Self: ... - def __next__(self) -> _T: ... + def __next__(self) -> _T_co: ... def __length_hint__(self) -> int: ... def repr(obj: object, /) -> str: ... @@ -2306,7 +2318,7 @@ class BaseException: __suppress_context__: bool __traceback__: TracebackType | None def __init__(self, *args: object) -> None: ... - def __new__(cls, *args: Any, **kwds: Any) -> Self: ... + def __new__(cls, /, *args: Any, **kwds: Any) -> Self: ... def __setstate__(self, state: dict[str, Any] | None, /) -> None: ... def with_traceback(self, tb: TracebackType | None, /) -> Self: ... # Necessary for security-focused static analyzers (e.g, pysa) diff --git a/python/helpers/typeshed/stdlib/codecs.pyi b/python/helpers/typeshed/stdlib/codecs.pyi index b341d0f813c4..ee1ab25bac47 100644 --- a/python/helpers/typeshed/stdlib/codecs.pyi +++ b/python/helpers/typeshed/stdlib/codecs.pyi @@ -193,7 +193,7 @@ def getincrementaldecoder(encoding: str) -> _IncrementalDecoder: ... def getreader(encoding: str) -> _StreamReader: ... def getwriter(encoding: str) -> _StreamWriter: ... -@deprecated("Deprecated since Python 3.14. Use `open()` instead.") +@deprecated("Deprecated. Use `open()` instead.") def open( filename: str, mode: str = "r", encoding: str | None = None, errors: str = "strict", buffering: int = -1 ) -> StreamReaderWriter: ... diff --git a/python/helpers/typeshed/stdlib/collections/__init__.pyi b/python/helpers/typeshed/stdlib/collections/__init__.pyi index 39b8a3c9ab6a..bea145e424dd 100644 --- a/python/helpers/typeshed/stdlib/collections/__init__.pyi +++ b/python/helpers/typeshed/stdlib/collections/__init__.pyi @@ -14,8 +14,8 @@ from collections.abc import ( ValuesView, ) from types import GenericAlias -from typing import Any, ClassVar, Generic, NoReturn, SupportsIndex, TypeVar, final, overload, type_check_only -from typing_extensions import Self, disjoint_base +from typing import Any, ClassVar, Generic, SupportsIndex, TypeVar, final, overload, type_check_only +from typing_extensions import Never, Self, disjoint_base if sys.version_info >= (3, 15): from builtins import frozendict @@ -277,6 +277,7 @@ class deque(MutableSequence[_T]): def __iadd__(self, value: Iterable[_T], /) -> Self: ... def __add__(self, value: Self, /) -> Self: ... def __mul__(self, value: int, /) -> Self: ... + def __rmul__(self, value: int, /) -> Self: ... def __imul__(self, value: int, /) -> Self: ... def __lt__(self, value: deque[_T], /) -> bool: ... def __le__(self, value: deque[_T], /) -> bool: ... @@ -299,7 +300,7 @@ class Counter(dict[_T, int], Generic[_T]): def elements(self) -> Iterator[_T]: ... def most_common(self, n: int | None = None) -> list[tuple[_T, int]]: ... @classmethod - def fromkeys(cls, iterable: Any, v: int | None = None) -> NoReturn: ... # type: ignore[override] + def fromkeys(cls, iterable: Any, v: int | None = None) -> Never: ... # type: ignore[override] @overload def subtract(self, iterable: None = None, /) -> None: ... diff --git a/python/helpers/typeshed/stdlib/concurrent/futures/process.pyi b/python/helpers/typeshed/stdlib/concurrent/futures/process.pyi index 282bafa0b611..6c7037cc0bbc 100644 --- a/python/helpers/typeshed/stdlib/concurrent/futures/process.pyi +++ b/python/helpers/typeshed/stdlib/concurrent/futures/process.pyi @@ -146,7 +146,12 @@ class _ExecutorManagerThread(Thread): def wait_result_broken_or_wakeup(self) -> tuple[Any, bool, str]: ... def process_result_item(self, result_item: int | _ResultItem) -> None: ... def is_shutting_down(self) -> bool: ... - def terminate_broken(self, cause: str) -> None: ... + + if sys.version_info >= (3, 15): + def terminate_broken(self, cause: str, bpe_message: str | None = None) -> None: ... + else: + def terminate_broken(self, cause: str) -> None: ... + def flag_executor_shutting_down(self) -> None: ... def shutdown_workers(self) -> None: ... def join_executor_internals(self) -> None: ... diff --git a/python/helpers/typeshed/stdlib/ctypes/__init__.pyi b/python/helpers/typeshed/stdlib/ctypes/__init__.pyi index 7eee1b760063..7760ddf9d8cb 100644 --- a/python/helpers/typeshed/stdlib/ctypes/__init__.pyi +++ b/python/helpers/typeshed/stdlib/ctypes/__init__.pyi @@ -168,10 +168,10 @@ c_buffer = create_string_buffer def create_unicode_buffer(init: int | str, size: int | None = None) -> Array[c_wchar]: ... if sys.version_info < (3, 15): - @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") + @deprecated("Deprecated; will be removed in Python 3.15.") def SetPointerType(pointer: type[_Pointer[Any]], cls: _CTypeBaseType) -> None: ... -@deprecated("Soft deprecated since Python 3.13. Use multiplication instead.") +@deprecated("Soft deprecated. Use multiplication instead.") def ARRAY(typ: _CT, len: int) -> Array[_CT]: ... if sys.platform == "win32": diff --git a/python/helpers/typeshed/stdlib/datetime.pyi b/python/helpers/typeshed/stdlib/datetime.pyi index 95c62a9c1b71..0a21f72b09de 100644 --- a/python/helpers/typeshed/stdlib/datetime.pyi +++ b/python/helpers/typeshed/stdlib/datetime.pyi @@ -1,8 +1,8 @@ import sys from abc import abstractmethod from time import struct_time -from typing import ClassVar, Final, NoReturn, SupportsIndex, TypeAlias, final, overload, type_check_only -from typing_extensions import CapsuleType, Self, deprecated, disjoint_base +from typing import ClassVar, Final, SupportsIndex, TypeAlias, final, overload, type_check_only +from typing_extensions import CapsuleType, Never, Self, deprecated, disjoint_base if sys.version_info >= (3, 11): __all__ = ("date", "datetime", "time", "timedelta", "timezone", "tzinfo", "MINYEAR", "MAXYEAR", "UTC") @@ -114,7 +114,7 @@ class date: def __radd__(self, value: timedelta, /) -> Self: ... @overload - def __sub__(self, value: datetime, /) -> NoReturn: ... + def __sub__(self, value: datetime, /) -> Never: ... @overload def __sub__(self, value: Self, /) -> timedelta: ... @overload diff --git a/python/helpers/typeshed/stdlib/decimal.pyi b/python/helpers/typeshed/stdlib/decimal.pyi index f16fa8aaae31..f116603cf0f2 100644 --- a/python/helpers/typeshed/stdlib/decimal.pyi +++ b/python/helpers/typeshed/stdlib/decimal.pyi @@ -184,7 +184,7 @@ class Context: # even settable attributes like `prec` and `rounding`, # but that's inexpressible 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 + # if you add a `def __delattr__(self, name: str, /) -> Never` method to the stub prec: int rounding: str Emin: int diff --git a/python/helpers/typeshed/stdlib/http/server.pyi b/python/helpers/typeshed/stdlib/http/server.pyi index 88cd2469cf11..6bab228f2ce7 100644 --- a/python/helpers/typeshed/stdlib/http/server.pyi +++ b/python/helpers/typeshed/stdlib/http/server.pyi @@ -128,7 +128,7 @@ class SimpleHTTPRequestHandler(BaseHTTPRequestHandler): def executable(path: StrPath) -> bool: ... # undocumented if sys.version_info < (3, 15): - @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") + @deprecated("Deprecated and unsafe; will be removed in Python 3.15.") class CGIHTTPRequestHandler(SimpleHTTPRequestHandler): cgi_directories: list[str] have_fork: bool # undocumented diff --git a/python/helpers/typeshed/stdlib/imaplib.pyi b/python/helpers/typeshed/stdlib/imaplib.pyi index fd14e45ed725..2ed47b18b19c 100644 --- a/python/helpers/typeshed/stdlib/imaplib.pyi +++ b/python/helpers/typeshed/stdlib/imaplib.pyi @@ -84,11 +84,20 @@ class IMAP4: if sys.version_info >= (3, 14): def idle(self, duration: float | None = None) -> Idler: ... - def list(self, directory: str = '""', pattern: str = "*") -> tuple[str, _AnyResponseData]: ... + if sys.version_info >= (3, 15): + def list(self, directory: str = "", pattern: str = "*") -> tuple[str, _AnyResponseData]: ... + else: + def list(self, directory: str = '""', pattern: str = "*") -> tuple[str, _AnyResponseData]: ... + def login(self, user: str, password: str) -> tuple[Literal["OK"], _list[bytes]]: ... def login_cram_md5(self, user: str, password: str) -> _CommandResults: ... def logout(self) -> tuple[str, _AnyResponseData]: ... - def lsub(self, directory: str = '""', pattern: str = "*") -> _CommandResults: ... + + if sys.version_info >= (3, 15): + def lsub(self, directory: str = "", pattern: str = "*") -> _CommandResults: ... + else: + def lsub(self, directory: str = '""', pattern: str = "*") -> _CommandResults: ... + def myrights(self, mailbox: str) -> _CommandResults: ... def namespace(self) -> _CommandResults: ... def noop(self) -> tuple[str, _list[bytes]]: ... @@ -98,7 +107,12 @@ class IMAP4: def search(self, charset: str | None, *criteria: str) -> _CommandResults: ... def select(self, mailbox: str = "INBOX", readonly: bool = False) -> tuple[str, _list[bytes | None]]: ... def setacl(self, mailbox: str, who: str, what: str) -> _CommandResults: ... - def setannotation(self, *args: str) -> _CommandResults: ... + + if sys.version_info >= (3, 15): + def setannotation(self, mailbox: str | bytes, *args: str) -> _CommandResults: ... + else: + def setannotation(self, *args: str) -> _CommandResults: ... + def setquota(self, root: str, limits: str) -> _CommandResults: ... def sort(self, sort_criteria: str, charset: str, *search_criteria: str) -> _CommandResults: ... def starttls(self, ssl_context: Any | None = None) -> tuple[Literal["OK"], _list[None]]: ... diff --git a/python/helpers/typeshed/stdlib/importlib/readers.pyi b/python/helpers/typeshed/stdlib/importlib/readers.pyi index 50f06ea5434d..c02f29d0a722 100644 --- a/python/helpers/typeshed/stdlib/importlib/readers.pyi +++ b/python/helpers/typeshed/stdlib/importlib/readers.pyi @@ -9,7 +9,7 @@ from _typeshed import StrPath from collections.abc import Iterable, Iterator from importlib._bootstrap_external import FileLoader from io import BufferedReader -from typing import Literal, NoReturn, TypeVar +from typing import Literal, TypeVar from typing_extensions import Never from zipimport import zipimporter @@ -43,8 +43,8 @@ class ZipReader(abc.TraversableResources): class MultiplexedPath(abc.Traversable): def __init__(self, *paths: abc.Traversable) -> None: ... def iterdir(self) -> Iterator[abc.Traversable]: ... - def read_bytes(self) -> NoReturn: ... - def read_text(self, *args: Never, **kwargs: Never) -> NoReturn: ... # type: ignore[override] + def read_bytes(self) -> Never: ... + def read_text(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] def is_dir(self) -> Literal[True]: ... def is_file(self) -> Literal[False]: ... @@ -58,7 +58,7 @@ class MultiplexedPath(abc.Traversable): if sys.version_info < (3, 12): __truediv__ = joinpath - def open(self, *args: Never, **kwargs: Never) -> NoReturn: ... # type: ignore[override] + def open(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] @property def name(self) -> str: ... diff --git a/python/helpers/typeshed/stdlib/importlib/resources/__init__.pyi b/python/helpers/typeshed/stdlib/importlib/resources/__init__.pyi index 5e58ddf310c9..4d3072ffe854 100644 --- a/python/helpers/typeshed/stdlib/importlib/resources/__init__.pyi +++ b/python/helpers/typeshed/stdlib/importlib/resources/__init__.pyi @@ -62,7 +62,7 @@ else: def read_text(package: Package, resource: Resource, encoding: str = "utf-8", errors: str = "strict") -> str: ... def path(package: Package, resource: Resource) -> AbstractContextManager[Path, Literal[False]]: ... def is_resource(package: Package, name: str) -> bool: ... - @deprecated("Deprecated since Python 3.11. Use `files(anchor).iterdir()`.") + @deprecated("Deprecated; limited resource support. Use `files(anchor).iterdir()`.") def contents(package: Package) -> Iterator[str]: ... if sys.version_info >= (3, 11): diff --git a/python/helpers/typeshed/stdlib/importlib/resources/abc.pyi b/python/helpers/typeshed/stdlib/importlib/resources/abc.pyi index 20a4b1fc5dfe..fd604997ff4a 100644 --- a/python/helpers/typeshed/stdlib/importlib/resources/abc.pyi +++ b/python/helpers/typeshed/stdlib/importlib/resources/abc.pyi @@ -7,7 +7,7 @@ from typing import IO, Any, Literal, Protocol, overload, runtime_checkable from typing_extensions import deprecated if sys.version_info >= (3, 11): - @deprecated("Deprecated since Python 3.12. Use `importlib.resources.abc.TraversableResources` instead.") + @deprecated("Deprecated. Use `importlib.resources.abc.TraversableResources` instead.") class ResourceReader(metaclass=ABCMeta): @abstractmethod def open_resource(self, resource: str) -> IO[bytes]: ... diff --git a/python/helpers/typeshed/stdlib/importlib/resources/simple.pyi b/python/helpers/typeshed/stdlib/importlib/resources/simple.pyi index ef9882056a9c..933a6ff164df 100644 --- a/python/helpers/typeshed/stdlib/importlib/resources/simple.pyi +++ b/python/helpers/typeshed/stdlib/importlib/resources/simple.pyi @@ -3,7 +3,7 @@ import sys from _typeshed import StrPath from collections.abc import Iterator from io import TextIOWrapper -from typing import IO, Any, BinaryIO, Literal, NoReturn, overload +from typing import IO, Any, BinaryIO, Literal, overload from typing_extensions import Never if sys.version_info >= (3, 11): @@ -43,7 +43,7 @@ if sys.version_info >= (3, 11): @overload def open(self, mode: str) -> IO[Any]: ... - def joinpath(self, name: Never) -> NoReturn: ... # type: ignore[override] + def joinpath(self, name: Never) -> Never: ... # type: ignore[override] class ResourceContainer(Traversable, metaclass=abc.ABCMeta): reader: SimpleReader @@ -51,7 +51,7 @@ if sys.version_info >= (3, 11): def is_dir(self) -> Literal[True]: ... def is_file(self) -> Literal[False]: ... def iterdir(self) -> Iterator[ResourceHandle | ResourceContainer]: ... - def open(self, *args: Never, **kwargs: Never) -> NoReturn: ... # type: ignore[override] + def open(self, *args: Never, **kwargs: Never) -> Never: ... # type: ignore[override] if sys.version_info < (3, 12): def joinpath(self, *descendants: StrPath) -> Traversable: ... diff --git a/python/helpers/typeshed/stdlib/lib2to3/pgen2/pgen.pyi b/python/helpers/typeshed/stdlib/lib2to3/pgen2/pgen.pyi index 4b951e1489e1..e0e2b8593a34 100644 --- a/python/helpers/typeshed/stdlib/lib2to3/pgen2/pgen.pyi +++ b/python/helpers/typeshed/stdlib/lib2to3/pgen2/pgen.pyi @@ -1,6 +1,7 @@ from _typeshed import Incomplete, StrPath from collections.abc import Iterable, Iterator -from typing import IO, ClassVar, NoReturn, overload +from typing import IO, ClassVar, overload +from typing_extensions import Never from . import grammar from .tokenize import _TokenInfo @@ -31,9 +32,9 @@ class ParserGenerator: def gettoken(self) -> None: ... @overload - def raise_error(self, msg: object) -> NoReturn: ... + def raise_error(self, msg: object) -> Never: ... @overload - def raise_error(self, msg: str, *args: object) -> NoReturn: ... + def raise_error(self, msg: str, *args: object) -> Never: ... class NFAState: arcs: list[tuple[str | None, NFAState]] diff --git a/python/helpers/typeshed/stdlib/lib2to3/refactor.pyi b/python/helpers/typeshed/stdlib/lib2to3/refactor.pyi index dfec28b758b5..b365d64a1de1 100644 --- a/python/helpers/typeshed/stdlib/lib2to3/refactor.pyi +++ b/python/helpers/typeshed/stdlib/lib2to3/refactor.pyi @@ -3,7 +3,8 @@ from collections.abc import Container, Generator, Iterable, Mapping from logging import Logger, _ExcInfoType from multiprocessing import JoinableQueue from multiprocessing.synchronize import Lock -from typing import Any, ClassVar, Final, NoReturn, overload +from typing import Any, ClassVar, Final, overload +from typing_extensions import Never from .btm_matcher import BottomMatcher from .fixer_base import BaseFix @@ -39,7 +40,7 @@ class RefactoringTool: self, fixer_names: Iterable[str], options: Mapping[str, object] | None = None, explicit: Container[str] | None = None ) -> None: ... def get_fixers(self) -> tuple[list[BaseFix], list[BaseFix]]: ... - def log_error(self, msg: str, *args: Iterable[str], **kwargs: _ExcInfoType) -> NoReturn: ... + def log_error(self, msg: str, *args: Iterable[str], **kwargs: _ExcInfoType) -> Never: ... @overload def log_message(self, msg: object) -> None: ... diff --git a/python/helpers/typeshed/stdlib/locale.pyi b/python/helpers/typeshed/stdlib/locale.pyi index 1be68ec51634..d234a08d779c 100644 --- a/python/helpers/typeshed/stdlib/locale.pyi +++ b/python/helpers/typeshed/stdlib/locale.pyi @@ -138,7 +138,7 @@ def getpreferredencoding(do_setlocale: bool = True) -> _str: ... def normalize(localename: _str) -> _str: ... if sys.version_info < (3, 13): - @deprecated("Deprecated since Python 3.11; removed in Python 3.13. Use `locale.setlocale(locale.LC_ALL, '')` instead.") + @deprecated("Deprecated; removed in Python 3.13. Use `locale.setlocale(locale.LC_ALL, '')` instead.") def resetlocale(category: int = ...) -> None: ... if sys.version_info < (3, 12): diff --git a/python/helpers/typeshed/stdlib/mmap.pyi b/python/helpers/typeshed/stdlib/mmap.pyi index 587b91d86c08..7aedd6711b01 100644 --- a/python/helpers/typeshed/stdlib/mmap.pyi +++ b/python/helpers/typeshed/stdlib/mmap.pyi @@ -2,8 +2,8 @@ import os import sys from _typeshed import ReadableBuffer, Unused from collections.abc import Iterator -from typing import Final, Literal, NoReturn, SupportsIndex, overload -from typing_extensions import Self, disjoint_base +from typing import Final, Literal, SupportsIndex, overload +from typing_extensions import Never, Self, disjoint_base ACCESS_DEFAULT: Final = 0 ACCESS_READ: Final = 1 @@ -113,7 +113,7 @@ class mmap: @overload def __getitem__(self, key: slice[SupportsIndex | None], /) -> bytes: ... - def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> NoReturn: ... + def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> Never: ... @overload def __setitem__(self, key: SupportsIndex, value: int, /) -> None: ... diff --git a/python/helpers/typeshed/stdlib/nturl2path.pyi b/python/helpers/typeshed/stdlib/nturl2path.pyi index 98686ed65420..3871f263f4e3 100644 --- a/python/helpers/typeshed/stdlib/nturl2path.pyi +++ b/python/helpers/typeshed/stdlib/nturl2path.pyi @@ -1,6 +1,6 @@ from typing_extensions import deprecated -@deprecated("The `nturl2path` module is deprecated since Python 3.14.") +@deprecated("Deprecated; use `urllib.request` file-URL helpers instead.") def url2pathname(url: str) -> str: ... -@deprecated("The `nturl2path` module is deprecated since Python 3.14.") +@deprecated("Deprecated; use `urllib.request` file-URL helpers instead.") def pathname2url(p: str) -> str: ... diff --git a/python/helpers/typeshed/stdlib/optparse.pyi b/python/helpers/typeshed/stdlib/optparse.pyi index 9e5536610272..35dfc54a9d49 100644 --- a/python/helpers/typeshed/stdlib/optparse.pyi +++ b/python/helpers/typeshed/stdlib/optparse.pyi @@ -2,8 +2,8 @@ import builtins from _typeshed import MaybeNone, SupportsWrite from abc import abstractmethod from collections.abc import Callable, Iterable, Mapping, Sequence -from typing import Any, ClassVar, Final, Literal, NoReturn, overload -from typing_extensions import Self +from typing import Any, ClassVar, Final, Literal, overload +from typing_extensions import Never, Self __all__ = [ "Option", @@ -291,8 +291,8 @@ class OptionParser(OptionContainer): def check_values(self, values: Values, args: list[str]) -> tuple[Values, list[str]]: ... def disable_interspersed_args(self) -> None: ... def enable_interspersed_args(self) -> None: ... - def error(self, msg: str) -> NoReturn: ... - def exit(self, status: int = 0, msg: str | None = None) -> NoReturn: ... + def error(self, msg: str) -> Never: ... + def exit(self, status: int = 0, msg: str | None = None) -> Never: ... def expand_prog_name(self, s: str) -> str: ... def format_epilog(self, formatter: HelpFormatter) -> str: ... def format_help(self, formatter: HelpFormatter | None = None) -> str: ... diff --git a/python/helpers/typeshed/stdlib/os/__init__.pyi b/python/helpers/typeshed/stdlib/os/__init__.pyi index 00c155956fb0..5f99c35132ed 100644 --- a/python/helpers/typeshed/stdlib/os/__init__.pyi +++ b/python/helpers/typeshed/stdlib/os/__init__.pyi @@ -33,7 +33,6 @@ from typing import ( Final, Generic, Literal, - NoReturn, Protocol, TypeAlias, TypeVar, @@ -42,7 +41,7 @@ from typing import ( runtime_checkable, type_check_only, ) -from typing_extensions import LiteralString, Self, Unpack, deprecated +from typing_extensions import LiteralString, Never, Self, Unpack, deprecated from . import path as _path @@ -1471,19 +1470,17 @@ if sys.platform != "win32": follow_symlinks: bool = True, ) -> None: ... -def abort() -> NoReturn: ... +def abort() -> Never: ... # These are defined as execl(file, *args) but the first *arg is mandatory. -def execl(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]]]]) -> NoReturn: ... -def execlp(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]]]]) -> NoReturn: ... +def execl(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]]]]) -> Never: ... +def execlp(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]]]]) -> Never: ... # These are: execle(file, *args, env) but env is pulled from the last element of the args. -def execle( - file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]], _ExecEnv]] -) -> NoReturn: ... +def execle(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]], _ExecEnv]]) -> Never: ... def execlpe( file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]], _ExecEnv]] -) -> NoReturn: ... +) -> Never: ... # The docs say `args: tuple or list of strings` # The implementation enforces tuple or list so we can't use Sequence. @@ -1506,11 +1503,11 @@ _ExecVArgs: TypeAlias = ( # we limit to str | bytes. _ExecEnv: TypeAlias = Mapping[bytes, bytes | str] | Mapping[str, bytes | str] -def execv(path: StrOrBytesPath, argv: _ExecVArgs, /) -> NoReturn: ... -def execve(path: FileDescriptorOrPath, argv: _ExecVArgs, env: _ExecEnv) -> NoReturn: ... -def execvp(file: StrOrBytesPath, args: _ExecVArgs) -> NoReturn: ... -def execvpe(file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> NoReturn: ... -def _exit(status: int) -> NoReturn: ... +def execv(path: StrOrBytesPath, argv: _ExecVArgs, /) -> Never: ... +def execve(path: FileDescriptorOrPath, argv: _ExecVArgs, env: _ExecEnv) -> Never: ... +def execvp(file: StrOrBytesPath, args: _ExecVArgs) -> Never: ... +def execvpe(file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> Never: ... +def _exit(status: int) -> Never: ... def kill(pid: int, signal: int, /) -> None: ... if sys.platform != "win32": diff --git a/python/helpers/typeshed/stdlib/pathlib/__init__.pyi b/python/helpers/typeshed/stdlib/pathlib/__init__.pyi index ca0d41f64958..fa011e6097a4 100644 --- a/python/helpers/typeshed/stdlib/pathlib/__init__.pyi +++ b/python/helpers/typeshed/stdlib/pathlib/__init__.pyi @@ -94,7 +94,7 @@ class PurePath(PathLike[str]): def __rtruediv__(self, key: StrPath) -> Self: ... def __bytes__(self) -> bytes: ... def as_posix(self) -> str: ... - @deprecated("Deprecated since Python 3.14; will be removed in Python 3.19. Use `Path.as_uri()` instead.") + @deprecated("Deprecated; will be removed in Python 3.19. Use `Path.as_uri()` instead.") def as_uri(self) -> str: ... def is_absolute(self) -> bool: ... if sys.version_info < (3, 15): @@ -112,7 +112,7 @@ class PurePath(PathLike[str]): @overload def is_relative_to(self, other: StrPath, /) -> bool: ... @overload - @deprecated("Passing additional arguments is deprecated since Python 3.12; removed in Python 3.14.") + @deprecated("Passing additional arguments is deprecated; removed in Python 3.14.") def is_relative_to(self, other: StrPath, /, *_deprecated: StrPath) -> bool: ... if sys.version_info >= (3, 12): diff --git a/python/helpers/typeshed/stdlib/pkgutil.pyi b/python/helpers/typeshed/stdlib/pkgutil.pyi index 365792bed952..6fdb01e728f4 100644 --- a/python/helpers/typeshed/stdlib/pkgutil.pyi +++ b/python/helpers/typeshed/stdlib/pkgutil.pyi @@ -39,9 +39,9 @@ if sys.version_info < (3, 12): def __init__(self, fullname: str, file: IO[str], filename: StrOrBytesPath, etc: tuple[str, str, int]) -> None: ... if sys.version_info < (3, 14): - @deprecated("Deprecated since Python 3.12; removed in Python 3.14. Use `importlib.util.find_spec()` instead.") + @deprecated("Deprecated; removed in Python 3.14. Use `importlib.util.find_spec()` instead.") def find_loader(fullname: str) -> LoaderProtocol | None: ... - @deprecated("Deprecated since Python 3.12; removed in Python 3.14. Use `importlib.util.find_spec()` instead.") + @deprecated("Deprecated; removed in Python 3.14. Use `importlib.util.find_spec()` instead.") def get_loader(module_or_name: str) -> LoaderProtocol | None: ... def get_importer(path_item: StrOrBytesPath) -> PathEntryFinderProtocol | None: ... diff --git a/python/helpers/typeshed/stdlib/platform.pyi b/python/helpers/typeshed/stdlib/platform.pyi index 07100d3bd592..b262186a68e4 100644 --- a/python/helpers/typeshed/stdlib/platform.pyi +++ b/python/helpers/typeshed/stdlib/platform.pyi @@ -11,7 +11,7 @@ def mac_ver( ) -> tuple[str, tuple[str, str, str], str]: ... if sys.version_info < (3, 15): - @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") + @deprecated("Deprecated; will be removed in Python 3.15.") def java_ver( release: str = "", vendor: str = "", diff --git a/python/helpers/typeshed/stdlib/poplib.pyi b/python/helpers/typeshed/stdlib/poplib.pyi index d4555a6b5ec0..59d95c0882f1 100644 --- a/python/helpers/typeshed/stdlib/poplib.pyi +++ b/python/helpers/typeshed/stdlib/poplib.pyi @@ -4,8 +4,8 @@ import sys from _typeshed import StrOrBytesPath from builtins import list as _list # conflicts with a method named "list" from re import Pattern -from typing import Any, BinaryIO, Final, NoReturn, TypeAlias, overload -from typing_extensions import deprecated +from typing import Any, BinaryIO, Final, TypeAlias, overload +from typing_extensions import Never, deprecated __all__ = ["POP3", "error_proto", "POP3_SSL"] @@ -59,7 +59,7 @@ class POP3_SSL(POP3): def __init__( self, host: str, port: int = 995, *, timeout: float = ..., context: ssl.SSLContext | None = None ) -> None: ... - def stls(self, context: Any = None) -> NoReturn: ... + def stls(self, context: Any = None) -> Never: ... else: @overload def __init__( @@ -90,4 +90,4 @@ class POP3_SSL(POP3): certfile: StrOrBytesPath | None # "context" is actually the last argument, # but that breaks LSP and it doesn't really matter because all the arguments are ignored - def stls(self, context: Any = None, keyfile: Any = None, certfile: Any = None) -> NoReturn: ... + def stls(self, context: Any = None, keyfile: Any = None, certfile: Any = None) -> Never: ... diff --git a/python/helpers/typeshed/stdlib/pty.pyi b/python/helpers/typeshed/stdlib/pty.pyi index e74c02ab1e1e..2bb48d782de6 100644 --- a/python/helpers/typeshed/stdlib/pty.pyi +++ b/python/helpers/typeshed/stdlib/pty.pyi @@ -15,9 +15,9 @@ if sys.platform != "win32": def openpty() -> tuple[int, int]: ... if sys.version_info < (3, 14): - @deprecated("Deprecated since Python 3.12; removed in Python 3.14. Use `openpty()` instead.") + @deprecated("Deprecated; removed in Python 3.14. Use `openpty()` instead.") def master_open() -> tuple[int, str]: ... - @deprecated("Deprecated since Python 3.12; removed in Python 3.14. Use `openpty()` instead.") + @deprecated("Deprecated; removed in Python 3.14. Use `openpty()` instead.") def slave_open(tty_name: str) -> int: ... def fork() -> tuple[int, int]: ... diff --git a/python/helpers/typeshed/stdlib/pydoc.pyi b/python/helpers/typeshed/stdlib/pydoc.pyi index 2e423dd3d425..34b2e656f435 100644 --- a/python/helpers/typeshed/stdlib/pydoc.pyi +++ b/python/helpers/typeshed/stdlib/pydoc.pyi @@ -5,8 +5,8 @@ from builtins import list as _list # "list" conflicts with method name from collections.abc import Callable, Container, Mapping, MutableMapping from reprlib import Repr from types import MethodType, ModuleType, TracebackType -from typing import IO, Any, AnyStr, Final, NoReturn, Protocol, TypeGuard, TypeVar, overload, type_check_only -from typing_extensions import deprecated +from typing import IO, Any, AnyStr, Final, Protocol, TypeGuard, TypeVar, overload, type_check_only +from typing_extensions import Never, deprecated __all__ = ["help"] @@ -32,7 +32,7 @@ def stripid(text: str) -> str: ... def allmethods(cl: type) -> MutableMapping[str, MethodType]: ... def visiblename(name: str, all: Container[str] | None = None, obj: object = None) -> bool: ... def classify_class_attrs(object: object) -> list[tuple[str, str, type, str]]: ... -@deprecated("Deprecated since Python 3.13.") +@deprecated("Deprecated.") def ispackage(path: StrPath) -> bool: ... # undocumented def source_synopsis(file: IO[AnyStr]) -> AnyStr | None: ... def synopsis(filename: str, cache: MutableMapping[str, tuple[int, str]] = {}) -> str | None: ... @@ -60,7 +60,7 @@ class Doc: STDLIB_DIR: str def document(self, object: object, name: str | None = None, *args: Any) -> str: ... - def fail(self, object: object, name: str | None = None, *args: Any) -> NoReturn: ... + def fail(self, object: object, name: str | None = None, *args: Any) -> Never: ... @abstractmethod def docmodule(self, object: object, name: str | None = None, *args: Any) -> str: ... @abstractmethod diff --git a/python/helpers/typeshed/stdlib/random.pyi b/python/helpers/typeshed/stdlib/random.pyi index 80fd2c7628a5..c70c8364684c 100644 --- a/python/helpers/typeshed/stdlib/random.pyi +++ b/python/helpers/typeshed/stdlib/random.pyi @@ -3,8 +3,8 @@ import sys from _typeshed import SupportsLenAndGetItem from collections.abc import Callable, Iterable, MutableSequence, Sequence, Set as AbstractSet from fractions import Fraction -from typing import Any, ClassVar, NoReturn, TypeVar, overload -from typing_extensions import deprecated +from typing import Any, ClassVar, TypeVar, overload +from typing_extensions import Never, deprecated __all__ = [ "Random", @@ -104,8 +104,8 @@ class Random(_random.Random): # SystemRandom is not implemented for all OS's; good on Windows & Linux class SystemRandom(Random): def getrandbits(self, k: int) -> int: ... # k can be passed by keyword - def getstate(self, *args: Any, **kwds: Any) -> NoReturn: ... - def setstate(self, *args: Any, **kwds: Any) -> NoReturn: ... + def getstate(self, *args: Any, **kwds: Any) -> Never: ... + def setstate(self, *args: Any, **kwds: Any) -> Never: ... _inst: Random seed = _inst.seed diff --git a/python/helpers/typeshed/stdlib/re.pyi b/python/helpers/typeshed/stdlib/re.pyi index 0183d7a81331..f0a892c797e9 100644 --- a/python/helpers/typeshed/stdlib/re.pyi +++ b/python/helpers/typeshed/stdlib/re.pyi @@ -169,7 +169,7 @@ class Pattern(Generic[AnyStr]): @overload def split(self, string: AnyStr, maxsplit: int = 0) -> list[AnyStr | MaybeNone]: ... - # return type depends on the number of groups in the pattern + # return type is either list[str/bytes] or list[tuple[str/bytes, ...]] @overload def findall(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> list[Any]: ... @overload @@ -302,6 +302,7 @@ def split( pattern: bytes | Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0, flags: _FlagsType = 0 ) -> list[bytes | MaybeNone]: ... +# return type is either list[str/bytes] or list[tuple[str/bytes, ...]] @overload def findall(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> list[Any]: ... @overload @@ -342,5 +343,5 @@ def escape(pattern: AnyStr) -> AnyStr: ... def purge() -> None: ... if sys.version_info < (3, 13): - @deprecated("Deprecated since Python 3.11; removed in Python 3.13. Use `re.compile()` instead.") + @deprecated("Deprecated; removed in Python 3.13. Use `re.compile()` instead.") def template(pattern: AnyStr | Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: ... # undocumented diff --git a/python/helpers/typeshed/stdlib/shutil.pyi b/python/helpers/typeshed/stdlib/shutil.pyi index badb0bae220d..5919106f3ed9 100644 --- a/python/helpers/typeshed/stdlib/shutil.pyi +++ b/python/helpers/typeshed/stdlib/shutil.pyi @@ -3,8 +3,8 @@ import sys from _typeshed import BytesPath, ExcInfo, FileDescriptorOrPath, MaybeNone, StrOrBytesPath, StrPath, SupportsRead, SupportsWrite from collections.abc import Callable, Iterable, Sequence from tarfile import _TarfileFilter -from typing import Any, AnyStr, NamedTuple, NoReturn, Protocol, TypeAlias, TypeVar, overload, type_check_only -from typing_extensions import deprecated +from typing import Any, AnyStr, NamedTuple, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, deprecated __all__ = [ "copyfileobj", @@ -191,7 +191,7 @@ else: if sys.platform == "win32" and sys.version_info < (3, 12): @overload @deprecated("On Windows before Python 3.12, using a PathLike as `cmd` would always fail or return `None`.") - def which(cmd: os.PathLike[str], mode: int = 1, path: StrPath | None = None) -> NoReturn: ... + def which(cmd: os.PathLike[str], mode: int = 1, path: StrPath | None = None) -> Never: ... @overload def which(cmd: StrPath, mode: int = 1, path: StrPath | None = None) -> str | None: ... diff --git a/python/helpers/typeshed/stdlib/sunau.pyi b/python/helpers/typeshed/stdlib/sunau.pyi index 1f18c041465e..e4b9fcb6b8ca 100644 --- a/python/helpers/typeshed/stdlib/sunau.pyi +++ b/python/helpers/typeshed/stdlib/sunau.pyi @@ -1,6 +1,6 @@ from _typeshed import Unused -from typing import IO, Any, Final, Literal, NamedTuple, NoReturn, TypeAlias, overload -from typing_extensions import Self +from typing import IO, Any, Final, Literal, NamedTuple, TypeAlias, overload +from typing_extensions import Never, Self _File: TypeAlias = str | IO[bytes] @@ -46,7 +46,7 @@ class Au_read: def getcompname(self) -> str: ... def getparams(self) -> _sunau_params: ... def getmarkers(self) -> None: ... - def getmark(self, id: Any) -> NoReturn: ... + def getmark(self, id: Any) -> Never: ... def setpos(self, pos: int) -> None: ... def readframes(self, nframes: int) -> bytes | None: ... diff --git a/python/helpers/typeshed/stdlib/symtable.pyi b/python/helpers/typeshed/stdlib/symtable.pyi index d41ef8419dec..3c6a828fad2a 100644 --- a/python/helpers/typeshed/stdlib/symtable.pyi +++ b/python/helpers/typeshed/stdlib/symtable.pyi @@ -56,7 +56,7 @@ class Function(SymbolTable): def get_nonlocals(self) -> tuple[str, ...]: ... class Class(SymbolTable): - @deprecated("Deprecated since Python 3.14; will be removed in Python 3.16.") + @deprecated("Deprecated; will be removed in Python 3.16.") def get_methods(self) -> tuple[str, ...]: ... class Symbol: diff --git a/python/helpers/typeshed/stdlib/sys/__init__.pyi b/python/helpers/typeshed/stdlib/sys/__init__.pyi index 72e894b9305f..11c78b73af5b 100644 --- a/python/helpers/typeshed/stdlib/sys/__init__.pyi +++ b/python/helpers/typeshed/stdlib/sys/__init__.pyi @@ -5,8 +5,8 @@ from builtins import object as _object from collections.abc import AsyncGenerator, Callable, Sequence from io import TextIOWrapper from types import FrameType, ModuleType, SimpleNamespace, TracebackType -from typing import Any, Final, Literal, NoReturn, Protocol, TextIO, TypeAlias, TypeVar, final, overload, type_check_only -from typing_extensions import LiteralString, deprecated +from typing import Any, Final, Literal, Protocol, TextIO, TypeAlias, TypeVar, final, overload, type_check_only +from typing_extensions import LiteralString, Never, deprecated _T = TypeVar("_T") _LazyImportMode: TypeAlias = Literal["normal", "all", "none"] @@ -377,7 +377,7 @@ def exc_info() -> OptExcInfo: ... if sys.version_info >= (3, 11): def exception() -> BaseException | None: ... -def exit(status: _ExitCode = None, /) -> NoReturn: ... +def exit(status: _ExitCode = None, /) -> Never: ... if sys.platform == "android": # noqa: Y008 def getandroidapilevel() -> int: ... @@ -521,7 +521,7 @@ if sys.version_info >= (3, 12): if sys.platform == "linux": def activate_stack_trampoline(backend: str, /) -> None: ... else: - def activate_stack_trampoline(backend: str, /) -> NoReturn: ... + def activate_stack_trampoline(backend: str, /) -> Never: ... from . import _monitoring diff --git a/python/helpers/typeshed/stdlib/sysconfig.pyi b/python/helpers/typeshed/stdlib/sysconfig.pyi index cfa3fbaceb73..bd20113e9df5 100644 --- a/python/helpers/typeshed/stdlib/sysconfig.pyi +++ b/python/helpers/typeshed/stdlib/sysconfig.pyi @@ -45,13 +45,13 @@ elif sys.version_info >= (3, 11): @overload def is_python_build() -> bool: ... @overload - @deprecated("The `check_home` parameter is deprecated since Python 3.12; removed in Python 3.15.") + @deprecated("The `check_home` parameter is deprecated; removed in Python 3.15.") def is_python_build(check_home: object = None) -> bool: ... else: @overload def is_python_build() -> bool: ... @overload - @deprecated("The `check_home` parameter is deprecated since Python 3.12; removed in Python 3.15.") + @deprecated("The `check_home` parameter is deprecated; removed in Python 3.15.") def is_python_build(check_home: bool = False) -> bool: ... def parse_config_h(fp: IO[Any], vars: dict[str, Any] | None = None) -> dict[str, Any]: ... diff --git a/python/helpers/typeshed/stdlib/tarfile.pyi b/python/helpers/typeshed/stdlib/tarfile.pyi index 6c55683fbaa3..7cfa098bb4f8 100644 --- a/python/helpers/typeshed/stdlib/tarfile.pyi +++ b/python/helpers/typeshed/stdlib/tarfile.pyi @@ -812,10 +812,10 @@ class TarInfo: def __init__(self, name: str = "") -> None: ... @property - @deprecated("Deprecated since Python 3.13; will be removed in Python 3.16.") + @deprecated("Deprecated; will be removed in Python 3.16.") def tarfile(self) -> TarFile | None: ... @tarfile.setter - @deprecated("Deprecated since Python 3.13; will be removed in Python 3.16.") + @deprecated("Deprecated; will be removed in Python 3.16.") def tarfile(self, tarfile: TarFile | None) -> None: ... @classmethod diff --git a/python/helpers/typeshed/stdlib/tkinter/__init__.pyi b/python/helpers/typeshed/stdlib/tkinter/__init__.pyi index 94787911df8d..45001cfea75a 100644 --- a/python/helpers/typeshed/stdlib/tkinter/__init__.pyi +++ b/python/helpers/typeshed/stdlib/tkinter/__init__.pyi @@ -329,13 +329,13 @@ class Variable: def trace_add(self, mode: Literal["array", "read", "write", "unset"], callback: Callable[[str, str, str], object]) -> str: ... def trace_remove(self, mode: Literal["array", "read", "write", "unset"], cbname: str) -> None: ... def trace_info(self) -> list[tuple[tuple[Literal["array", "read", "write", "unset"], ...], str]]: ... - @deprecated("Deprecated since Python 3.14. Use `trace_add()` instead.") + @deprecated("Deprecated; will be removed in Python 3.17. Use `trace_add()` instead.") def trace(self, mode, callback) -> str: ... - @deprecated("Deprecated since Python 3.14. Use `trace_add()` instead.") + @deprecated("Deprecated; will be removed in Python 3.17. Use `trace_add()` instead.") def trace_variable(self, mode, callback) -> str: ... - @deprecated("Deprecated since Python 3.14. Use `trace_remove()` instead.") + @deprecated("Deprecated; will be removed in Python 3.17. Use `trace_remove()` instead.") def trace_vdelete(self, mode, cbname) -> None: ... - @deprecated("Deprecated since Python 3.14. Use `trace_info()` instead.") + @deprecated("Deprecated; will be removed in Python 3.17. Use `trace_info()` instead.") def trace_vinfo(self) -> list[Incomplete]: ... def __eq__(self, other: object) -> bool: ... def __del__(self) -> None: ... diff --git a/python/helpers/typeshed/stdlib/typing.pyi b/python/helpers/typeshed/stdlib/typing.pyi index 8c1fb9d28d7c..35031a27445b 100644 --- a/python/helpers/typeshed/stdlib/typing.pyi +++ b/python/helpers/typeshed/stdlib/typing.pyi @@ -423,7 +423,7 @@ def overload(func: _F) -> _F: ... def no_type_check(arg: _F) -> _F: ... if sys.version_info < (3, 15): - @deprecated("Deprecated since Python 3.13; removed in Python 3.15.") + @deprecated("Deprecated; removed in Python 3.15.") def no_type_check_decorator(decorator: Callable[_P, _T]) -> Callable[_P, _T]: ... if sys.version_info >= (3, 15): diff --git a/python/helpers/typeshed/stdlib/typing_extensions.pyi b/python/helpers/typeshed/stdlib/typing_extensions.pyi index 5a8848e9151d..b89d96b2be9c 100644 --- a/python/helpers/typeshed/stdlib/typing_extensions.pyi +++ b/python/helpers/typeshed/stdlib/typing_extensions.pyi @@ -629,7 +629,7 @@ else: def __module__(self) -> str | None: ... # type: ignore[override] # Returns typing._GenericAlias, which isn't stubbed. def __getitem__(self, parameters: Incomplete | tuple[Incomplete, ...]) -> AnnotationForm: ... - def __init_subclass__(cls, *args: Unused, **kwargs: Unused) -> NoReturn: ... + def __init_subclass__(cls, *args: Unused, **kwargs: Unused) -> Never: ... def __or__(self, right: Any, /) -> _SpecialForm: ... def __ror__(self, left: Any, /) -> _SpecialForm: ... diff --git a/python/helpers/typeshed/stdlib/unittest/case.pyi b/python/helpers/typeshed/stdlib/unittest/case.pyi index 942154ea53ae..1d1206b7fc36 100644 --- a/python/helpers/typeshed/stdlib/unittest/case.pyi +++ b/python/helpers/typeshed/stdlib/unittest/case.pyi @@ -12,7 +12,6 @@ from typing import ( AnyStr, Final, Generic, - NoReturn, ParamSpec, Protocol, SupportsAbs, @@ -91,7 +90,7 @@ class TestCase: def tearDownClass(cls) -> None: ... def run(self, result: unittest.result.TestResult | None = None) -> unittest.result.TestResult | None: ... def __call__(self, result: unittest.result.TestResult | None = ...) -> unittest.result.TestResult | None: ... - def skipTest(self, reason: Any) -> NoReturn: ... + def skipTest(self, reason: Any) -> Never: ... def subTest(self, msg: Any = ..., **params: Any) -> AbstractContextManager[None]: ... def debug(self) -> None: ... if sys.version_info < (3, 11): @@ -267,7 +266,7 @@ class TestCase: # assertDictEqual accepts only true dict instances. We can't use that here, since that would make # assertDictEqual incompatible with TypedDict. def assertDictEqual(self, d1: Mapping[Any, object], d2: Mapping[Any, object], msg: Any = None) -> None: ... - def fail(self, msg: Any = None) -> NoReturn: ... + def fail(self, msg: Any = None) -> Never: ... def countTestCases(self) -> int: ... def defaultTestResult(self) -> unittest.result.TestResult: ... def id(self) -> str: ... diff --git a/python/helpers/typeshed/stdlib/unittest/loader.pyi b/python/helpers/typeshed/stdlib/unittest/loader.pyi index 0d92b78f3461..106004fadcc2 100644 --- a/python/helpers/typeshed/stdlib/unittest/loader.pyi +++ b/python/helpers/typeshed/stdlib/unittest/loader.pyi @@ -35,21 +35,21 @@ class TestLoader: defaultTestLoader: TestLoader if sys.version_info < (3, 13): - @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") + @deprecated("Deprecated; removed in Python 3.13.") def getTestCaseNames( testCaseClass: type[unittest.case.TestCase], prefix: str, sortUsing: _SortComparisonMethod = ..., testNamePatterns: list[str] | None = None, ) -> Sequence[str]: ... - @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") + @deprecated("Deprecated; removed in Python 3.13.") def makeSuite( testCaseClass: type[unittest.case.TestCase], prefix: str = "test", sortUsing: _SortComparisonMethod = ..., suiteClass: _SuiteClass = ..., ) -> unittest.suite.TestSuite: ... - @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") + @deprecated("Deprecated; removed in Python 3.13.") def findTestCases( module: ModuleType, prefix: str = "test", sortUsing: _SortComparisonMethod = ..., suiteClass: _SuiteClass = ... ) -> unittest.suite.TestSuite: ... diff --git a/python/helpers/typeshed/stdlib/unittest/main.pyi b/python/helpers/typeshed/stdlib/unittest/main.pyi index f48347c16ec3..09b547cd1cd6 100644 --- a/python/helpers/typeshed/stdlib/unittest/main.pyi +++ b/python/helpers/typeshed/stdlib/unittest/main.pyi @@ -64,7 +64,7 @@ class TestProgram: ) -> None: ... if sys.version_info < (3, 13): - @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") + @deprecated("Deprecated; removed in Python 3.13.") def usageExit(self, msg: Any = None) -> None: ... def parseArgs(self, argv: list[str]) -> None: ... diff --git a/python/helpers/typeshed/stdlib/urllib/request.pyi b/python/helpers/typeshed/stdlib/urllib/request.pyi index 0ec26052b23c..17a283321df4 100644 --- a/python/helpers/typeshed/stdlib/urllib/request.pyi +++ b/python/helpers/typeshed/stdlib/urllib/request.pyi @@ -6,8 +6,8 @@ from email.message import Message from http.client import HTTPConnection, HTTPMessage, HTTPResponse from http.cookiejar import CookieJar from re import Pattern -from typing import IO, Any, ClassVar, Literal, NoReturn, Protocol, TypeAlias, TypeVar, overload, type_check_only -from typing_extensions import deprecated +from typing import IO, Any, ClassVar, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, deprecated from urllib.error import HTTPError as HTTPError from urllib.response import addclosehook, addinfourl @@ -336,7 +336,7 @@ class CacheFTPHandler(FTPHandler): def clear_cache(self) -> None: ... # undocumented class UnknownHandler(BaseHandler): - def unknown_open(self, req: Request) -> NoReturn: ... + def unknown_open(self, req: Request) -> Never: ... class HTTPErrorProcessor(BaseHandler): def http_response(self, request: Request, response: HTTPResponse) -> _UrlopenRet: ... diff --git a/python/helpers/typeshed/stdlib/uuid.pyi b/python/helpers/typeshed/stdlib/uuid.pyi index 06285e03aea7..1b5d0c1fbf5a 100644 --- a/python/helpers/typeshed/stdlib/uuid.pyi +++ b/python/helpers/typeshed/stdlib/uuid.pyi @@ -2,8 +2,8 @@ import builtins import sys from _typeshed import Unused from enum import Enum -from typing import Final, NoReturn, TypeAlias -from typing_extensions import LiteralString +from typing import Final, TypeAlias +from typing_extensions import LiteralString, Never _FieldsType: TypeAlias = tuple[int, int, int, int, int, int] @@ -65,7 +65,7 @@ class UUID: def __gt__(self, other: UUID) -> bool: ... def __ge__(self, other: UUID) -> bool: ... def __hash__(self) -> builtins.int: ... - def __setattr__(self, name: Unused, value: Unused) -> NoReturn: ... + def __setattr__(self, name: Unused, value: Unused) -> Never: ... def getnode() -> int: ... def uuid1(node: int | None = None, clock_seq: int | None = None) -> UUID: ... diff --git a/python/helpers/typeshed/stdlib/wave.pyi b/python/helpers/typeshed/stdlib/wave.pyi index 74f8b8a9e3cf..70bf87281550 100644 --- a/python/helpers/typeshed/stdlib/wave.pyi +++ b/python/helpers/typeshed/stdlib/wave.pyi @@ -1,7 +1,7 @@ import sys from _typeshed import ReadableBuffer, StrOrBytesPath, Unused -from typing import IO, Any, BinaryIO, Final, Literal, NamedTuple, NoReturn, TypeAlias, overload -from typing_extensions import Self, deprecated +from typing import IO, Any, BinaryIO, Final, Literal, NamedTuple, TypeAlias, overload +from typing_extensions import Never, Self, deprecated __all__ = ["open", "Error", "Wave_read", "Wave_write"] if sys.version_info >= (3, 15): @@ -47,10 +47,10 @@ class Wave_read: def getcompname(self) -> str: ... def getparams(self) -> _wave_params: ... if sys.version_info < (3, 15): - @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") + @deprecated("Deprecated; will be removed in Python 3.15.") def getmarkers(self) -> None: ... - @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") - def getmark(self, id: Any) -> NoReturn: ... + @deprecated("Deprecated; will be removed in Python 3.15.") + def getmark(self, id: Any) -> Never: ... def setpos(self, pos: int) -> None: ... def readframes(self, nframes: int) -> bytes: ... @@ -85,11 +85,11 @@ class Wave_write: def getparams(self) -> _wave_params: ... if sys.version_info < (3, 15): - @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") - def setmark(self, id: Any, pos: Any, name: Any) -> NoReturn: ... - @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") - def getmark(self, id: Any) -> NoReturn: ... - @deprecated("Deprecated since Python 3.13; will be removed in Python 3.15.") + @deprecated("Deprecated; will be removed in Python 3.15.") + def setmark(self, id: Any, pos: Any, name: Any) -> Never: ... + @deprecated("Deprecated; will be removed in Python 3.15.") + def getmark(self, id: Any) -> Never: ... + @deprecated("Deprecated; will be removed in Python 3.15.") def getmarkers(self) -> None: ... def tell(self) -> int: ... diff --git a/python/helpers/typeshed/stdlib/webbrowser.pyi b/python/helpers/typeshed/stdlib/webbrowser.pyi index 40b57c3c6a09..4bcaf3307591 100644 --- a/python/helpers/typeshed/stdlib/webbrowser.pyi +++ b/python/helpers/typeshed/stdlib/webbrowser.pyi @@ -64,7 +64,7 @@ if sys.platform == "win32": if sys.platform == "darwin": if sys.version_info < (3, 13): - @deprecated("Deprecated since Python 3.11; removed in Python 3.13.") + @deprecated("Deprecated; removed in Python 3.13.") class MacOSX(BaseBrowser): def __init__(self, name: str) -> None: ... def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ... diff --git a/python/helpers/typeshed/stdlib/wsgiref/validate.pyi b/python/helpers/typeshed/stdlib/wsgiref/validate.pyi index 498e03aa3673..ce3e79f341f9 100644 --- a/python/helpers/typeshed/stdlib/wsgiref/validate.pyi +++ b/python/helpers/typeshed/stdlib/wsgiref/validate.pyi @@ -1,6 +1,7 @@ from _typeshed.wsgi import ErrorStream, InputStream, WSGIApplication from collections.abc import Callable, Iterable, Iterator -from typing import Any, NoReturn, TypeAlias +from typing import Any, TypeAlias +from typing_extensions import Never __all__ = ["validator"] @@ -15,7 +16,7 @@ class InputWrapper: def readline(self, size: int = ...) -> bytes: ... def readlines(self, hint: int = ...) -> bytes: ... def __iter__(self) -> Iterator[bytes]: ... - def close(self) -> NoReturn: ... + def close(self) -> Never: ... class ErrorWrapper: errors: ErrorStream @@ -23,7 +24,7 @@ class ErrorWrapper: def write(self, s: str) -> None: ... def flush(self) -> None: ... def writelines(self, seq: Iterable[str]) -> None: ... - def close(self) -> NoReturn: ... + def close(self) -> Never: ... _WriterCallback: TypeAlias = Callable[[bytes], Any] diff --git a/python/helpers/typeshed/stdlib/xml/dom/expatbuilder.pyi b/python/helpers/typeshed/stdlib/xml/dom/expatbuilder.pyi index e41067182935..5aef384ff0f2 100644 --- a/python/helpers/typeshed/stdlib/xml/dom/expatbuilder.pyi +++ b/python/helpers/typeshed/stdlib/xml/dom/expatbuilder.pyi @@ -1,5 +1,6 @@ from _typeshed import ReadableBuffer, SupportsRead -from typing import Any, Final, NoReturn, TypeAlias +from typing import Any, Final, TypeAlias +from typing_extensions import Never from xml.dom.minidom import Document, DocumentFragment, DOMImplementation, Element, Node, TypeInfo from xml.dom.xmlbuilder import DOMBuilderFilter, Options from xml.parsers.expat import XMLParserType @@ -115,8 +116,8 @@ class InternalSubsetExtractor(ExpatBuilder): def start_doctype_decl_handler( # type: ignore[override] self, name: str, publicId: str | None, systemId: str | None, has_internal_subset: bool ) -> None: ... - def end_doctype_decl_handler(self) -> NoReturn: ... - def start_element_handler(self, name: str, attrs: list[str]) -> NoReturn: ... + def end_doctype_decl_handler(self) -> Never: ... + def start_element_handler(self, name: str, attrs: list[str]) -> Never: ... def parse(file: str | SupportsRead[ReadableBuffer | str], namespaces: bool = True) -> Document: ... def parseString(string: str | ReadableBuffer, namespaces: bool = True) -> Document: ... diff --git a/python/helpers/typeshed/stdlib/xml/dom/minidom.pyi b/python/helpers/typeshed/stdlib/xml/dom/minidom.pyi index c54b0de86e55..7d287a6c9b60 100644 --- a/python/helpers/typeshed/stdlib/xml/dom/minidom.pyi +++ b/python/helpers/typeshed/stdlib/xml/dom/minidom.pyi @@ -3,8 +3,8 @@ from _collections_abc import dict_keys, dict_values from _typeshed import Incomplete, ReadableBuffer, SupportsRead, SupportsWrite from collections.abc import Iterable, Sequence from types import TracebackType -from typing import Any, ClassVar, Generic, Literal, NoReturn, Protocol, TypeAlias, TypeVar, overload, type_check_only -from typing_extensions import Self +from typing import Any, ClassVar, Generic, Literal, Protocol, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, Self from xml.dom.minicompat import EmptyNodeList, NodeList from xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS from xml.sax.xmlreader import XMLReader @@ -367,14 +367,14 @@ class Childless: def firstChild(self) -> None: ... @property def lastChild(self) -> None: ... - def appendChild(self, node: _NodesThatAreChildren | DocumentFragment) -> NoReturn: ... + def appendChild(self, node: _NodesThatAreChildren | DocumentFragment) -> Never: ... def hasChildNodes(self) -> Literal[False]: ... def insertBefore( self, newChild: _NodesThatAreChildren | DocumentFragment, refChild: _NodesThatAreChildren | None - ) -> NoReturn: ... - def removeChild(self, oldChild: _NodesThatAreChildren) -> NoReturn: ... + ) -> Never: ... + def removeChild(self, oldChild: _NodesThatAreChildren) -> Never: ... def normalize(self) -> None: ... - def replaceChild(self, newChild: _NodesThatAreChildren | DocumentFragment, oldChild: _NodesThatAreChildren) -> NoReturn: ... + def replaceChild(self, newChild: _NodesThatAreChildren | DocumentFragment, oldChild: _NodesThatAreChildren) -> Never: ... class ProcessingInstruction(Childless, Node): __slots__ = ("target", "data") @@ -501,10 +501,10 @@ class ReadOnlySequentialNamedNodeMap(Generic[_N]): def getNamedItemNS(self, namespaceURI: str | None, localName: str) -> _N | None: ... def __getitem__(self, name_or_tuple: str | _NSName) -> _N | None: ... def item(self, index: int) -> _N | None: ... - def removeNamedItem(self, name: str) -> NoReturn: ... - def removeNamedItemNS(self, namespaceURI: str | None, localName: str) -> NoReturn: ... - def setNamedItem(self, node: Node) -> NoReturn: ... - def setNamedItemNS(self, node: Node) -> NoReturn: ... + def removeNamedItem(self, name: str) -> Never: ... + def removeNamedItemNS(self, namespaceURI: str | None, localName: str) -> Never: ... + def setNamedItem(self, node: Node) -> Never: ... + def setNamedItemNS(self, node: Node) -> Never: ... @property def length(self) -> int: ... @@ -568,10 +568,10 @@ class Entity(Identified, Node): notationName: str | None def __init__(self, name: str, publicId: str | None, systemId: str | None, notation: str | None) -> None: ... - def appendChild(self, newChild: _EntityChildren) -> NoReturn: ... # type: ignore[override] - def insertBefore(self, newChild: _EntityChildren, refChild: _EntityChildren | None) -> NoReturn: ... # type: ignore[override] - def removeChild(self, oldChild: _EntityChildren) -> NoReturn: ... # type: ignore[override] - def replaceChild(self, newChild: _EntityChildren, oldChild: _EntityChildren) -> NoReturn: ... # type: ignore[override] + def appendChild(self, newChild: _EntityChildren) -> Never: ... # type: ignore[override] + def insertBefore(self, newChild: _EntityChildren, refChild: _EntityChildren | None) -> Never: ... # type: ignore[override] + def removeChild(self, oldChild: _EntityChildren) -> Never: ... # type: ignore[override] + def replaceChild(self, newChild: _EntityChildren, oldChild: _EntityChildren) -> Never: ... # type: ignore[override] class Notation(Identified, Childless, Node): nodeType: ClassVar[Literal[12]] diff --git a/python/helpers/typeshed/stdlib/xml/dom/pulldom.pyi b/python/helpers/typeshed/stdlib/xml/dom/pulldom.pyi index 4ede39015585..7014c865bcdd 100644 --- a/python/helpers/typeshed/stdlib/xml/dom/pulldom.pyi +++ b/python/helpers/typeshed/stdlib/xml/dom/pulldom.pyi @@ -1,8 +1,8 @@ import sys from _typeshed import Incomplete, Unused from collections.abc import MutableSequence, Sequence -from typing import Final, Literal, NoReturn, TypeAlias -from typing_extensions import Self +from typing import Final, Literal, TypeAlias +from typing_extensions import Never, Self from xml.dom.minidom import Comment, Document, DOMImplementation, Element, ProcessingInstruction, Text from xml.sax import _SupportsReadClose from xml.sax.handler import ContentHandler @@ -73,8 +73,8 @@ class PullDOM(ContentHandler): class ErrorHandler: def warning(self, exception: BaseException) -> None: ... - def error(self, exception: BaseException) -> NoReturn: ... - def fatalError(self, exception: BaseException) -> NoReturn: ... + def error(self, exception: BaseException) -> Never: ... + def fatalError(self, exception: BaseException) -> Never: ... class DOMEventStream: stream: _SupportsReadClose[bytes] | _SupportsReadClose[str] diff --git a/python/helpers/typeshed/stdlib/xml/dom/xmlbuilder.pyi b/python/helpers/typeshed/stdlib/xml/dom/xmlbuilder.pyi index f19f7050b08d..686c9d8efe8f 100644 --- a/python/helpers/typeshed/stdlib/xml/dom/xmlbuilder.pyi +++ b/python/helpers/typeshed/stdlib/xml/dom/xmlbuilder.pyi @@ -1,5 +1,6 @@ from _typeshed import SupportsRead -from typing import Any, Final, Literal, NoReturn +from typing import Any, Final, Literal +from typing_extensions import Never from xml.dom.minidom import Document, Node, _DOMErrorHandler __all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"] @@ -41,7 +42,7 @@ class DOMBuilder: def getFeature(self, name: str) -> Any: ... def parseURI(self, uri: str) -> Document: ... def parse(self, input: DOMInputSource) -> Document: ... - def parseWithContext(self, input: DOMInputSource, cnode: Node, action: Literal[1, 2, 3, 4]) -> NoReturn: ... + def parseWithContext(self, input: DOMInputSource, cnode: Node, action: Literal[1, 2, 3, 4]) -> Never: ... class DOMEntityResolver: __slots__ = ("_opener",) @@ -68,14 +69,14 @@ class DOMBuilderFilter: class DocumentLS: async_: bool - def abort(self) -> NoReturn: ... - def load(self, uri: str) -> NoReturn: ... - def loadXML(self, source: str) -> NoReturn: ... + def abort(self) -> Never: ... + def load(self, uri: str) -> Never: ... + def loadXML(self, source: str) -> Never: ... def saveXML(self, snode: Node | None) -> str: ... class DOMImplementationLS: MODE_SYNCHRONOUS: Final = 1 MODE_ASYNCHRONOUS: Final = 2 def createDOMBuilder(self, mode: Literal[1], schemaType: None) -> DOMBuilder: ... - def createDOMWriter(self) -> NoReturn: ... + def createDOMWriter(self) -> Never: ... def createDOMInputSource(self) -> DOMInputSource: ... diff --git a/python/helpers/typeshed/stdlib/xml/sax/_exceptions.pyi b/python/helpers/typeshed/stdlib/xml/sax/_exceptions.pyi index e9cc8856a9c8..8f5e3a827185 100644 --- a/python/helpers/typeshed/stdlib/xml/sax/_exceptions.pyi +++ b/python/helpers/typeshed/stdlib/xml/sax/_exceptions.pyi @@ -1,11 +1,11 @@ -from typing import NoReturn +from typing_extensions import Never from xml.sax.xmlreader import Locator class SAXException(Exception): def __init__(self, msg: str, exception: Exception | None = None) -> None: ... def getMessage(self) -> str: ... def getException(self) -> Exception | None: ... - def __getitem__(self, ix: object) -> NoReturn: ... + def __getitem__(self, ix: object) -> Never: ... class SAXParseException(SAXException): def __init__(self, msg: str, exception: Exception | None, locator: Locator) -> None: ... diff --git a/python/helpers/typeshed/stdlib/xml/sax/handler.pyi b/python/helpers/typeshed/stdlib/xml/sax/handler.pyi index e1e080ac2d1a..654c98866cfb 100644 --- a/python/helpers/typeshed/stdlib/xml/sax/handler.pyi +++ b/python/helpers/typeshed/stdlib/xml/sax/handler.pyi @@ -1,17 +1,18 @@ -from typing import Final, NoReturn, Protocol, type_check_only +from typing import Final, Protocol, type_check_only +from typing_extensions import Never from xml.sax import xmlreader version: Final[str] @type_check_only class _ErrorHandlerProtocol(Protocol): # noqa: Y046 # Protocol is not used - def error(self, exception: BaseException) -> NoReturn: ... - def fatalError(self, exception: BaseException) -> NoReturn: ... + def error(self, exception: BaseException) -> Never: ... + def fatalError(self, exception: BaseException) -> Never: ... def warning(self, exception: BaseException) -> None: ... class ErrorHandler: - def error(self, exception: BaseException) -> NoReturn: ... - def fatalError(self, exception: BaseException) -> NoReturn: ... + def error(self, exception: BaseException) -> Never: ... + def fatalError(self, exception: BaseException) -> Never: ... def warning(self, exception: BaseException) -> None: ... @type_check_only diff --git a/python/helpers/typeshed/stdlib/xml/sax/saxutils.pyi b/python/helpers/typeshed/stdlib/xml/sax/saxutils.pyi index a29588faae2a..0f5251def6b0 100644 --- a/python/helpers/typeshed/stdlib/xml/sax/saxutils.pyi +++ b/python/helpers/typeshed/stdlib/xml/sax/saxutils.pyi @@ -2,7 +2,8 @@ from _typeshed import SupportsWrite from codecs import StreamReaderWriter, StreamWriter from collections.abc import Mapping from io import RawIOBase, TextIOBase -from typing import Literal, NoReturn +from typing import Literal +from typing_extensions import Never from xml.sax import _Source, handler, xmlreader def escape(data: str, entities: Mapping[str, str] = {}) -> str: ... @@ -32,8 +33,8 @@ class XMLGenerator(handler.ContentHandler): class XMLFilterBase(xmlreader.XMLReader): def __init__(self, parent: xmlreader.XMLReader | None = None) -> None: ... # ErrorHandler methods - def error(self, exception: BaseException) -> NoReturn: ... - def fatalError(self, exception: BaseException) -> NoReturn: ... + def error(self, exception: BaseException) -> Never: ... + def fatalError(self, exception: BaseException) -> Never: ... def warning(self, exception: BaseException) -> None: ... # ContentHandler methods def setDocumentLocator(self, locator: xmlreader.Locator) -> None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/METADATA.toml b/python/helpers/typeshed/stubs/Authlib/METADATA.toml index 5c2a9e76e1ed..6a322fd7f4d3 100644 --- a/python/helpers/typeshed/stubs/Authlib/METADATA.toml +++ b/python/helpers/typeshed/stubs/Authlib/METADATA.toml @@ -1,3 +1,3 @@ -version = "1.6.11" +version = "1.7.2" upstream-repository = "https://github.com/authlib/authlib" dependencies = ["cryptography"] diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/common/language.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/common/language.pyi new file mode 100644 index 000000000000..34b1ecf943aa --- /dev/null +++ b/python/helpers/typeshed/stubs/Authlib/authlib/common/language.pyi @@ -0,0 +1 @@ +def is_valid_language_tag(tag: object) -> bool: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/deprecate.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/deprecate.pyi index 201ceb6a53b2..cb8b6991a7d8 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/deprecate.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/deprecate.pyi @@ -1,5 +1,3 @@ class AuthlibDeprecationWarning(DeprecationWarning): ... -def deprecate( - message: str, version: str | None = None, link_uid: str | None = None, link_file: str | None = None, stacklevel: int = 3 -) -> None: ... +def deprecate(message: str, version: str | None = None, stacklevel: int = 3) -> None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/base_client/async_openid.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/base_client/async_openid.pyi index 702bed62fba3..3213ac6631b0 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/base_client/async_openid.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/base_client/async_openid.pyi @@ -1,3 +1,4 @@ +from authlib.integrations.base_client.sync_openid import _LogoutData from authlib.oidc.core.claims import UserInfo __all__ = ["AsyncOpenIDMixin"] @@ -6,3 +7,6 @@ class AsyncOpenIDMixin: async def fetch_jwk_set(self, force: bool = False): ... async def userinfo(self, **kwargs) -> UserInfo: ... async def parse_id_token(self, token, nonce, claims_options=None, claims_cls=None, leeway: int = 120) -> UserInfo: ... + async def create_logout_url( + self, post_logout_redirect_uri=None, id_token_hint=None, state=None, *, client_id=None, logout_hint=None, ui_locales=None + ) -> _LogoutData: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/base_client/sync_openid.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/base_client/sync_openid.pyi index a78b26b4f6fc..5bd8eb1de7da 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/base_client/sync_openid.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/base_client/sync_openid.pyi @@ -1,7 +1,17 @@ +from _typeshed import Incomplete +from typing import TypedDict, type_check_only + from authlib.oidc.core.claims import UserInfo +@type_check_only +class _LogoutData(TypedDict): + url: str + state: Incomplete + class OpenIDMixin: def fetch_jwk_set(self, force: bool = False): ... def userinfo(self, **kwargs) -> UserInfo: ... def parse_id_token(self, token, nonce, claims_options=None, claims_cls=None, leeway: int = 120) -> UserInfo | None: ... - def create_load_key(self): ... + def create_logout_url( + self, post_logout_redirect_uri=None, id_token_hint=None, state=None, *, client_id=None, logout_hint=None, ui_locales=None + ) -> _LogoutData: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/django_client/apps.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/django_client/apps.pyi index 895db81ec120..1325168c1fc4 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/django_client/apps.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/django_client/apps.pyi @@ -1,6 +1,11 @@ +from _typeshed import Incomplete +from typing import TypeAlias + from ..base_client import BaseApp, OAuth1Mixin, OAuth2Mixin, OpenIDMixin from ..requests_client import OAuth1Session, OAuth2Session +_HttpResponseRedirect: TypeAlias = Incomplete # actual type is django.http.response.HttpResponseRedirect + class DjangoAppMixin: def save_authorize_data(self, request, **kwargs) -> None: ... def authorize_redirect(self, request, redirect_uri=None, **kwargs): ... @@ -11,4 +16,16 @@ class DjangoOAuth1App(DjangoAppMixin, OAuth1Mixin, BaseApp): class DjangoOAuth2App(DjangoAppMixin, OAuth2Mixin, OpenIDMixin, BaseApp): client_cls = OAuth2Session + def logout_redirect( + self, + request, + post_logout_redirect_uri=None, + id_token_hint=None, + *, + state=None, + client_id=None, + logout_hint=None, + ui_locales=None, + ) -> _HttpResponseRedirect: ... + def validate_logout_response(self, request): ... def authorize_access_token(self, request, **kwargs): ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/flask_client/apps.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/flask_client/apps.pyi index 43b771e59a39..f11d6d1b7e74 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/flask_client/apps.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/flask_client/apps.pyi @@ -1,6 +1,11 @@ +from _typeshed import Incomplete +from typing import TypeAlias + from ..base_client import BaseApp, OAuth1Mixin, OAuth2Mixin, OpenIDMixin from ..requests_client import OAuth1Session, OAuth2Session +_Response: TypeAlias = Incomplete # actual type is werkzeug.wrappers.Response + class FlaskAppMixin: @property def token(self): ... @@ -16,4 +21,8 @@ class FlaskOAuth1App(FlaskAppMixin, OAuth1Mixin, BaseApp): class FlaskOAuth2App(FlaskAppMixin, OAuth2Mixin, OpenIDMixin, BaseApp): client_cls = OAuth2Session + def logout_redirect( + self, post_logout_redirect_uri=None, id_token_hint=None, *, state=None, client_id=None, logout_hint=None, ui_locales=None + ) -> _Response: ... + def validate_logout_response(self): ... def authorize_access_token(self, **kwargs): ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/flask_oauth2/errors.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/flask_oauth2/errors.pyi index 258839271bd5..63389264ebcc 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/flask_oauth2/errors.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/flask_oauth2/errors.pyi @@ -1,5 +1,5 @@ from _typeshed import Incomplete -from typing import NoReturn +from typing_extensions import Never # Inherits from werkzeug.exceptions.HTTPException class _HTTPException: @@ -11,4 +11,4 @@ class _HTTPException: def get_body(self, environ=None, scope=None): ... def get_headers(self, environ=None, scope=None): ... -def raise_http_exception(status, body, headers) -> NoReturn: ... +def raise_http_exception(status, body, headers) -> Never: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/flask_oauth2/resource_protector.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/flask_oauth2/resource_protector.pyi index a4c4928a04df..c0b262f8faf7 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/flask_oauth2/resource_protector.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/flask_oauth2/resource_protector.pyi @@ -1,12 +1,12 @@ from _typeshed import Incomplete from collections.abc import Generator from contextlib import contextmanager -from typing import NoReturn +from typing_extensions import Never from authlib.oauth2 import ResourceProtector as _ResourceProtector class ResourceProtector(_ResourceProtector): - def raise_error_response(self, error) -> NoReturn: ... + def raise_error_response(self, error) -> Never: ... def acquire_token(self, scopes=None, **kwargs): ... @contextmanager def acquire(self, scopes=None) -> Generator[Incomplete]: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/httpx_client/oauth1_client.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/httpx_client/oauth1_client.pyi index 9d99c64d4d5d..423172e9913e 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/httpx_client/oauth1_client.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/httpx_client/oauth1_client.pyi @@ -1,6 +1,7 @@ from _typeshed import Incomplete from collections.abc import Generator -from typing import NoReturn, TypeAlias +from typing import TypeAlias +from typing_extensions import Never from authlib.oauth1 import ClientAuth from authlib.oauth1.client import OAuth1Client as _OAuth1Client @@ -32,7 +33,7 @@ class AsyncOAuth1Client(_OAuth1Client): ) -> None: ... async def fetch_access_token(self, url, verifier=None, **kwargs): ... @staticmethod - def handle_error(error_type: str | None, error_description: str | None) -> NoReturn: ... + def handle_error(error_type: str | None, error_description: str | None) -> Never: ... # Inherits from httpx.Client class OAuth1Client(_OAuth1Client): @@ -52,4 +53,4 @@ class OAuth1Client(_OAuth1Client): **kwargs, ) -> None: ... @staticmethod - def handle_error(error_type: str | None, error_description: str | None) -> NoReturn: ... + def handle_error(error_type: str | None, error_description: str | None) -> Never: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/httpx_client/oauth2_client.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/httpx_client/oauth2_client.pyi index 9493842b5378..2fc9facabeb5 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/httpx_client/oauth2_client.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/httpx_client/oauth2_client.pyi @@ -1,6 +1,7 @@ from _typeshed import Incomplete from collections.abc import Generator -from typing import NoReturn, TypeAlias +from typing import TypeAlias +from typing_extensions import Never from authlib.oauth2.auth import ClientAuth, TokenAuth from authlib.oauth2.client import OAuth2Client as _OAuth2Client @@ -66,6 +67,6 @@ class OAuth2Client(_OAuth2Client): **kwargs, ) -> None: ... @staticmethod - def handle_error(error_type: str | None, error_description: str | None) -> NoReturn: ... + def handle_error(error_type: str | None, error_description: str | None) -> Never: ... def request(self, method, url, withhold_token: bool = False, auth=..., **kwargs): ... def stream(self, method, url, withhold_token: bool = False, auth=..., **kwargs): ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/requests_client/oauth1_session.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/requests_client/oauth1_session.pyi index deead135e951..d197f07f7e9e 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/requests_client/oauth1_session.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/requests_client/oauth1_session.pyi @@ -1,4 +1,4 @@ -from typing import NoReturn +from typing_extensions import Never from authlib.oauth1 import ClientAuth from authlib.oauth1.client import OAuth1Client @@ -26,4 +26,4 @@ class OAuth1Session(OAuth1Client): ) -> None: ... def rebuild_auth(self, prepared_request, response) -> None: ... @staticmethod - def handle_error(error_type: str | None, error_description: str | None) -> NoReturn: ... + def handle_error(error_type: str | None, error_description: str | None) -> Never: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/starlette_client/apps.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/starlette_client/apps.pyi index c5118f638285..47b6267c4430 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/integrations/starlette_client/apps.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/integrations/starlette_client/apps.pyi @@ -1,11 +1,16 @@ +from _typeshed import Incomplete +from typing import TypeAlias + from ..base_client import BaseApp from ..base_client.async_app import AsyncOAuth1Mixin, AsyncOAuth2Mixin from ..base_client.async_openid import AsyncOpenIDMixin from ..httpx_client import AsyncOAuth1Client, AsyncOAuth2Client +_RedirectResponse: TypeAlias = Incomplete # actual type is starlette.responses.RedirectResponse + class StarletteAppMixin: async def save_authorize_data(self, request, **kwargs) -> None: ... - async def authorize_redirect(self, request, redirect_uri=None, **kwargs): ... + async def authorize_redirect(self, request, redirect_uri=None, **kwargs) -> _RedirectResponse: ... class StarletteOAuth1App(StarletteAppMixin, AsyncOAuth1Mixin, BaseApp): client_cls = AsyncOAuth1Client @@ -13,4 +18,16 @@ class StarletteOAuth1App(StarletteAppMixin, AsyncOAuth1Mixin, BaseApp): class StarletteOAuth2App(StarletteAppMixin, AsyncOAuth2Mixin, AsyncOpenIDMixin, BaseApp): client_cls = AsyncOAuth2Client + async def logout_redirect( + self, + request, + post_logout_redirect_uri=None, + id_token_hint=None, + *, + state=None, + client_id=None, + logout_hint=None, + ui_locales=None, + ) -> _RedirectResponse: ... + async def validate_logout_response(self, request): ... async def authorize_access_token(self, request, **kwargs): ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/jose/rfc7519/claims.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/jose/rfc7519/claims.pyi index 060f627c483c..55ec2dbf9a73 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/jose/rfc7519/claims.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/jose/rfc7519/claims.pyi @@ -12,11 +12,11 @@ class BaseClaims(dict[str, Any]): # dict values are key-dependent def get_registered_claims(self) -> dict[str, Incomplete]: ... class JWTClaims(BaseClaims): - def validate(self, now=None, leeway: int = 0) -> None: ... + def validate(self, now: int | None = None, leeway: int = 0) -> None: ... def validate_iss(self) -> None: ... def validate_sub(self) -> None: ... def validate_aud(self) -> None: ... - def validate_exp(self, now, leeway) -> None: ... - def validate_nbf(self, now, leeway) -> None: ... - def validate_iat(self, now, leeway) -> None: ... + def validate_exp(self, now: int, leeway: int) -> None: ... + def validate_nbf(self, now: int, leeway: int) -> None: ... + def validate_iat(self, now: int, leeway: int) -> None: ... def validate_jti(self) -> None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth1/client.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth1/client.pyi index 25a169c46bf5..07b0221f9c15 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth1/client.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth1/client.pyi @@ -1,5 +1,6 @@ from _typeshed import Incomplete -from typing import Any, NoReturn +from typing import Any +from typing_extensions import Never from authlib.oauth1 import ClientAuth @@ -40,5 +41,5 @@ class OAuth1Client: def parse_authorization_response(self, url: str) -> dict[str, str]: ... def parse_response_token(self, status_code: int, text: str): ... @staticmethod - def handle_error(error_type: str, error_description: str) -> NoReturn: ... + def handle_error(error_type: str, error_description: str) -> Never: ... def __del__(self) -> None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/claims.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/claims.pyi new file mode 100644 index 000000000000..899113298ca0 --- /dev/null +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/claims.pyi @@ -0,0 +1,31 @@ +from _typeshed import Incomplete +from collections.abc import Callable +from typing import TypedDict + +class ClaimsOption(TypedDict, total=False): + essential: bool + allow_blank: bool | None + value: str | int | bool + values: list[str | int | bool] | list[str] | list[int] | list[bool] + validate: Callable[[BaseClaims, Incomplete], bool] + +class BaseClaims(dict[str, Incomplete]): + registry_cls: Incomplete + REGISTERED_CLAIMS: list[str] + header: dict[str, Incomplete] + options: dict[str, ClaimsOption] + params: dict[str, Incomplete] + def __init__( + self, + claims: dict[str, Incomplete], + header: dict[str, Incomplete], + options: dict[str, ClaimsOption] | None = None, + params: dict[str, Incomplete] | None = None, + ) -> None: ... + def get_registered_claims(self) -> dict[str, Incomplete]: ... + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... + +class JWTClaims(BaseClaims): + registry_cls: Incomplete + REGISTERED_CLAIMS: list[str] + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/__init__.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/__init__.pyi index 360b28566411..378c042e688b 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/__init__.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/__init__.pyi @@ -1,5 +1,6 @@ from .authenticate_client import ClientAuthentication as ClientAuthentication from .authorization_server import AuthorizationServer as AuthorizationServer +from .endpoint import Endpoint, EndpointRequest from .errors import ( AccessDeniedError as AccessDeniedError, InsecureTransportError as InsecureTransportError, @@ -69,6 +70,8 @@ __all__ = [ "AuthorizationServer", "ResourceProtector", "TokenValidator", + "Endpoint", + "EndpointRequest", "TokenEndpoint", "BaseGrant", "AuthorizationEndpointMixin", diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/authorization_server.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/authorization_server.pyi index af3561c3f6b8..932bec1278f1 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/authorization_server.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/authorization_server.pyi @@ -6,6 +6,7 @@ from authlib.oauth2 import JsonRequest, OAuth2Error, OAuth2Request from authlib.oauth2.rfc6749 import BaseGrant, ClientMixin from authlib.oauth2.rfc6750 import BearerTokenGenerator +from .endpoint import Endpoint, EndpointRequest from .hooks import Hookable _ServerResponse: TypeAlias = tuple[int, str, list[tuple[str, str]]] @@ -37,10 +38,11 @@ class AuthorizationServer(Hookable): def register_grant( self, grant_cls: type[BaseGrant], extensions: Collection[Callable[[BaseGrant], None]] | None = None ) -> None: ... - def register_endpoint(self, endpoint) -> None: ... + def register_endpoint(self, endpoint: type[Endpoint] | Endpoint) -> None: ... def get_authorization_grant(self, request: OAuth2Request) -> BaseGrant: ... def get_consent_grant(self, request=None, end_user=None): ... def get_token_grant(self, request: OAuth2Request) -> BaseGrant: ... + def validate_endpoint_request(self, name, request=None) -> EndpointRequest: ... def create_endpoint_response(self, name, request=None): ... @overload diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/endpoint.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/endpoint.pyi new file mode 100644 index 000000000000..6fb13da985f7 --- /dev/null +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/endpoint.pyi @@ -0,0 +1,19 @@ +from _typeshed import Incomplete +from dataclasses import dataclass + +from .requests import OAuth2Request + +@dataclass +class EndpointRequest: + request: OAuth2Request + client: Incomplete | None = None + +class Endpoint: + ENDPOINT_NAME: str | None + server: Incomplete + def __init__(self, server=None) -> None: ... + def create_endpoint_request(self, request): ... + def validate_request(self, request: OAuth2Request) -> EndpointRequest: ... + def create_response(self, validated_request: EndpointRequest) -> tuple[int, Incomplete, list[Incomplete]] | None: ... + def create_endpoint_response(self, request: OAuth2Request) -> tuple[int, Incomplete, list[Incomplete]] | None: ... + def __call__(self, request: OAuth2Request) -> tuple[int, Incomplete, list[Incomplete]] | None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/requests.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/requests.pyi index a08553800101..37cafb6b54c9 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/requests.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/requests.pyi @@ -70,9 +70,12 @@ class OAuth2Request(OAuth2Payload): @property @deprecated("'request.redirect_uri' is deprecated in favor of 'request.payload.redirect_uri'") def redirect_uri(self) -> str: ... + @property - @deprecated("'request.scope' is deprecated in favor of 'request.payload.scope'") def scope(self) -> str: ... + @scope.setter + def scope(self, value: str) -> None: ... + @property @deprecated("'request.state' is deprecated in favor of 'request.payload.state'") def state(self) -> str | None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/token_endpoint.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/token_endpoint.pyi index 80c20beaf52c..579acec4ab20 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/token_endpoint.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6749/token_endpoint.pyi @@ -1,13 +1,11 @@ from _typeshed import Incomplete -class TokenEndpoint: - ENDPOINT_NAME: Incomplete +from .endpoint import Endpoint + +class TokenEndpoint(Endpoint): + ENDPOINT_NAME: str | None SUPPORTED_TOKEN_TYPES: Incomplete CLIENT_AUTH_METHODS: Incomplete - server: Incomplete - def __init__(self, server) -> None: ... - def __call__(self, request): ... - def create_endpoint_request(self, request): ... def authenticate_endpoint_client(self, request): ... def authenticate_token(self, request, client): ... def create_endpoint_response(self, request): ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6750/errors.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6750/errors.pyi index 570a94f286f0..4f1576dd0ac4 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6750/errors.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc6750/errors.pyi @@ -9,8 +9,16 @@ class InvalidTokenError(OAuth2Error): description: str status_code: int realm: Incomplete - extra_attributes: Incomplete - def __init__(self, description=None, uri=None, status_code=None, state=None, realm=None, **extra_attributes) -> None: ... + extra_attributes: dict[str, Incomplete] + def __init__( + self, + description=None, + uri=None, + status_code=None, + state=None, + realm=None, + extra_attributes: dict[str, Incomplete] | None = None, + ) -> None: ... def get_headers(self) -> list[tuple[str, str]]: ... class InsufficientScopeError(OAuth2Error): diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/assertion.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/assertion.pyi index bef3fad2cb8c..e4b5986a41ee 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/assertion.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/assertion.pyi @@ -1,5 +1,27 @@ def sign_jwt_bearer_assertion( - key, issuer, audience, subject=None, issued_at=None, expires_at=None, claims=None, header=None, **kwargs -) -> bytes: ... -def client_secret_jwt_sign(client_secret, client_id, token_endpoint, alg: str = "HS256", claims=None, **kwargs) -> bytes: ... -def private_key_jwt_sign(private_key, client_id, token_endpoint, alg: str = "RS256", claims=None, **kwargs) -> bytes: ... + key, issuer, audience, subject=None, issued_at=None, expires_at=None, claims=None, header=None, *, alg=None, expires_in=3600 +) -> str: ... +def client_secret_jwt_sign( + client_secret, + client_id, + token_endpoint, + alg: str = "HS256", + claims=None, + *, + issued_at=None, + expires_at=None, + header=None, + expires_in=3600, +) -> str: ... +def private_key_jwt_sign( + private_key, + client_id, + token_endpoint, + alg: str = "RS256", + claims=None, + *, + issued_at=None, + expires_at=None, + header=None, + expires_in=3600, +) -> str: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/auth.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/auth.pyi index 95e22de2b2de..c6c88e80c984 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/auth.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/auth.pyi @@ -7,10 +7,10 @@ class ClientSecretJWT: claims: Incomplete headers: Incomplete def __init__(self, token_endpoint=None, claims=None, headers=None, alg=None) -> None: ... - def sign(self, auth, token_endpoint) -> bytes: ... + def sign(self, auth, token_endpoint) -> str: ... def __call__(self, auth, method, uri, headers, body): ... class PrivateKeyJWT(ClientSecretJWT): name: str alg: str - def sign(self, auth, token_endpoint) -> bytes: ... + def sign(self, auth, token_endpoint) -> str: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/client.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/client.pyi index f0c5895f6fc5..a58719ac613a 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/client.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/client.pyi @@ -1,7 +1,7 @@ +from _typeshed import Incomplete from logging import Logger -from typing import Final - -from authlib.jose.rfc7519.claims import JWTClaims +from typing import Final, overload +from typing_extensions import deprecated ASSERTION_TYPE: Final[str] log: Logger @@ -9,13 +9,20 @@ log: Logger class JWTBearerClientAssertion: CLIENT_ASSERTION_TYPE: Final[str] CLIENT_AUTH_METHOD: Final[str] - token_url: str + token_url: str | None leeway: int - def __init__(self, token_url: str, validate_jti: bool = True, leeway: int = 60) -> None: ... + + @overload + @deprecated("The `token_url` parameter is deprecated. Override `get_audiences` instead.") + def __init__(self, token_url: str = ..., validate_jti: bool = True, leeway: int = 60) -> None: ... + @overload + def __init__(self, token_url: None = None, validate_jti: bool = True, leeway: int = 60) -> None: ... + def __call__(self, query_client, request): ... - def create_claims_options(self): ... - def process_assertion_claims(self, assertion, resolve_key) -> JWTClaims: ... + def verify_claims(self, claims: dict[str, Incomplete]) -> None: ... + def get_audiences(self) -> list[str]: ... + def process_assertion_claims(self, assertion, resolve_key) -> dict[str, Incomplete]: ... def authenticate_client(self, client): ... - def create_resolve_key_func(self, query_client, request): ... + def extract_assertion(self, assertion: str) -> tuple[dict[str, Incomplete], Incomplete]: ... def validate_jti(self, claims, jti): ... - def resolve_client_public_key(self, client, headers): ... + def resolve_client_public_key(self, client): ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/jwt_bearer.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/jwt_bearer.pyi index ea9209205c03..d50561b210a4 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/jwt_bearer.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/jwt_bearer.pyi @@ -1,7 +1,7 @@ +from _typeshed import Incomplete from logging import Logger from typing import ClassVar, Final -from authlib.jose.rfc7519.claims import JWTClaims from authlib.oauth2.rfc6749 import BaseGrant, TokenEndpointMixin log: Logger @@ -13,11 +13,13 @@ class JWTBearerGrant(BaseGrant, TokenEndpointMixin): LEEWAY: ClassVar[int] @staticmethod def sign(key, issuer, audience, subject=None, issued_at=None, expires_at=None, claims=None, **kwargs): ... - def process_assertion_claims(self, assertion) -> JWTClaims: ... - def resolve_public_key(self, headers, payload): ... + def verify_claims(self, claims: dict[str, Incomplete]) -> None: ... + def process_assertion_claims(self, assertion) -> dict[str, Incomplete]: ... + def extract_assertion(self, assertion: str) -> tuple[dict[str, Incomplete], Incomplete]: ... def validate_token_request(self) -> None: ... def create_token_response(self): ... def resolve_issuer_client(self, issuer): ... - def resolve_client_key(self, client, headers, payload): ... + def resolve_client_public_key(self, client): ... def authenticate_user(self, subject): ... + def get_audiences(self) -> list[str]: ... def has_granted_permission(self, client, user) -> bool: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/validator.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/validator.pyi index e9f1d0c7f535..068756c77c80 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/validator.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7523/validator.pyi @@ -1,17 +1,16 @@ from _typeshed import Incomplete -from authlib.jose import JWTClaims from authlib.oauth2.rfc6749 import TokenMixin from authlib.oauth2.rfc6750 import BearerTokenValidator logger: Incomplete -class JWTBearerToken(TokenMixin, JWTClaims): - def check_client(self, client): ... +class JWTBearerToken(TokenMixin, dict[str, Incomplete]): + def check_client(self, client) -> bool: ... def get_scope(self): ... def get_expires_in(self): ... - def is_expired(self): ... - def is_revoked(self): ... + def is_expired(self) -> bool: ... + def is_revoked(self) -> bool: ... class JWTBearerTokenValidator(BearerTokenValidator): TOKEN_TYPE: str @@ -19,4 +18,4 @@ class JWTBearerTokenValidator(BearerTokenValidator): public_key: Incomplete claims_options: Incomplete def __init__(self, public_key, issuer=None, realm=None, **extra_attributes) -> None: ... - def authenticate_token(self, token_string): ... + def authenticate_token(self, token_string: str) -> JWTBearerToken | None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7591/claims.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7591/claims.pyi index e79d2fddca8f..15179250147a 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7591/claims.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7591/claims.pyi @@ -1,11 +1,11 @@ from _typeshed import Incomplete -from collections.abc import Mapping +from collections.abc import Callable, Mapping from typing import Any from authlib.jose import BaseClaims class ClientMetadataClaims(BaseClaims): - def validate(self) -> None: ... + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... def validate_redirect_uris(self) -> None: ... def validate_token_endpoint_auth_method(self) -> None: ... def validate_grant_types(self) -> None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7591/endpoint.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7591/endpoint.pyi index d3d94d4427c8..21dde441cee9 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7591/endpoint.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc7591/endpoint.pyi @@ -1,20 +1,18 @@ from _typeshed import Incomplete from typing import Final -from authlib.jose import JWTClaims - class ClientRegistrationEndpoint: ENDPOINT_NAME: Final = "client_registration" software_statement_alg_values_supported: Incomplete server: Incomplete claims_classes: list[type[Incomplete]] def __init__(self, server=None, claims_classes: list[type[Incomplete]] | None = None) -> None: ... - def __call__(self, request) -> dict[Incomplete, Incomplete]: ... - def create_registration_response(self, request): ... - def extract_client_metadata(self, request): ... - def extract_software_statement(self, software_statement, request) -> JWTClaims: ... + def __call__(self, request) -> tuple[int, dict[Incomplete, Incomplete], list[tuple[str, str]]]: ... + def create_registration_response(self, request) -> tuple[int, dict[Incomplete, Incomplete], list[tuple[str, str]]]: ... + def extract_client_metadata(self, request) -> dict[Incomplete, Incomplete]: ... + def extract_software_statement(self, software_statement, request) -> dict[str, Incomplete]: ... def generate_client_info(self, request) -> dict[str, Incomplete]: ... - def generate_client_registration_info(self, client, request) -> None: ... + def generate_client_registration_info(self, client, request) -> Incomplete | None: ... def create_endpoint_request(self, request): ... def generate_client_id(self, request) -> str: ... def generate_client_secret(self, request) -> str: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc8414/models.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc8414/models.pyi index 2c3b593ae2ca..54dec12ec5ea 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc8414/models.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc8414/models.pyi @@ -1,7 +1,7 @@ from _typeshed import Incomplete class AuthorizationServerMetadata(dict[str, object]): - REGISTRY_KEYS: Incomplete + REGISTRY_KEYS: list[str] def validate_issuer(self) -> None: ... def validate_authorization_endpoint(self) -> None: ... def validate_token_endpoint(self) -> None: ... @@ -34,7 +34,9 @@ class AuthorizationServerMetadata(dict[str, object]): def revocation_endpoint_auth_methods_supported(self): ... @property def introspection_endpoint_auth_methods_supported(self): ... - def validate(self) -> None: ... + def validate(self, metadata_classes: list[type[Incomplete]] | None = None) -> None: ... def __getattr__(self, key): ... def validate_array_value(metadata, key) -> None: ... +def validate_language_tags_array(metadata, key) -> None: ... +def validate_boolean_value(metadata, key) -> None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/claims.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/claims.pyi index e68d1ba20a90..d91f4321a212 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/claims.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/claims.pyi @@ -1,13 +1,12 @@ +from collections.abc import Callable + from authlib.jose import JWTClaims +# Inherits from joserfc.jwt.JWTClaimsRegistry +class JWTAccessTokenClaimsValidator: + def validate_auth_time(self, auth_time) -> None: ... + def validate_amr(self, amr) -> None: ... + class JWTAccessTokenClaims(JWTClaims): - def validate(self, *, now=None, leeway: int = 0) -> None: ... # type: ignore[override] - def validate_typ(self) -> None: ... - def validate_client_id(self): ... - def validate_auth_time(self) -> None: ... - def validate_acr(self): ... - def validate_amr(self) -> None: ... - def validate_scope(self): ... - def validate_groups(self): ... - def validate_roles(self): ... - def validate_entitlements(self): ... + registry_cls = JWTAccessTokenClaimsValidator + def validate(self, *, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... # type: ignore[override] diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/introspection.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/introspection.pyi index 2187442f8f87..c54599bf0a83 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/introspection.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/introspection.pyi @@ -1,13 +1,14 @@ from _typeshed import Incomplete -from authlib.oauth2.rfc7662 import IntrospectionEndpoint +from ..rfc7662 import IntrospectionEndpoint +from .claims import JWTAccessTokenClaims class JWTIntrospectionEndpoint(IntrospectionEndpoint): ENDPOINT_NAME: str issuer: Incomplete def __init__(self, issuer, server=None, *args, **kwargs) -> None: ... def create_endpoint_response(self, request): ... - def authenticate_token(self, request, client): ... - def create_introspection_payload(self, token): ... + def authenticate_token(self, request, client) -> JWTAccessTokenClaims | None: ... + def create_introspection_payload(self, token: JWTAccessTokenClaims) -> dict[str, Incomplete]: ... def get_jwks(self): ... def get_username(self, user_id: str) -> str: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/revocation.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/revocation.pyi index 13eee4f99868..befb05a1702d 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/revocation.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/revocation.pyi @@ -1,10 +1,10 @@ from _typeshed import Incomplete -from typing import NoReturn +from typing_extensions import Never from authlib.oauth2.rfc7009 import RevocationEndpoint class JWTRevocationEndpoint(RevocationEndpoint): issuer: Incomplete def __init__(self, issuer, server=None, *args, **kwargs) -> None: ... - def authenticate_token(self, request, client) -> NoReturn: ... + def authenticate_token(self, request, client) -> Never: ... def get_jwks(self): ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/token.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/token.pyi index 9f6f310ea3d8..6ef3b9c2d46d 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/token.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/token.pyi @@ -14,4 +14,4 @@ class JWTBearerTokenGenerator(BearerTokenGenerator): def get_amr(self, user) -> list[str] | None: ... def get_jti(self, client, grant_type, user, scope) -> str: ... # Override seems safe, but mypy doesn't like that it's a callabe protocol in the base - def access_token_generator(self, client, grant_type, user, scope): ... # type: ignore[override] + def access_token_generator(self, client, grant_type, user, scope) -> str: ... # type: ignore[override] diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/token_validator.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/token_validator.pyi index fe6d9f9edfb8..c893ec9349f1 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/token_validator.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9068/token_validator.pyi @@ -1,6 +1,8 @@ from _typeshed import Incomplete -from authlib.oauth2.rfc6750 import BearerTokenValidator +from authlib.oauth2.rfc6750.validator import BearerTokenValidator + +from .claims import JWTAccessTokenClaims class JWTBearerTokenValidator(BearerTokenValidator): issuer: Incomplete @@ -8,5 +10,7 @@ class JWTBearerTokenValidator(BearerTokenValidator): def __init__(self, issuer, resource_server, *args, **kwargs) -> None: ... def get_jwks(self): ... def validate_iss(self, claims, iss: str) -> bool: ... - def authenticate_token(self, token_string): ... - def validate_token(self, token, scopes, request, groups=None, roles=None, entitlements=None) -> None: ... + def authenticate_token(self, token_string) -> JWTAccessTokenClaims: ... + def validate_token( + self, token: JWTAccessTokenClaims, scopes, request, groups=None, roles=None, entitlements=None + ) -> None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9101/authorization_server.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9101/authorization_server.pyi index c889ee7b2f93..5461a00b654c 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9101/authorization_server.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9101/authorization_server.pyi @@ -4,12 +4,14 @@ from ..rfc6749 import AuthorizationServer, ClientMixin from ..rfc6749.requests import OAuth2Request class JWTAuthenticationRequest: + claims_validator: Incomplete support_request: bool support_request_uri: bool def __init__(self, support_request: bool = True, support_request_uri: bool = True) -> None: ... def __call__(self, authorization_server: AuthorizationServer) -> None: ... + def get_request_object_signing_algorithms(self, client) -> list[str]: ... def parse_authorization_request(self, authorization_server: AuthorizationServer, request: OAuth2Request) -> None: ... def get_request_object(self, request_uri: str): ... - def resolve_client_public_keys(self, client: ClientMixin): ... + def resolve_client_public_key(self, client: ClientMixin): ... def get_server_metadata(self) -> dict[str, Incomplete]: ... def get_client_require_signed_request_object(self, client: ClientMixin) -> bool: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9101/registration.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9101/registration.pyi index f4c742554cb5..66af83e065b4 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9101/registration.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9101/registration.pyi @@ -1,5 +1,7 @@ +from collections.abc import Callable + from authlib.jose import BaseClaims class ClientMetadataClaims(BaseClaims): - def validate(self) -> None: ... + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... def validate_require_signed_request_object(self) -> None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9207/__init__.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9207/__init__.pyi index f0d14fa1c1f4..559a1c9263f4 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9207/__init__.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9207/__init__.pyi @@ -1,3 +1,4 @@ +from .discovery import AuthorizationServerMetadata as AuthorizationServerMetadata from .parameter import IssuerParameter as IssuerParameter -__all__ = ["IssuerParameter"] +__all__ = ["AuthorizationServerMetadata", "IssuerParameter"] diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9207/discovery.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9207/discovery.pyi new file mode 100644 index 000000000000..654d2d31e28a --- /dev/null +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oauth2/rfc9207/discovery.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete + +class AuthorizationServerMetadata(dict[str, Incomplete]): + REGISTRY_KEYS: list[str] + def validate_authorization_response_iss_parameter_supported(self) -> None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/claims.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/claims.pyi index 2a2f9f47abc3..f9a24cfbcfa6 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/claims.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/claims.pyi @@ -1,13 +1,14 @@ +from collections.abc import Callable + from authlib.jose import JWTClaims __all__ = ["IDToken", "CodeIDToken", "ImplicitIDToken", "HybridIDToken", "UserInfo", "get_claim_cls_by_response_type"] class IDToken(JWTClaims): ESSENTIAL_CLAIMS: list[str] - def validate(self, now=None, leeway: int = 0) -> None: ... + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... def validate_auth_time(self) -> None: ... def validate_nonce(self) -> None: ... - def validate_acr(self): ... def validate_amr(self) -> None: ... def validate_azp(self) -> None: ... def validate_at_hash(self) -> None: ... @@ -28,6 +29,7 @@ class HybridIDToken(ImplicitIDToken): class UserInfo(dict[str, object]): REGISTERED_CLAIMS: list[str] SCOPES_CLAIMS_MAPPING: dict[str, list[str]] + def validate_locale(self) -> None: ... def filter(self, scope: str) -> UserInfo: ... def __getattr__(self, key): ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/grants/_legacy.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/grants/_legacy.pyi new file mode 100644 index 000000000000..ba67813c9836 --- /dev/null +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/grants/_legacy.pyi @@ -0,0 +1,11 @@ +from _typeshed import Incomplete + +from authlib.oauth2 import OAuth2Request + +class LegacyMixin: + DEFAULT_EXPIRES_IN: int + def resolve_client_private_key(self, client): ... + def get_client_algorithm(self, client): ... + def get_client_claims(self, client) -> dict[str, Incomplete]: ... + def get_encode_header(self, client) -> dict[str, Incomplete]: ... + def get_compatible_claims(self, request: OAuth2Request) -> dict[str, Incomplete]: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/grants/code.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/grants/code.pyi index 69b48d93c5fe..6c29a87897f2 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/grants/code.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/grants/code.pyi @@ -1,17 +1,20 @@ +from _typeshed import Incomplete from logging import Logger from authlib.oauth2 import OAuth2Request -from authlib.oauth2.client import OAuth2Client from authlib.oauth2.rfc6749 import BaseGrant from authlib.oidc.core import UserInfo +from ..models import AuthorizationCodeMixin +from ._legacy import LegacyMixin + log: Logger -class OpenIDToken: - def get_jwt_config(self, grant: BaseGrant, client: OAuth2Client) -> dict[str, str | int]: ... +class OpenIDToken(LegacyMixin): + def get_authorization_code_claims(self, authorization_code: AuthorizationCodeMixin) -> dict[str, Incomplete]: ... def generate_user_info(self, user, scope: str) -> UserInfo: ... - def get_audiences(self, request: OAuth2Request) -> list[str]: ... - def process_token(self, grant: BaseGrant, response) -> dict[str, str | int]: ... + def encode_id_token(self, token, request: OAuth2Request) -> str: ... + def process_token(self, grant: BaseGrant, response) -> dict[str, Incomplete]: ... def __call__(self, grant: BaseGrant) -> None: ... class OpenIDCode(OpenIDToken): diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/grants/implicit.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/grants/implicit.pyi index 73be6e936141..959a688b0e35 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/grants/implicit.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/grants/implicit.pyi @@ -1,21 +1,21 @@ from _typeshed import Incomplete from logging import Logger -from authlib.oauth2.client import OAuth2Client from authlib.oauth2.rfc6749 import ImplicitGrant from authlib.oidc.core import UserInfo +from ._legacy import LegacyMixin + log: Logger -class OpenIDImplicitGrant(ImplicitGrant): +class OpenIDImplicitGrant(LegacyMixin, ImplicitGrant): RESPONSE_TYPES: Incomplete DEFAULT_RESPONSE_MODE: str def exists_nonce(self, nonce, request) -> bool: ... - def get_jwt_config(self, client: OAuth2Client) -> dict[str, Incomplete]: ... def generate_user_info(self, user, scope) -> UserInfo: ... def get_audiences(self, request) -> list[Incomplete]: ... def validate_authorization_request(self) -> str: ... def validate_consent_request(self) -> str: ... def create_authorization_response(self, redirect_uri, grant_user): ... - def create_granted_params(self, grant_user): ... + def create_granted_params(self, grant_user) -> list[tuple[str, Incomplete]]: ... def process_implicit_token(self, token, code=None): ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/userinfo.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/userinfo.pyi index 0bec9bda3dd9..cf3bf956cba3 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/userinfo.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/core/userinfo.pyi @@ -12,7 +12,8 @@ class UserInfoEndpoint: self, server: AuthorizationServer | None = None, resource_protector: ResourceProtector | None = None ) -> None: ... def create_endpoint_request(self, request: OAuth2Request) -> OAuth2Request: ... - def __call__(self, request: OAuth2Request) -> tuple[int, dict[str, str | None], list[tuple[str, str]]]: ... + def __call__(self, request: OAuth2Request) -> tuple[int, str | UserInfo, list[tuple[str, str]]]: ... + def get_supported_algorithms(self) -> list[str]: ... def generate_user_info(self, user, scope: str) -> UserInfo: ... def get_issuer(self) -> str: ... def resolve_private_key(self): ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/registration/claims.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/registration/claims.pyi index f2dd67de8278..5327d0704d7e 100644 --- a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/registration/claims.pyi +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/registration/claims.pyi @@ -1,10 +1,10 @@ from _typeshed import Incomplete -from collections.abc import Mapping +from collections.abc import Callable, Mapping from authlib.jose import BaseClaims class ClientMetadataClaims(BaseClaims): - def validate(self) -> None: ... + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... # The "cls" argument is called "self" in the actual implementation, # but stubtest will not allow that. @classmethod diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/rpinitiated/__init__.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/rpinitiated/__init__.pyi new file mode 100644 index 000000000000..1da8effafddf --- /dev/null +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/rpinitiated/__init__.pyi @@ -0,0 +1,5 @@ +from .discovery import OpenIDProviderMetadata as OpenIDProviderMetadata +from .end_session import EndSessionEndpoint as EndSessionEndpoint, EndSessionRequest as EndSessionRequest +from .registration import ClientMetadataClaims as ClientMetadataClaims + +__all__ = ["EndSessionEndpoint", "EndSessionRequest", "ClientMetadataClaims", "OpenIDProviderMetadata"] diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/rpinitiated/discovery.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/rpinitiated/discovery.pyi new file mode 100644 index 000000000000..b492c7e6654a --- /dev/null +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/rpinitiated/discovery.pyi @@ -0,0 +1,5 @@ +from _typeshed import Incomplete + +class OpenIDProviderMetadata(dict[str, Incomplete]): + REGISTRY_KEYS: list[str] + def validate_end_session_endpoint(self) -> None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/rpinitiated/end_session.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/rpinitiated/end_session.pyi new file mode 100644 index 000000000000..85e56a5465e3 --- /dev/null +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/rpinitiated/end_session.pyi @@ -0,0 +1,26 @@ +from _typeshed import Incomplete +from dataclasses import dataclass + +from authlib.oauth2.rfc6749.endpoint import Endpoint, EndpointRequest +from authlib.oauth2.rfc6749.requests import OAuth2Request + +@dataclass +class EndSessionRequest(EndpointRequest): + id_token_claims: dict[Incomplete, Incomplete] | None = None + redirect_uri: str | None = None + logout_hint: str | None = None + ui_locales: str | None = None + @property + def needs_confirmation(self) -> bool: ... + +class EndSessionEndpoint(Endpoint): + ENDPOINT_NAME: str + def validate_request(self, request: OAuth2Request) -> EndSessionRequest: ... + def create_response(self, validated_request: EndSessionRequest) -> tuple[int, Incomplete, list[tuple[str, str]]] | None: ... # type: ignore[override] + def resolve_client_from_id_token_claims(self, id_token_claims: dict[Incomplete, Incomplete]) -> Incomplete | None: ... + def is_post_logout_redirect_uri_legitimate( + self, request: OAuth2Request, post_logout_redirect_uri: str, client, logout_hint: str | None + ) -> bool: ... + def get_server_jwks(self): ... + def get_algorithms(self) -> list[str]: ... + def end_session(self, end_session_request: EndSessionRequest) -> None: ... diff --git a/python/helpers/typeshed/stubs/Authlib/authlib/oidc/rpinitiated/registration.pyi b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/rpinitiated/registration.pyi new file mode 100644 index 000000000000..6fe844ac1df3 --- /dev/null +++ b/python/helpers/typeshed/stubs/Authlib/authlib/oidc/rpinitiated/registration.pyi @@ -0,0 +1,7 @@ +from collections.abc import Callable + +from authlib.oauth2.claims import BaseClaims + +class ClientMetadataClaims(BaseClaims): + REGISTERED_CLAIMS: list[str] + def validate(self, now: int | Callable[[], int] | None = None, leeway: int = 0) -> None: ... diff --git a/python/helpers/typeshed/stubs/JACK-Client/jack/__init__.pyi b/python/helpers/typeshed/stubs/JACK-Client/jack/__init__.pyi index c173e7be07cc..d577f8f2742d 100644 --- a/python/helpers/typeshed/stubs/JACK-Client/jack/__init__.pyi +++ b/python/helpers/typeshed/stubs/JACK-Client/jack/__init__.pyi @@ -1,7 +1,7 @@ from _typeshed import Unused from collections.abc import Callable, Generator, Iterable, Iterator, Sequence -from typing import Any, Final, Literal, NoReturn, overload, type_check_only -from typing_extensions import Self +from typing import Any, Final, Literal, overload, type_check_only +from typing_extensions import Never, Self import numpy from _cffi_backend import _CDataBase @@ -239,8 +239,8 @@ class OwnMidiPort(MidiPort, OwnPort): def __init__(self, port_ptr: _CDataBase, client: Client) -> None: ... # The implementation raises NotImplementedError, but this is not an abstract class. # `get_buffer()` and `get_array()` are disabled for OwnMidiPort - def get_buffer(self) -> NoReturn: ... - def get_array(self) -> NoReturn: ... + def get_buffer(self) -> Never: ... + def get_array(self) -> Never: ... @property def max_event_size(self) -> int: ... @property diff --git a/python/helpers/typeshed/stubs/PyMySQL/METADATA.toml b/python/helpers/typeshed/stubs/PyMySQL/METADATA.toml index 55b5654668ef..b5cd7fc2bafb 100644 --- a/python/helpers/typeshed/stubs/PyMySQL/METADATA.toml +++ b/python/helpers/typeshed/stubs/PyMySQL/METADATA.toml @@ -1,2 +1,2 @@ -version = "1.1.*" +version = "1.2.*" upstream-repository = "https://github.com/PyMySQL/PyMySQL" diff --git a/python/helpers/typeshed/stubs/PyMySQL/pymysql/connections.pyi b/python/helpers/typeshed/stubs/PyMySQL/pymysql/connections.pyi index 05cf60eaab64..f911c13600a1 100644 --- a/python/helpers/typeshed/stubs/PyMySQL/pymysql/connections.pyi +++ b/python/helpers/typeshed/stubs/PyMySQL/pymysql/connections.pyi @@ -2,7 +2,7 @@ from _typeshed import FileDescriptorOrPath, Incomplete, Unused from collections.abc import Callable, Mapping from socket import _Address, socket as _socket from ssl import SSLContext, _PasswordType -from typing import Any, AnyStr, Generic, overload +from typing import Any, AnyStr, Generic, Literal, overload from typing_extensions import Self, TypeVar, deprecated from .charset import charset_by_id as charset_by_id, charset_by_name as charset_by_name @@ -91,7 +91,7 @@ class Connection(Generic[_C]): binary_prefix: bool = False, program_name: str | None = None, server_public_key: bytes | None = None, - ssl: dict[str, Incomplete] | SSLContext | None = None, + ssl: SSLContext | None = None, # Passing a dict is deprecated ssl_ca: str | None = None, ssl_cert: str | None = None, ssl_disabled: bool | None = None, @@ -106,6 +106,53 @@ class Connection(Generic[_C]): db: None = None, # deprecated ) -> None: ... @overload + @deprecated("Passing a dict for 'ssl' parameter is deprecated. Use 'ssl_*' parameters or 'ssl.SSLContext' instead.") + def __init__( + self, + *, + user: str | bytes | None = None, + password: str | bytes = "", + host: str | None = None, + database: str | bytes | None = None, + unix_socket: _Address | None = None, + port: int = 0, + charset: str = "", + collation: str | None = None, + sql_mode: str | None = None, + read_default_file: str | None = None, + conv: dict[int | type[Any], Callable[[Any], str] | Callable[[str], Any]] | None = None, + use_unicode: bool = True, + client_flag: int = 0, + cursorclass: type[_C] = ..., + init_command: str | None = None, + connect_timeout: float = 10, + read_default_group: str | None = None, + autocommit: bool | None = False, + local_infile: bool = False, + max_allowed_packet: int = 16_777_216, + defer_connect: bool = False, + auth_plugin_map: dict[str, Callable[[Connection[Any]], Any]] | None = None, + read_timeout: float | None = None, + write_timeout: float | None = None, + bind_address: str | None = None, + binary_prefix: bool = False, + program_name: str | None = None, + server_public_key: bytes | None = None, + ssl: dict[str, Incomplete], # Passing a dict is deprecated + ssl_ca: str | None = None, + ssl_cert: str | None = None, + ssl_disabled: bool | None = None, + ssl_key: str | None = None, + ssl_key_password: _PasswordType | None = None, + ssl_verify_cert: bool | None = None, + ssl_verify_identity: bool | None = None, + compress: Unused = None, + named_pipe: Unused = None, + # different between overloads: + passwd: str | bytes | None = None, # deprecated + db: str | bytes | None = None, # deprecated + ) -> None: ... + @overload @deprecated("'passwd' and 'db' arguments are deprecated. Use 'password' and 'database' instead.") def __init__( self, @@ -138,7 +185,7 @@ class Connection(Generic[_C]): binary_prefix: bool = False, program_name: str | None = None, server_public_key: bytes | None = None, - ssl: dict[str, Incomplete] | SSLContext | None = None, + ssl: dict[str, Incomplete] | SSLContext | None = None, # Passing a dict is deprecated ssl_ca: str | None = None, ssl_cert: str | None = None, ssl_disabled: bool | None = None, @@ -176,8 +223,14 @@ class Connection(Generic[_C]): def next_result(self, unbuffered: bool = False) -> int: ... def affected_rows(self): ... def kill(self, thread_id): ... - def ping(self, reconnect: bool = True) -> None: ... - @deprecated("Method is deprecated. Use set_character_set() instead.") + + @overload + def ping(self, reconnect: Literal[False] | None = False) -> None: ... + @overload + @deprecated("The 'reconnect' parameter is deprecated. Create a new connection if you want to reconnect.") + def ping(self, reconnect: Literal[True]) -> None: ... + + @deprecated("Method is deprecated. Use 'set_character_set()' instead.") def set_charset(self, charset: str) -> None: ... def set_character_set(self, charset: str, collation: str | None = None) -> None: ... def connect(self, sock: _socket | None = None) -> None: ... diff --git a/python/helpers/typeshed/stubs/PyMySQL/pymysql/converters.pyi b/python/helpers/typeshed/stubs/PyMySQL/pymysql/converters.pyi index e7a80135d612..dcda0644fb05 100644 --- a/python/helpers/typeshed/stubs/PyMySQL/pymysql/converters.pyi +++ b/python/helpers/typeshed/stubs/PyMySQL/pymysql/converters.pyi @@ -4,15 +4,15 @@ import time from _typeshed import Unused from collections.abc import Callable, Mapping, Sequence from decimal import Decimal -from typing import Any, NoReturn, TypeAlias, TypeVar -from typing_extensions import deprecated +from typing import Any, TypeAlias, TypeVar +from typing_extensions import Never, deprecated _EscaperMapping: TypeAlias = Mapping[type[object], Callable[..., str]] | None _T = TypeVar("_T") def escape_item(val: object, charset: object, mapping: _EscaperMapping = None) -> str: ... @deprecated("dict cannot be used as parameter. It didn't produce valid SQL and might cause SQL injection.") -def escape_dict(val: Mapping[str, object], charset: object, mapping: _EscaperMapping = None) -> NoReturn: ... +def escape_dict(val: Mapping[str, object], charset: object, mapping: _EscaperMapping = None) -> Never: ... def escape_sequence(val: Sequence[object], charset: object, mapping: _EscaperMapping = None) -> str: ... def escape_set(val: set[object], charset: object, mapping: _EscaperMapping = None) -> str: ... def escape_bool(value: bool, mapping: _EscaperMapping = None) -> str: ... diff --git a/python/helpers/typeshed/stubs/PyMySQL/pymysql/err.pyi b/python/helpers/typeshed/stubs/PyMySQL/pymysql/err.pyi index da77ca9b65ec..d8a2d837761c 100644 --- a/python/helpers/typeshed/stubs/PyMySQL/pymysql/err.pyi +++ b/python/helpers/typeshed/stubs/PyMySQL/pymysql/err.pyi @@ -1,11 +1,15 @@ import builtins -from typing import NoReturn +from typing_extensions import Never from .constants import ER as ER class MySQLError(Exception): ... class Warning(builtins.Warning, MySQLError): ... -class Error(MySQLError): ... + +class Error(MySQLError): + sqlstate: str | None + def __init__(self, *args: object, sqlstate: str | None = None) -> None: ... + class InterfaceError(Error): ... class DatabaseError(Error): ... class DataError(DatabaseError): ... @@ -17,4 +21,4 @@ class NotSupportedError(DatabaseError): ... error_map: dict[int, type[DatabaseError]] -def raise_mysql_exception(data: bytes | bytearray) -> NoReturn: ... +def raise_mysql_exception(data: bytes | bytearray) -> Never: ... diff --git a/python/helpers/typeshed/stubs/PyYAML/yaml/emitter.pyi b/python/helpers/typeshed/stubs/PyYAML/yaml/emitter.pyi index 6d7f2b0e6bd0..3a19e94a31a9 100644 --- a/python/helpers/typeshed/stubs/PyYAML/yaml/emitter.pyi +++ b/python/helpers/typeshed/stubs/PyYAML/yaml/emitter.pyi @@ -1,5 +1,6 @@ from collections.abc import Callable -from typing import Any, NoReturn, Protocol, TypeVar, type_check_only +from typing import Any, Protocol, TypeVar, type_check_only +from typing_extensions import Never from yaml.error import YAMLError @@ -74,7 +75,7 @@ class Emitter: def need_events(self, count: int) -> bool: ... def increase_indent(self, flow: bool = False, indentless: bool = False) -> None: ... def expect_stream_start(self) -> None: ... - def expect_nothing(self) -> NoReturn: ... + def expect_nothing(self) -> Never: ... def expect_first_document_start(self) -> None: ... def expect_document_start(self, first: bool = False) -> None: ... def expect_document_end(self) -> None: ... diff --git a/python/helpers/typeshed/stubs/PyYAML/yaml/representer.pyi b/python/helpers/typeshed/stubs/PyYAML/yaml/representer.pyi index b0629b245ccb..ac10d892949b 100644 --- a/python/helpers/typeshed/stubs/PyYAML/yaml/representer.pyi +++ b/python/helpers/typeshed/stubs/PyYAML/yaml/representer.pyi @@ -2,8 +2,8 @@ import datetime from _typeshed import Incomplete, ReadableBuffer, SupportsItems from collections.abc import Callable, Iterable, Mapping from types import BuiltinFunctionType, FunctionType, ModuleType -from typing import Any, ClassVar, NoReturn, TypeVar -from typing_extensions import Self +from typing import Any, ClassVar, TypeVar +from typing_extensions import Never, Self from yaml.error import YAMLError as YAMLError from yaml.nodes import MappingNode as MappingNode, Node as Node, ScalarNode as ScalarNode, SequenceNode as SequenceNode @@ -50,7 +50,7 @@ class SafeRepresenter(BaseRepresenter): def represent_date(self, data: datetime.date) -> ScalarNode: ... def represent_datetime(self, data: datetime.datetime) -> ScalarNode: ... def represent_yaml_object(self, tag: str, data, cls, flow_style: bool | None = None) -> MappingNode: ... - def represent_undefined(self, data) -> NoReturn: ... + def represent_undefined(self, data) -> Never: ... class Representer(SafeRepresenter): def represent_complex(self, data: complex) -> ScalarNode: ... diff --git a/python/helpers/typeshed/stubs/boltons/METADATA.toml b/python/helpers/typeshed/stubs/boltons/METADATA.toml index 829db8486880..9c5868f7d067 100644 --- a/python/helpers/typeshed/stubs/boltons/METADATA.toml +++ b/python/helpers/typeshed/stubs/boltons/METADATA.toml @@ -1,2 +1,2 @@ -version = "25.0.*" +version = "26.1.*" upstream-repository = "https://github.com/mahmoud/boltons" diff --git a/python/helpers/typeshed/stubs/boltons/boltons/__init__.pyi b/python/helpers/typeshed/stubs/boltons/boltons/__init__.pyi index e69de29bb2d1..c5dd95466063 100644 --- a/python/helpers/typeshed/stubs/boltons/boltons/__init__.pyi +++ b/python/helpers/typeshed/stubs/boltons/boltons/__init__.pyi @@ -0,0 +1,3 @@ +from typing import Final + +__version__: Final[str] diff --git a/python/helpers/typeshed/stubs/boltons/boltons/dictutils.pyi b/python/helpers/typeshed/stubs/boltons/boltons/dictutils.pyi index 69b5a258ea61..e2a8277fca00 100644 --- a/python/helpers/typeshed/stubs/boltons/boltons/dictutils.pyi +++ b/python/helpers/typeshed/stubs/boltons/boltons/dictutils.pyi @@ -1,13 +1,14 @@ from _typeshed import SupportsKeysAndGetItem from collections.abc import Generator, ItemsView, Iterable, Iterator, KeysView, ValuesView -from typing import Any, Generic, NoReturn, TypeAlias, TypeVar, overload -from typing_extensions import Self +from typing import Any, Generic, TypeAlias, TypeVar, overload +from typing_extensions import Never, Self _KT = TypeVar("_KT") _VT = TypeVar("_VT") _T = TypeVar("_T") class OrderedMultiDict(dict[_KT, _VT]): + def __reduce__(self) -> tuple[type[Self], tuple[()], list[tuple[_KT, _VT]]]: ... def add(self, k: _KT, v: _VT) -> None: ... def addlist(self, k: _KT, v: Iterable[_VT]) -> None: ... def clear(self) -> None: ... @@ -116,13 +117,13 @@ class FrozenDict(dict[_KT, _VT]): @classmethod def fromkeys(cls, keys: Iterable[_KT], value: _VT | None = None) -> Self: ... # type: ignore[override] def updated(self, *a, **kw) -> Self: ... - def __ior__(self, *a, **kw) -> NoReturn: ... # type: ignore[misc] # noqa: Y034 # Signature conflicts with superclass - def __setitem__(self, *a, **kw) -> NoReturn: ... - def __delitem__(self, *a, **kw) -> NoReturn: ... - def update(self, *a, **kw) -> NoReturn: ... - def pop(self, *a, **kw) -> NoReturn: ... - def popitem(self, *a, **kw) -> NoReturn: ... - def setdefault(self, *a, **kw) -> NoReturn: ... - def clear(self, *a, **kw) -> NoReturn: ... + def __ior__(self, *a, **kw) -> Never: ... # type: ignore[misc] # noqa: Y034 # Signature conflicts with superclass + def __setitem__(self, *a, **kw) -> Never: ... + def __delitem__(self, *a, **kw) -> Never: ... + def update(self, *a, **kw) -> Never: ... + def pop(self, *a, **kw) -> Never: ... + def popitem(self, *a, **kw) -> Never: ... + def setdefault(self, *a, **kw) -> Never: ... + def clear(self, *a, **kw) -> Never: ... __all__ = ["MultiDict", "OMD", "OrderedMultiDict", "OneToOne", "ManyToMany", "subdict", "FrozenDict"] diff --git a/python/helpers/typeshed/stubs/boltons/boltons/easterutils.pyi b/python/helpers/typeshed/stubs/boltons/boltons/easterutils.pyi index 4ccfba3eee9a..bea7b390f909 100644 --- a/python/helpers/typeshed/stubs/boltons/boltons/easterutils.pyi +++ b/python/helpers/typeshed/stubs/boltons/boltons/easterutils.pyi @@ -1,3 +1,3 @@ -from typing import NoReturn +from typing_extensions import Never -def gobs_program() -> NoReturn: ... +def gobs_program() -> Never: ... diff --git a/python/helpers/typeshed/stubs/boltons/boltons/fileutils.pyi b/python/helpers/typeshed/stubs/boltons/boltons/fileutils.pyi index c880b762b361..8e2fb8b75b27 100644 --- a/python/helpers/typeshed/stubs/boltons/boltons/fileutils.pyi +++ b/python/helpers/typeshed/stubs/boltons/boltons/fileutils.pyi @@ -2,8 +2,8 @@ from _typeshed import BytesPath, StrOrBytesPath, StrPath from collections.abc import Callable, Generator, Iterable from os import PathLike from types import TracebackType -from typing import IO, Any, NoReturn, TypeVar, overload -from typing_extensions import Self +from typing import IO, Any, TypeVar, overload +from typing_extensions import Never, Self _StrPathT = TypeVar("_StrPathT", bound=StrPath) _BytesPathT = TypeVar("_BytesPathT", bound=BytesPath) @@ -80,7 +80,7 @@ class DummyFile: def close(self) -> None: ... def fileno(self) -> int: ... def flush(self) -> None: ... - def next(self) -> NoReturn: ... + def next(self) -> Never: ... def read(self, size: int = 0) -> str: ... def readline(self, size: int = 0) -> str: ... def readlines(self, size: int = 0) -> list[str]: ... @@ -89,7 +89,7 @@ class DummyFile: def truncate(self) -> None: ... def write(self, string: str) -> None: ... def writelines(self, list_of_strings: list[str]) -> None: ... - def __next__(self) -> NoReturn: ... + def __next__(self) -> Never: ... def __enter__(self) -> None: ... def __exit__(self, exc_type, exc_val, exc_tb) -> None: ... diff --git a/python/helpers/typeshed/stubs/boltons/boltons/funcutils.pyi b/python/helpers/typeshed/stubs/boltons/boltons/funcutils.pyi index 0102bc154b33..d9b02dc9eb2e 100644 --- a/python/helpers/typeshed/stubs/boltons/boltons/funcutils.pyi +++ b/python/helpers/typeshed/stubs/boltons/boltons/funcutils.pyi @@ -1,6 +1,10 @@ import functools -from _typeshed import Incomplete +from _typeshed import Incomplete, Unused +from collections.abc import Callable from functools import total_ordering as total_ordering +from typing import TypeVar + +_R = TypeVar("_R") NO_DEFAULT: Incomplete @@ -60,4 +64,5 @@ class FunctionBuilder: class MissingArgument(ValueError): ... class ExistingArgument(ValueError): ... -def noop(*args, **kwargs) -> None: ... +def noop(*args: Unused, **kwargs: Unused) -> None: ... +def once(func: Callable[[], _R]) -> Callable[[], _R]: ... diff --git a/python/helpers/typeshed/stubs/boltons/boltons/iterutils.pyi b/python/helpers/typeshed/stubs/boltons/boltons/iterutils.pyi index 0c16dfa66e59..cf0251567288 100644 --- a/python/helpers/typeshed/stubs/boltons/boltons/iterutils.pyi +++ b/python/helpers/typeshed/stubs/boltons/boltons/iterutils.pyi @@ -1,11 +1,15 @@ from _typeshed import Incomplete -from collections.abc import Generator +from collections.abc import Callable, Generator, Iterable +from typing import TypeVar +from typing_extensions import TypeIs -def is_iterable(obj) -> bool: ... -def is_scalar(obj) -> bool: ... -def is_collection(obj) -> bool: ... +_T = TypeVar("_T") + +def is_iterable(obj: Iterable[_T] | object) -> TypeIs[Iterable[_T]]: ... +def is_scalar(obj: object) -> bool: ... +def is_collection(obj: object) -> bool: ... def split(src, sep=None, maxsplit=None): ... -def split_iter(src, sep=None, maxsplit=None) -> Generator[Incomplete, None, Incomplete]: ... +def split_iter(src, sep=None, maxsplit=None) -> Generator[list[Incomplete]]: ... def lstrip(iterable, strip_value=None): ... def lstrip_iter(iterable, strip_value=None) -> Generator[Incomplete]: ... def rstrip(iterable, strip_value=None): ... @@ -13,7 +17,7 @@ def rstrip_iter(iterable, strip_value=None) -> Generator[Incomplete]: ... def strip(iterable, strip_value=None): ... def strip_iter(iterable, strip_value=None): ... def chunked(src, size, count=None, **kw): ... -def chunked_iter(src, size, **kw) -> Generator[Incomplete, None, Incomplete]: ... +def chunked_iter(src, size, **kw) -> Generator[str | bytes]: ... def chunk_ranges( input_size: int, chunk_size: int, input_offset: int = 0, overlap_size: int = 0, align: bool = False ) -> Generator[tuple[int, int]]: ... @@ -26,9 +30,9 @@ def frange(stop, start=None, step: float = 1.0): ... def backoff(start, stop, count=None, factor: float = 2.0, jitter: bool = False): ... def backoff_iter(start, stop, count=None, factor: float = 2.0, jitter: bool = False) -> Generator[Incomplete]: ... def bucketize(src, key=..., value_transform=None, key_filter=None): ... -def partition(src, key=...): ... +def partition(src, key=..., *keys: str | Callable[..., Incomplete]) -> tuple[list[Incomplete], ...]: ... def unique(src, key=None): ... -def unique_iter(src, key=None) -> Generator[Incomplete, None, Incomplete]: ... +def unique_iter(src, key=None) -> Generator[Incomplete]: ... def redundant(src, key=None, groups: bool = False): ... def one(src, default=None, key=None): ... def first(iterable, default=None, key=None): ... @@ -38,7 +42,7 @@ def same(iterable, ref=...): ... def default_visit(path, key, value): ... def default_enter(path, key, value): ... def default_exit(path, key, old_parent, new_parent, new_items): ... -def remap(root, visit=..., enter=..., exit=..., **kwargs): ... +def remap(root, visit=..., enter=..., exit=..., cache: bool = True, **kwargs): ... class PathAccessError(KeyError, IndexError, TypeError): exc: Incomplete diff --git a/python/helpers/typeshed/stubs/boltons/boltons/strutils.pyi b/python/helpers/typeshed/stubs/boltons/boltons/strutils.pyi index 450937729c74..2eae46714980 100644 --- a/python/helpers/typeshed/stubs/boltons/boltons/strutils.pyi +++ b/python/helpers/typeshed/stubs/boltons/boltons/strutils.pyi @@ -1,5 +1,5 @@ from _typeshed import ReadableBuffer -from collections.abc import Callable, Generator, Iterable, Sized +from collections.abc import Callable, Generator, Iterable, Sequence, Sized from html.parser import HTMLParser from re import Pattern from typing import Literal, overload @@ -32,8 +32,6 @@ class DeaccenterDict(dict[int, int]): def bytes2human(nbytes: int, ndigits: int = 0) -> str: ... class HTMLTextExtractor(HTMLParser): - strict: bool - convert_charrefs: bool result: list[str] def __init__(self) -> None: ... def handle_data(self, d: str) -> None: ... @@ -66,6 +64,7 @@ class MultiReplace: def multi_replace(text: str, sub_map: dict[str, str], **kwargs) -> str: ... def unwrap_text(text: str, ending: str | None = "\n\n") -> str: ... def removeprefix(text: str, prefix: str) -> str: ... +def human_readable_list(items: Sequence[str], delimiter: str = ",", conjunction: str = "and", *, oxford: bool = True) -> str: ... __all__ = [ "camel2under", @@ -100,4 +99,5 @@ __all__ = [ "multi_replace", "unwrap_text", "removeprefix", + "human_readable_list", ] diff --git a/python/helpers/typeshed/stubs/braintree/braintree/credit_card_gateway.pyi b/python/helpers/typeshed/stubs/braintree/braintree/credit_card_gateway.pyi index 7ec3fac2cb04..2661ad018aea 100644 --- a/python/helpers/typeshed/stubs/braintree/braintree/credit_card_gateway.pyi +++ b/python/helpers/typeshed/stubs/braintree/braintree/credit_card_gateway.pyi @@ -1,6 +1,6 @@ from _typeshed import Incomplete, Unused from datetime import date, datetime -from typing import NoReturn +from typing_extensions import Never from braintree.credit_card import CreditCard from braintree.error_result import ErrorResult @@ -16,7 +16,7 @@ class CreditCardGateway: def expired(self) -> ResourceCollection: ... def expiring_between(self, start_date: date | datetime, end_date: date | datetime) -> ResourceCollection: ... def find(self, credit_card_token: str) -> CreditCard: ... - def forward(self, credit_card_token: Unused, receiving_merchant_id: Unused) -> NoReturn: ... + def forward(self, credit_card_token: Unused, receiving_merchant_id: Unused) -> Never: ... def from_nonce(self, nonce: str) -> CreditCard: ... def update( self, credit_card_token: str, params: dict[str, Incomplete] | None = None diff --git a/python/helpers/typeshed/stubs/capturer/capturer.pyi b/python/helpers/typeshed/stubs/capturer/capturer.pyi index 48759b77ae76..0bd324a760ea 100644 --- a/python/helpers/typeshed/stubs/capturer/capturer.pyi +++ b/python/helpers/typeshed/stubs/capturer/capturer.pyi @@ -6,8 +6,8 @@ from multiprocessing.queues import Queue from multiprocessing.synchronize import Event from signal import Signals from types import FrameType, TracebackType -from typing import IO, Any, NoReturn -from typing_extensions import Self +from typing import IO, Any +from typing_extensions import Never, Self __version__: str aliases: dict[str, Any] @@ -28,7 +28,7 @@ class MultiProcessHelper: def stop_children(self) -> None: ... def wait_for_children(self) -> None: ... def enable_graceful_shutdown(self) -> None: ... - def raise_shutdown_request(self, signum: int, frame: FrameType | None) -> NoReturn: ... + def raise_shutdown_request(self, signum: int, frame: FrameType | None) -> Never: ... class CaptureOutput(MultiProcessHelper): chunk_size: int diff --git a/python/helpers/typeshed/stubs/convertdate/convertdate/mayan.pyi b/python/helpers/typeshed/stubs/convertdate/convertdate/mayan.pyi index fda5faaa18c7..310f04093135 100644 --- a/python/helpers/typeshed/stubs/convertdate/convertdate/mayan.pyi +++ b/python/helpers/typeshed/stubs/convertdate/convertdate/mayan.pyi @@ -1,6 +1,7 @@ from _typeshed import Unused from collections.abc import Generator -from typing import Final, Literal, NoReturn, overload +from typing import Final, Literal, overload +from typing_extensions import Never EPOCH: Final = 584282.5 HAAB: Final[list[str]] @@ -22,7 +23,7 @@ def translate_tzolkin(tz: str) -> str | None: ... def tzolkin_generator(number: int | None = None, name: str | None = None) -> Generator[tuple[int, str]]: ... def longcount_generator( baktun: int, katun: int, tun: int, uinal: int, kin: int -) -> Generator[tuple[int, int, int, int, int], None, NoReturn]: ... +) -> Generator[tuple[int, int, int, int, int], None, Never]: ... def next_haab(month: str, jd: float) -> float: ... def next_tzolkin(tzolkin: tuple[int, str], jd: float) -> float: ... def next_tzolkin_haab(tzolkin: tuple[int, str], haab: tuple[int, str], jd: float) -> float: ... diff --git a/python/helpers/typeshed/stubs/django-import-export/import_export/resources.pyi b/python/helpers/typeshed/stubs/django-import-export/import_export/resources.pyi index 1baf4cba7ac6..4f1c75dac782 100644 --- a/python/helpers/typeshed/stubs/django-import-export/import_export/resources.pyi +++ b/python/helpers/typeshed/stubs/django-import-export/import_export/resources.pyi @@ -3,8 +3,8 @@ from collections import OrderedDict from collections.abc import Iterator, Sequence from functools import partial from logging import Logger -from typing import Any, ClassVar, Generic, Literal, NoReturn, TypeAlias, TypeVar, overload -from typing_extensions import deprecated +from typing import Any, ClassVar, Generic, Literal, TypeAlias, TypeVar, overload +from typing_extensions import Never, deprecated from django.db.models import Field as DjangoField, Model, QuerySet from django.utils.safestring import SafeString @@ -104,7 +104,7 @@ class Resource(Generic[_ModelT], metaclass=DeclarativeMetaclass): def after_init_instance(self, instance: _ModelT, new: bool, row: dict[str, Any], **kwargs: Any) -> None: ... @overload - def handle_import_error(self, result: Result, error: Exception, raise_errors: Literal[True]) -> NoReturn: ... + def handle_import_error(self, result: Result, error: Exception, raise_errors: Literal[True]) -> Never: ... @overload def handle_import_error(self, result: Result, error: Exception, raise_errors: Literal[False] = False) -> None: ... diff --git a/python/helpers/typeshed/stubs/docker/@tests/stubtest_allowlist.txt b/python/helpers/typeshed/stubs/docker/@tests/stubtest_allowlist.txt index 437de1b4009f..224425773c24 100644 --- a/python/helpers/typeshed/stubs/docker/@tests/stubtest_allowlist.txt +++ b/python/helpers/typeshed/stubs/docker/@tests/stubtest_allowlist.txt @@ -6,10 +6,8 @@ docker.transport.sshconn # model is always set by child classes docker.models.resource.Collection.model -# keyword arguments are now unsupported -docker.api.container.ContainerApiMixin.start - # implementation has *args and **kwargs params that can't be used +docker.api.container.ContainerApiMixin.start docker.client.DockerClient.info docker.client.DockerClient.ping diff --git a/python/helpers/typeshed/stubs/docker/docker/api/config.pyi b/python/helpers/typeshed/stubs/docker/docker/api/config.pyi index 209a0762c53c..df2a281ee813 100644 --- a/python/helpers/typeshed/stubs/docker/docker/api/config.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/api/config.pyi @@ -1,5 +1,13 @@ +from _typeshed import Incomplete + class ConfigApiMixin: - def create_config(self, name, data, labels=None, templating=None): ... + def create_config( + self, + name: str, + data: bytes, + labels: dict[Incomplete, Incomplete] | None = None, + templating: dict[Incomplete, Incomplete] | None = None, + ): ... def inspect_config(self, id): ... def remove_config(self, id): ... def configs(self, filters=None): ... diff --git a/python/helpers/typeshed/stubs/docker/docker/api/container.pyi b/python/helpers/typeshed/stubs/docker/docker/api/container.pyi index 5fb0a48c87bb..09322cad2948 100644 --- a/python/helpers/typeshed/stubs/docker/docker/api/container.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/api/container.pyi @@ -1,12 +1,22 @@ import datetime from _typeshed import Incomplete +from collections.abc import Iterable, Mapping from typing import Any, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import NotRequired -from docker._types import WaitContainerResponse +from docker._types import ContainerWeightDevice, WaitContainerResponse +from docker.types.containers import DeviceRequest, LogConfig, Ulimit from docker.types.daemon import CancellableStream +from docker.types.healthcheck import Healthcheck +from docker.types.services import Mount from ..types import ContainerConfig, EndpointConfig, HostConfig, NetworkingConfig +@type_check_only +class _RestartPolicy(TypedDict): + MaximumRetryCount: NotRequired[int] + Name: NotRequired[Literal["always", "on-failure"]] + @type_check_only class _HasId(TypedDict): Id: str @@ -121,11 +131,116 @@ class ContainerApiMixin: use_config_proxy: bool = True, platform: str | None = None, ): ... - def create_container_config(self, *args, **kwargs) -> ContainerConfig: ... + # Please keep in sync with docker.types.ContainerConfig + def create_container_config( + self, + image: str, + command: str | list[str], + hostname: str | None = None, + user: str | int | None = None, + detach: bool = False, + stdin_open: bool = False, + tty: bool = False, + # list is invariant, enumerating all possible union combination would be too complex for: + # list[str | int | tuple[int | str, str] | tuple[int | str, ...]] + ports: dict[str, dict[str, str]] | list[Any] | None = None, + environment: dict[str, str] | list[str] | None = None, + volumes: str | list[str] | None = None, + network_disabled: bool = False, + entrypoint: str | list[str] | None = None, + working_dir: str | None = None, + domainname: str | None = None, + host_config: HostConfig | None = None, + mac_address: str | None = None, + labels: dict[str, str] | list[str] | None = None, + stop_signal: str | None = None, + networking_config: NetworkingConfig | None = None, + healthcheck: Healthcheck | None = None, + stop_timeout: int | None = None, + runtime: str | None = None, + ) -> ContainerConfig: ... def create_container_from_config(self, config, name=None, platform=None): ... - def create_host_config(self, *args, **kwargs) -> HostConfig: ... - def create_networking_config(self, *args, **kwargs) -> NetworkingConfig: ... - def create_endpoint_config(self, *args, **kwargs) -> EndpointConfig: ... + # Please keep in sync with docker.types.HostConfig + def create_host_config( + self, + binds: dict[str, Mapping[str, str]] | list[str] | None = None, + port_bindings: Mapping[int | str, Any] | None = None, # Any: int, str, tuple, dict, or list + lxc_conf: dict[str, str] | list[dict[str, str]] | None = None, + publish_all_ports: bool = False, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + privileged: bool = False, + dns: list[str] | None = None, + dns_search: list[str] | None = None, + volumes_from: list[str] | None = None, + network_mode: str | None = None, + restart_policy: Mapping[str, str | int] | None = None, + cap_add: list[str] | None = None, + cap_drop: list[str] | None = None, + devices: list[str] | None = None, + extra_hosts: dict[str, str] | list[str] | None = None, + read_only: bool | None = None, + pid_mode: str | None = None, + ipc_mode: str | None = None, + security_opt: list[str] | None = None, + ulimits: list[Ulimit] | None = None, + log_config: LogConfig | None = None, + mem_limit: str | int | None = None, + memswap_limit: str | int | None = None, + mem_reservation: str | int | None = None, + kernel_memory: str | int | None = None, + mem_swappiness: int | None = None, + cgroup_parent: str | None = None, + group_add: Iterable[str | int] | None = None, + cpu_quota: int | None = None, + cpu_period: int | None = None, + blkio_weight: int | None = None, + blkio_weight_device: list[ContainerWeightDevice] | None = None, + device_read_bps: list[Mapping[str, str | int]] | None = None, + device_write_bps: list[Mapping[str, str | int]] | None = None, + device_read_iops: list[Mapping[str, str | int]] | None = None, + device_write_iops: list[Mapping[str, str | int]] | None = None, + oom_kill_disable: bool = False, + shm_size: str | int | None = None, + sysctls: dict[str, str] | None = None, + tmpfs: dict[str, str] | None = None, + oom_score_adj: int | None = None, + dns_opt: list[str] | None = None, + cpu_shares: int | None = None, + cpuset_cpus: str | None = None, + userns_mode: str | None = None, + uts_mode: str | None = None, + pids_limit: int | None = None, + isolation: str | None = None, + auto_remove: bool = False, + storage_opt: dict[str, str] | None = None, + init: bool | None = None, + init_path: str | None = None, + volume_driver: str | None = None, + cpu_count: int | None = None, + cpu_percent: int | None = None, + nano_cpus: int | None = None, + cpuset_mems: str | None = None, + runtime: str | None = None, + mounts: list[Mount] | None = None, + cpu_rt_period: int | None = None, + cpu_rt_runtime: int | None = None, + device_cgroup_rules: list[str] | None = None, + device_requests: list[DeviceRequest] | None = None, + cgroupns: Literal["private", "host"] | None = None, + ) -> HostConfig: ... + # Please keep in sync with docker.types.NetworkingConfig + def create_networking_config(self, endpoints_config: EndpointConfig | None = None) -> NetworkingConfig: ... + # Please keep in sync with docker.types.EndpointConfig + def create_endpoint_config( + self, + aliases: list[str] | None = None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + ipv4_address: str | None = None, + ipv6_address: str | None = None, + link_local_ips: list[str] | None = None, + driver_opt: dict[str, str] | None = None, + mac_address: str | None = None, + ) -> EndpointConfig: ... def diff(self, container: _Container) -> list[dict[Incomplete, Incomplete]]: ... def export(self, container: _Container, chunk_size: int | None = 2097152): ... def get_archive( @@ -201,7 +316,7 @@ class ContainerApiMixin: mem_reservation: float | str | None = None, memswap_limit: int | str | None = None, kernel_memory: int | str | None = None, - restart_policy=None, + restart_policy: _RestartPolicy | None = None, ): ... def wait( self, diff --git a/python/helpers/typeshed/stubs/docker/docker/api/image.pyi b/python/helpers/typeshed/stubs/docker/docker/api/image.pyi index 4137ee8883ca..565ed904d273 100644 --- a/python/helpers/typeshed/stubs/docker/docker/api/image.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/api/image.pyi @@ -38,6 +38,6 @@ class ImageApiMixin: def push(self, repository: str, tag: str | None = None, stream: bool = False, auth_config=None, decode: bool = False): ... def remove_image(self, image: str, force: bool = False, noprune: bool = False): ... def search(self, term: str, limit: int | None = None): ... - def tag(self, image, repository, tag: str | None = None, force: bool = False): ... + def tag(self, image, repository, tag: str | None = None, force: bool = False) -> bool: ... def is_file(src: str) -> bool: ... diff --git a/python/helpers/typeshed/stubs/docker/docker/api/network.pyi b/python/helpers/typeshed/stubs/docker/docker/api/network.pyi index 8443762babe2..c6a8cf6b434e 100644 --- a/python/helpers/typeshed/stubs/docker/docker/api/network.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/api/network.pyi @@ -1,3 +1,4 @@ +from _typeshed import Incomplete from collections.abc import Iterable from typing import Any, Literal, TypeAlias, TypedDict, type_check_only @@ -15,7 +16,7 @@ _Network: TypeAlias = _HasId | _HasID | str _Container: TypeAlias = _HasId | _HasID | str class NetworkApiMixin: - def networks(self, names=None, ids=None, filters=None): ... + def networks(self, names: list[Incomplete] | None = None, ids: list[Incomplete] | None = None, filters=None): ... def create_network( self, name: str, diff --git a/python/helpers/typeshed/stubs/docker/docker/client.pyi b/python/helpers/typeshed/stubs/docker/docker/client.pyi index 4ba4bcfce905..eef6be705974 100644 --- a/python/helpers/typeshed/stubs/docker/docker/client.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/client.pyi @@ -1,6 +1,8 @@ from _typeshed import Incomplete from collections.abc import Iterable, Mapping -from typing import Any, Literal, NoReturn, Protocol, overload, type_check_only +from datetime import datetime +from typing import Any, Literal, Protocol, overload, type_check_only +from typing_extensions import Never from docker import APIClient from docker.models.configs import ConfigCollection @@ -83,13 +85,28 @@ class DockerClient: @property def volumes(self) -> VolumeCollection: ... + # Please keep in sync with docker.api.daemon.DaemonApiMixin.events @overload - def events(self, *args, decode: Literal[False] | None = None, **kwargs) -> CancellableStream[str]: ... + def events( + self, + since: datetime | int | None = None, + until: datetime | int | None = None, + filters: dict[str, Any] | None = None, + decode: Literal[False] | None = None, + ) -> CancellableStream[str]: ... @overload - def events(self, *args, decode: Literal[True] = ..., **kwargs) -> CancellableStream[dict[str, Any]]: ... + def events( + self, + since: datetime | int | None = None, + until: datetime | int | None = None, + filters: dict[str, Any] | None = None, + decode: Literal[True] = ..., + ) -> CancellableStream[dict[str, Any]]: ... def df(self) -> dict[str, Any]: ... + # Please keep in sync with docker.api.daemon.DaemonApiMixin.info def info(self) -> dict[str, Any]: ... + # Please keep in sync with docker.api.daemon.DaemonApiMixin.login def login( self, username: str, @@ -99,10 +116,12 @@ class DockerClient: reauth: bool = False, dockercfg_path: str | None = None, ) -> dict[str, Any]: ... + # Please keep in sync with docker.api.daemon.DaemonApiMixin.ping def ping(self) -> bool: ... + # Please keep in sync with docker.api.daemon.DaemonApiMixin.version def version(self, api_version: bool = True) -> dict[str, Any]: ... def close(self) -> None: ... - def __getattr__(self, name: str) -> NoReturn: ... + def __getattr__(self, name: str) -> Never: ... from_env = DockerClient.from_env from_context = DockerClient.from_context diff --git a/python/helpers/typeshed/stubs/docker/docker/errors.pyi b/python/helpers/typeshed/stubs/docker/docker/errors.pyi index da2c69053452..407f1afb13f9 100644 --- a/python/helpers/typeshed/stubs/docker/docker/errors.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/errors.pyi @@ -1,5 +1,6 @@ from collections.abc import Iterator, Mapping -from typing import Any, NoReturn +from typing import Any +from typing_extensions import Never from docker.models.containers import Container from docker.models.images import Image @@ -7,7 +8,7 @@ from requests import HTTPError, Response class DockerException(Exception): ... -def create_api_error_from_http_exception(e: HTTPError) -> NoReturn: ... +def create_api_error_from_http_exception(e: HTTPError) -> Never: ... class APIError(HTTPError, DockerException): response: Response | None @@ -54,7 +55,7 @@ class BuildError(DockerException): class ImageLoadError(DockerException): ... -def create_unexpected_kwargs_error(name, kwargs: Mapping[str, Any]) -> NoReturn: ... +def create_unexpected_kwargs_error(name, kwargs: Mapping[str, Any]) -> Never: ... class MissingContextParameter(DockerException): param: str diff --git a/python/helpers/typeshed/stubs/docker/docker/models/configs.pyi b/python/helpers/typeshed/stubs/docker/docker/models/configs.pyi index 3a973f31763e..08a8fe4e6baa 100644 --- a/python/helpers/typeshed/stubs/docker/docker/models/configs.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/models/configs.pyi @@ -1,4 +1,5 @@ -import builtins +from _typeshed import Incomplete +from builtins import list as _list from .resource import Collection, Model @@ -10,6 +11,15 @@ class Config(Model): class ConfigCollection(Collection[Config]): model: type[Config] - def create(self, **kwargs) -> Config: ... # type: ignore[override] + # Please keep in sync with docker.api.config.ConfigApiMixin.create_config + def create( # type: ignore[override] + self, + *, + name: str, + data: bytes, + labels: dict[Incomplete, Incomplete] | None = None, + templating: dict[Incomplete, Incomplete] | None = None, + ) -> Config: ... def get(self, config_id: str) -> Config: ... - def list(self, **kwargs) -> builtins.list[Config]: ... + # Please keep in sync with docker.api.config.ConfigApiMixin.configs + def list(self, *, filters=None) -> _list[Config]: ... diff --git a/python/helpers/typeshed/stubs/docker/docker/models/containers.pyi b/python/helpers/typeshed/stubs/docker/docker/models/containers.pyi index 14a9505d908b..2a89fa402d89 100644 --- a/python/helpers/typeshed/stubs/docker/docker/models/containers.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/models/containers.pyi @@ -1,12 +1,12 @@ -import builtins import datetime from _io import _BufferedReaderStream +from builtins import list as _list from collections.abc import Iterable, Iterator, Mapping from socket import SocketIO -from typing import Any, Literal, NamedTuple, TypedDict, overload, type_check_only -from typing_extensions import NotRequired +from typing import Any, Literal, NamedTuple, overload from docker._types import ContainerWeightDevice, WaitContainerResponse +from docker.api.container import _RestartPolicy, _TopResult from docker.transport.sshconn import SSHSocket from docker.types import EndpointConfig from docker.types.containers import DeviceRequest, LogConfig, Ulimit @@ -16,16 +16,6 @@ from docker.types.services import Mount from .images import Image from .resource import Collection, Model -@type_check_only -class _RestartPolicy(TypedDict): - MaximumRetryCount: NotRequired[int] - Name: NotRequired[Literal["always", "on-failure"]] - -@type_check_only -class _TopResult(TypedDict): - Titles: list[str] - Processes: list[list[str]] - class Container(Model): @property def name(self) -> str | None: ... @@ -40,6 +30,7 @@ class Container(Model): @property def ports(self) -> dict[str, list[dict[str, str]] | None]: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.attach @overload def attach( self, @@ -75,8 +66,20 @@ class Container(Model): self, *, stdout: bool = True, stderr: bool = True, stream: Literal[True], logs: bool = False, demux: Literal[True] ) -> CancellableStream[tuple[bytes | None, bytes | None]]: ... - def attach_socket(self, **kwargs) -> SocketIO | _BufferedReaderStream | SSHSocket: ... - def commit(self, repository: str | None = None, tag: str | None = None, **kwargs) -> Image: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.attach_socket + def attach_socket(self, *, params=None, ws: bool = False) -> SocketIO | _BufferedReaderStream | SSHSocket: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.commit + def commit( + self, + repository: str | None = None, + tag: str | None = None, + *, + message=None, + author=None, + pause: bool = True, + changes=None, + conf=None, + ) -> Image: ... def diff(self) -> list[dict[str, int | str]]: ... def exec_run( self, @@ -100,6 +103,7 @@ class Container(Model): ) -> tuple[Iterator[bytes], dict[str, Any] | None]: ... def kill(self, signal: str | int | None = None) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.logs @overload def logs( self, @@ -129,15 +133,24 @@ class Container(Model): def pause(self) -> None: ... def put_archive(self, path: str, data) -> bool: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.remove_container def remove(self, *, v: bool = False, link: bool = False, force: bool = False) -> None: ... def rename(self, name: str) -> None: ... def resize(self, height: int, width: int) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.restart def restart(self, *, timeout: float | None = 10) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.start def start(self) -> None: ... - def stats(self, **kwargs) -> Iterator[dict[str, Any]] | dict[str, Any]: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.stats + def stats( + self, *, decode: bool | None = None, stream: bool = True, one_shot: bool | None = None + ) -> Iterator[dict[str, Any]] | dict[str, Any]: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.stop def stop(self, *, timeout: float | None = None) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.top def top(self, *, ps_args: str | None = None) -> _TopResult: ... def unpause(self) -> None: ... + # Please keep in sync with docker.api.container.ContainerApiMixin.update_container def update( self, *, @@ -153,6 +166,7 @@ class Container(Model): kernel_memory: int | str | None = None, restart_policy: _RestartPolicy | None = None, ): ... + # Please keep in sync with docker.api.container.ContainerApiMixin.wait def wait( self, *, timeout: float | None = None, condition: Literal["not-running", "next-exit", "removed"] | None = None ) -> WaitContainerResponse: ... @@ -164,16 +178,16 @@ class ContainerCollection(Collection[Container]): def run( self, image: str | Image, - command: str | builtins.list[str] | None = None, + command: str | _list[str] | None = None, stdout: bool = True, stderr: bool = False, remove: bool = False, *, auto_remove: bool = False, - blkio_weight_device: builtins.list[ContainerWeightDevice] | None = None, + blkio_weight_device: _list[ContainerWeightDevice] | None = None, blkio_weight: int | None = None, - cap_add: builtins.list[str] | None = None, - cap_drop: builtins.list[str] | None = None, + cap_add: _list[str] | None = None, + cap_drop: _list[str] | None = None, cgroup_parent: str | None = None, cgroupns: Literal["private", "host"] | None = None, cpu_count: int | None = None, @@ -186,19 +200,19 @@ class ContainerCollection(Collection[Container]): cpuset_cpus: str | None = None, cpuset_mems: str | None = None, detach: Literal[False] = False, - device_cgroup_rules: builtins.list[str] | None = None, - device_read_bps: builtins.list[Mapping[str, str | int]] | None = None, - device_read_iops: builtins.list[Mapping[str, str | int]] | None = None, - device_write_bps: builtins.list[Mapping[str, str | int]] | None = None, - device_write_iops: builtins.list[Mapping[str, str | int]] | None = None, - devices: builtins.list[str] | None = None, - device_requests: builtins.list[DeviceRequest] | None = None, - dns: builtins.list[str] | None = None, - dns_opt: builtins.list[str] | None = None, - dns_search: builtins.list[str] | None = None, - domainname: str | builtins.list[str] | None = None, - entrypoint: str | builtins.list[str] | None = None, - environment: dict[str, str] | builtins.list[str] | None = None, + device_cgroup_rules: _list[str] | None = None, + device_read_bps: _list[Mapping[str, str | int]] | None = None, + device_read_iops: _list[Mapping[str, str | int]] | None = None, + device_write_bps: _list[Mapping[str, str | int]] | None = None, + device_write_iops: _list[Mapping[str, str | int]] | None = None, + devices: _list[str] | None = None, + device_requests: _list[DeviceRequest] | None = None, + dns: _list[str] | None = None, + dns_opt: _list[str] | None = None, + dns_search: _list[str] | None = None, + domainname: str | _list[str] | None = None, + entrypoint: str | _list[str] | None = None, + environment: dict[str, str] | _list[str] | None = None, extra_hosts: dict[str, str] | None = None, group_add: Iterable[str | int] | None = None, healthcheck: dict[str, Any] | None = None, @@ -208,7 +222,7 @@ class ContainerCollection(Collection[Container]): ipc_mode: str | None = None, isolation: str | None = None, kernel_memory: str | int | None = None, - labels: dict[str, str] | builtins.list[str] | None = None, + labels: dict[str, str] | _list[str] | None = None, links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, log_config: LogConfig | None = None, lxc_conf: dict[str, str] | None = None, @@ -217,7 +231,7 @@ class ContainerCollection(Collection[Container]): mem_reservation: str | int | None = None, mem_swappiness: int | None = None, memswap_limit: str | int | None = None, - mounts: builtins.list[Mount] | None = None, + mounts: _list[Mount] | None = None, name: str | None = None, nano_cpus: int | None = None, network: str | None = None, @@ -229,13 +243,13 @@ class ContainerCollection(Collection[Container]): pid_mode: str | None = None, pids_limit: int | None = None, platform: str | None = None, - ports: Mapping[str, int | builtins.list[int] | tuple[str, int] | None] | None = None, + ports: Mapping[str, int | _list[int] | tuple[str, int] | None] | None = None, privileged: bool = False, publish_all_ports: bool = False, read_only: bool | None = None, restart_policy: _RestartPolicy | None = None, runtime: str | None = None, - security_opt: builtins.list[str] | None = None, + security_opt: _list[str] | None = None, shm_size: str | int | None = None, stdin_open: bool = False, stop_signal: str | None = None, @@ -244,31 +258,31 @@ class ContainerCollection(Collection[Container]): sysctls: dict[str, str] | None = None, tmpfs: dict[str, str] | None = None, tty: bool = False, - ulimits: builtins.list[Ulimit] | None = None, + ulimits: _list[Ulimit] | None = None, use_config_proxy: bool | None = None, user: str | int | None = None, userns_mode: str | None = None, uts_mode: str | None = None, version: str | None = None, volume_driver: str | None = None, - volumes: dict[str, dict[str, str]] | builtins.list[str] | None = None, - volumes_from: builtins.list[str] | None = None, + volumes: dict[str, dict[str, str]] | _list[str] | None = None, + volumes_from: _list[str] | None = None, working_dir: str | None = None, ) -> bytes: ... # TODO: This should return a stream, if `stream` is True @overload def run( self, image: str | Image, - command: str | builtins.list[str] | None = None, + command: str | _list[str] | None = None, stdout: bool = True, stderr: bool = False, remove: bool = False, *, auto_remove: bool = False, - blkio_weight_device: builtins.list[ContainerWeightDevice] | None = None, + blkio_weight_device: _list[ContainerWeightDevice] | None = None, blkio_weight: int | None = None, - cap_add: builtins.list[str] | None = None, - cap_drop: builtins.list[str] | None = None, + cap_add: _list[str] | None = None, + cap_drop: _list[str] | None = None, cgroup_parent: str | None = None, cgroupns: Literal["private", "host"] | None = None, cpu_count: int | None = None, @@ -281,19 +295,19 @@ class ContainerCollection(Collection[Container]): cpuset_cpus: str | None = None, cpuset_mems: str | None = None, detach: Literal[True], - device_cgroup_rules: builtins.list[str] | None = None, - device_read_bps: builtins.list[Mapping[str, str | int]] | None = None, - device_read_iops: builtins.list[Mapping[str, str | int]] | None = None, - device_write_bps: builtins.list[Mapping[str, str | int]] | None = None, - device_write_iops: builtins.list[Mapping[str, str | int]] | None = None, - devices: builtins.list[str] | None = None, - device_requests: builtins.list[DeviceRequest] | None = None, - dns: builtins.list[str] | None = None, - dns_opt: builtins.list[str] | None = None, - dns_search: builtins.list[str] | None = None, - domainname: str | builtins.list[str] | None = None, - entrypoint: str | builtins.list[str] | None = None, - environment: dict[str, str] | builtins.list[str] | None = None, + device_cgroup_rules: _list[str] | None = None, + device_read_bps: _list[Mapping[str, str | int]] | None = None, + device_read_iops: _list[Mapping[str, str | int]] | None = None, + device_write_bps: _list[Mapping[str, str | int]] | None = None, + device_write_iops: _list[Mapping[str, str | int]] | None = None, + devices: _list[str] | None = None, + device_requests: _list[DeviceRequest] | None = None, + dns: _list[str] | None = None, + dns_opt: _list[str] | None = None, + dns_search: _list[str] | None = None, + domainname: str | _list[str] | None = None, + entrypoint: str | _list[str] | None = None, + environment: dict[str, str] | _list[str] | None = None, extra_hosts: dict[str, str] | None = None, group_add: Iterable[str | int] | None = None, healthcheck: dict[str, Any] | None = None, @@ -303,7 +317,7 @@ class ContainerCollection(Collection[Container]): ipc_mode: str | None = None, isolation: str | None = None, kernel_memory: str | int | None = None, - labels: dict[str, str] | builtins.list[str] | None = None, + labels: dict[str, str] | _list[str] | None = None, links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, log_config: LogConfig | None = None, lxc_conf: dict[str, str] | None = None, @@ -312,7 +326,7 @@ class ContainerCollection(Collection[Container]): mem_reservation: str | int | None = None, mem_swappiness: int | None = None, memswap_limit: str | int | None = None, - mounts: builtins.list[Mount] | None = None, + mounts: _list[Mount] | None = None, name: str | None = None, nano_cpus: int | None = None, network: str | None = None, @@ -324,13 +338,13 @@ class ContainerCollection(Collection[Container]): pid_mode: str | None = None, pids_limit: int | None = None, platform: str | None = None, - ports: Mapping[str, int | builtins.list[int] | tuple[str, int] | None] | None = None, + ports: Mapping[str, int | _list[int] | tuple[str, int] | None] | None = None, privileged: bool = False, publish_all_ports: bool = False, read_only: bool | None = None, restart_policy: _RestartPolicy | None = None, runtime: str | None = None, - security_opt: builtins.list[str] | None = None, + security_opt: _list[str] | None = None, shm_size: str | int | None = None, stdin_open: bool = False, stop_signal: str | None = None, @@ -339,28 +353,28 @@ class ContainerCollection(Collection[Container]): sysctls: dict[str, str] | None = None, tmpfs: dict[str, str] | None = None, tty: bool = False, - ulimits: builtins.list[Ulimit] | None = None, + ulimits: _list[Ulimit] | None = None, use_config_proxy: bool | None = None, user: str | int | None = None, userns_mode: str | None = None, uts_mode: str | None = None, version: str | None = None, volume_driver: str | None = None, - volumes: dict[str, dict[str, str]] | builtins.list[str] | None = None, - volumes_from: builtins.list[str] | None = None, + volumes: dict[str, dict[str, str]] | _list[str] | None = None, + volumes_from: _list[str] | None = None, working_dir: str | None = None, ) -> Container: ... def create( # type: ignore[override] self, image: str | Image, - command: str | builtins.list[str] | None = None, + command: str | _list[str] | None = None, *, auto_remove: bool = False, - blkio_weight_device: builtins.list[ContainerWeightDevice] | None = None, + blkio_weight_device: _list[ContainerWeightDevice] | None = None, blkio_weight: int | None = None, - cap_add: builtins.list[str] | None = None, - cap_drop: builtins.list[str] | None = None, + cap_add: _list[str] | None = None, + cap_drop: _list[str] | None = None, cgroup_parent: str | None = None, cgroupns: Literal["private", "host"] | None = None, cpu_count: int | None = None, @@ -373,19 +387,19 @@ class ContainerCollection(Collection[Container]): cpuset_cpus: str | None = None, cpuset_mems: str | None = None, detach: bool = False, - device_cgroup_rules: builtins.list[str] | None = None, - device_read_bps: builtins.list[Mapping[str, str | int]] | None = None, - device_read_iops: builtins.list[Mapping[str, str | int]] | None = None, - device_write_bps: builtins.list[Mapping[str, str | int]] | None = None, - device_write_iops: builtins.list[Mapping[str, str | int]] | None = None, - devices: builtins.list[str] | None = None, - device_requests: builtins.list[DeviceRequest] | None = None, - dns: builtins.list[str] | None = None, - dns_opt: builtins.list[str] | None = None, - dns_search: builtins.list[str] | None = None, - domainname: str | builtins.list[str] | None = None, - entrypoint: str | builtins.list[str] | None = None, - environment: dict[str, str] | builtins.list[str] | None = None, + device_cgroup_rules: _list[str] | None = None, + device_read_bps: _list[Mapping[str, str | int]] | None = None, + device_read_iops: _list[Mapping[str, str | int]] | None = None, + device_write_bps: _list[Mapping[str, str | int]] | None = None, + device_write_iops: _list[Mapping[str, str | int]] | None = None, + devices: _list[str] | None = None, + device_requests: _list[DeviceRequest] | None = None, + dns: _list[str] | None = None, + dns_opt: _list[str] | None = None, + dns_search: _list[str] | None = None, + domainname: str | _list[str] | None = None, + entrypoint: str | _list[str] | None = None, + environment: dict[str, str] | _list[str] | None = None, extra_hosts: dict[str, str] | None = None, group_add: Iterable[str | int] | None = None, healthcheck: dict[str, Any] | None = None, @@ -395,7 +409,7 @@ class ContainerCollection(Collection[Container]): ipc_mode: str | None = None, isolation: str | None = None, kernel_memory: str | int | None = None, - labels: dict[str, str] | builtins.list[str] | None = None, + labels: dict[str, str] | _list[str] | None = None, links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, log_config: LogConfig | None = None, lxc_conf: dict[str, str] | None = None, @@ -404,7 +418,7 @@ class ContainerCollection(Collection[Container]): mem_reservation: str | int | None = None, mem_swappiness: int | None = None, memswap_limit: str | int | None = None, - mounts: builtins.list[Mount] | None = None, + mounts: _list[Mount] | None = None, name: str | None = None, nano_cpus: int | None = None, network: str | None = None, @@ -416,13 +430,13 @@ class ContainerCollection(Collection[Container]): pid_mode: str | None = None, pids_limit: int | None = None, platform: str | None = None, - ports: Mapping[str, int | builtins.list[int] | tuple[str, int] | None] | None = None, + ports: Mapping[str, int | _list[int] | tuple[str, int] | None] | None = None, privileged: bool = False, publish_all_ports: bool = False, read_only: bool | None = None, restart_policy: _RestartPolicy | None = None, runtime: str | None = None, - security_opt: builtins.list[str] | None = None, + security_opt: _list[str] | None = None, shm_size: str | int | None = None, stdin_open: bool = False, stop_signal: str | None = None, @@ -431,15 +445,15 @@ class ContainerCollection(Collection[Container]): sysctls: dict[str, str] | None = None, tmpfs: dict[str, str] | None = None, tty: bool = False, - ulimits: builtins.list[Ulimit] | None = None, + ulimits: _list[Ulimit] | None = None, use_config_proxy: bool | None = None, user: str | int | None = None, userns_mode: str | None = None, uts_mode: str | None = None, version: str | None = None, volume_driver: str | None = None, - volumes: dict[str, dict[str, str]] | builtins.list[str] | None = None, - volumes_from: builtins.list[str] | None = None, + volumes: dict[str, dict[str, str]] | _list[str] | None = None, + volumes_from: _list[str] | None = None, working_dir: str | None = None, ) -> Container: ... def get(self, container_id: str) -> Container: ... @@ -447,12 +461,12 @@ class ContainerCollection(Collection[Container]): self, all: bool = False, before: str | None = None, - filters: dict[str, str | builtins.list[str] | bool] | None = None, + filters: dict[str, str | _list[str] | bool] | None = None, limit: int = -1, since: str | None = None, sparse: bool = False, ignore_removed: bool = False, - ) -> builtins.list[Container]: ... + ) -> _list[Container]: ... def prune(self, filters: dict[str, Any] | None = None) -> dict[str, Any]: ... RUN_CREATE_KWARGS: list[str] diff --git a/python/helpers/typeshed/stubs/docker/docker/models/images.pyi b/python/helpers/typeshed/stubs/docker/docker/models/images.pyi index 7f42c3fa8460..db5b7954ca3e 100644 --- a/python/helpers/typeshed/stubs/docker/docker/models/images.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/models/images.pyi @@ -1,15 +1,14 @@ -import builtins -from _typeshed import SupportsRead +from _typeshed import Incomplete, SupportsRead +from builtins import list as _list from collections.abc import Iterator from io import StringIO -from typing import IO, Any, Literal, TypeAlias, TypedDict, overload, type_check_only +from typing import IO, Any, Literal, TypedDict, overload, type_check_only from docker._types import JSON +from docker.api.build import _Filers from .resource import Collection, Model -_ImageList: TypeAlias = list[Image] # To resolve conflicts with a method called "list" - @type_check_only class _ContainerLimits(TypedDict, total=False): memory: int @@ -27,11 +26,13 @@ class Image(Model): def history(self) -> list[Any]: ... def remove(self, force: bool = False, noprune: bool = False) -> dict[str, Any]: ... def save(self, chunk_size: int = 2097152, named: str | bool = False) -> Iterator[Any]: ... - def tag(self, repository: str, tag: str | None = None, **kwargs) -> bool: ... + # Please keep in sync with docker.api.image.ImageApiMixin.tag + def tag(self, repository: str, tag: str | None = None, *, force: bool = False) -> bool: ... class RegistryData(Model): image_name: str - def __init__(self, image_name: str, *args, **kwargs) -> None: ... + # Please keep in sync with docker.models.resource.Model.__init__ + def __init__(self, image_name: str, attrs=None, client=None, collection=None) -> None: ... @property def id(self) -> str: ... @property @@ -42,13 +43,14 @@ class RegistryData(Model): class ImageCollection(Collection[Image]): model: type[Image] + # Please keep in sync with docker.api.build.BuildApiMixin.build def build( self, *, path: str | None = None, - fileobj: StringIO | IO[bytes] | None = None, tag: str | None = None, quiet: bool = False, + fileobj: StringIO | IO[bytes] | None = None, nocache: bool = False, rm: bool = False, timeout: int | None = None, @@ -57,25 +59,28 @@ class ImageCollection(Collection[Image]): pull: bool = False, forcerm: bool = False, dockerfile: str | None = None, - buildargs: dict[str, Any] | None = None, container_limits: _ContainerLimits | None = None, + decode: bool = False, + buildargs: dict[str, Any] | None = None, + gzip: bool = False, shmsize: int | None = None, labels: dict[str, Any] | None = None, # need to use list, because the type must be json serializable - cache_from: builtins.list[str] | None = None, + cache_from: _list[str] | None = None, target: str | None = None, network_mode: str | None = None, squash: bool | None = None, - extra_hosts: builtins.list[str] | dict[str, str] | None = None, + extra_hosts: _list[str] | dict[str, str] | None = None, platform: str | None = None, isolation: str | None = None, use_config_proxy: bool = True, ) -> tuple[Image, Iterator[JSON]]: ... def get(self, name: str) -> Image: ... def get_registry_data(self, name, auth_config: dict[str, Any] | None = None) -> RegistryData: ... - def list(self, name: str | None = None, all: bool = False, filters: dict[str, Any] | None = None) -> _ImageList: ... - def load(self, data: bytes | SupportsRead[bytes]) -> _ImageList: ... + def list(self, name: str | None = None, all: bool = False, filters: dict[str, Any] | None = None) -> _list[Image]: ... + def load(self, data: bytes | SupportsRead[bytes]) -> _list[Image]: ... + # Please keep in sync with docker.api.image.ImageApiMixin.pull @overload def pull( self, @@ -95,7 +100,7 @@ class ImageCollection(Collection[Image]): all_tags: Literal[True], auth_config: dict[str, Any] | None = None, platform: str | None = None, - ) -> _ImageList: ... + ) -> _list[Image]: ... @overload def pull( self, @@ -105,12 +110,18 @@ class ImageCollection(Collection[Image]): *, auth_config: dict[str, Any] | None = None, platform: str | None = None, - ) -> _ImageList: ... + ) -> _list[Image]: ... - def push(self, repository: str, tag: str | None = None, **kwargs): ... - def remove(self, *args, **kwargs) -> None: ... - def search(self, *args, **kwargs): ... + # Please keep in sync with docker.api.image.ImageApiMixin.push + def push(self, repository: str, tag: str | None = None, *, stream: bool = False, auth_config=None, decode: bool = False): ... + # Please keep in sync with docker.api.image.ImageApiMixin.remove_image + def remove(self, image: str, force: bool = False, noprune: bool = False) -> None: ... + # Please keep in sync with docker.api.image.ImageApiMixin.search + def search(self, term: str, limit: int | None = None): ... def prune(self, filters: dict[str, Any] | None = None): ... - def prune_builds(self, *args, **kwargs): ... + # Please keep in sync with docker.api.build.BuildApiMixin.prune_builds + def prune_builds( + self, filters: _Filers | None = None, keep_storage: int | None = None, all: bool | None = None + ) -> dict[str, Incomplete]: ... def normalize_platform(platform, engine_info): ... diff --git a/python/helpers/typeshed/stubs/docker/docker/models/networks.pyi b/python/helpers/typeshed/stubs/docker/docker/models/networks.pyi index 68a31333d99a..d1679aa9f397 100644 --- a/python/helpers/typeshed/stubs/docker/docker/models/networks.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/models/networks.pyi @@ -1,4 +1,6 @@ -import builtins +from _typeshed import Incomplete +from builtins import list as _list +from collections.abc import Iterable from typing import Any, Literal from docker.types import IPAMConfig @@ -11,12 +13,25 @@ class Network(Model): def name(self) -> str | None: ... @property def containers(self) -> list[Container]: ... - def connect(self, container: str | Container, *args, **kwargs) -> None: ... + # Please keep in sync with docker.api.network.NetworkApiMixin.connect_container_to_network + def connect( + self, + container: str | Container, + ipv4_address=None, + ipv6_address=None, + aliases=None, + links: dict[str, str] | dict[str, None] | dict[str, str | None] | Iterable[tuple[str, str | None]] | None = None, + link_local_ips=None, + driver_opt=None, + mac_address=None, + ) -> None: ... + # Please keep in sync with docker.api.network.NetworkApiMixin.disconnect_container_from_network def disconnect(self, container: str | Container, force: bool = False) -> None: ... def remove(self) -> None: ... class NetworkCollection(Collection[Network]): model: type[Network] + # Please keep in sync with docker.api.network.NetworkApiMixin.create_network def create( # type: ignore[override] self, name: str, @@ -31,8 +46,12 @@ class NetworkCollection(Collection[Network]): scope: Literal["local", "global", "swarm"] | None = None, ingress: bool | None = None, ) -> Network: ... - def get( + # Please keep in sync with docker.api.network.NetworkApiMixin.inspect_network + def get( # type: ignore[override] self, network_id: str, verbose: bool | None = None, scope: Literal["local", "global", "swarm"] | None = None - ) -> Network: ... # type: ignore[override] - def list(self, *args, **kwargs) -> builtins.list[Network]: ... - def prune(self, filters: dict[str, Any] | None = None) -> dict[str, Any]: ... + ) -> Network: ... + # Please keep in sync with docker.api.network.NetworkApiMixin.networks + def list( + self, names: _list[Incomplete] | None = None, ids: _list[Incomplete] | None = None, filters=None, *, greedy: bool = False + ) -> _list[Network]: ... + def prune(self, filters: dict[str, Incomplete] | None = None) -> dict[str, Any]: ... diff --git a/python/helpers/typeshed/stubs/docker/docker/models/nodes.pyi b/python/helpers/typeshed/stubs/docker/docker/models/nodes.pyi index 2292d9243142..e738c9f33bd0 100644 --- a/python/helpers/typeshed/stubs/docker/docker/models/nodes.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/models/nodes.pyi @@ -1,3 +1,6 @@ +from builtins import list as _list +from typing import Any + from .resource import Collection, Model class Node(Model): @@ -10,4 +13,5 @@ class Node(Model): class NodeCollection(Collection[Node]): model: type[Node] def get(self, node_id): ... - def list(self, *args, **kwargs): ... + # Please keep in sync with docker.api.swarm.SwarmApiMixin.nodes + def list(self, filters: dict[str, Any] | None = None) -> _list[Node]: ... # Any: filter values + Node response diff --git a/python/helpers/typeshed/stubs/docker/docker/models/plugins.pyi b/python/helpers/typeshed/stubs/docker/docker/models/plugins.pyi index 3efb68272eae..68c672edd038 100644 --- a/python/helpers/typeshed/stubs/docker/docker/models/plugins.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/models/plugins.pyi @@ -1,3 +1,4 @@ +from builtins import list as _list from collections.abc import Generator from typing import Any @@ -22,4 +23,4 @@ class PluginCollection(Collection[Plugin]): def create(self, name, plugin_data_dir, gzip: bool = False): ... # type: ignore[override] def get(self, name): ... def install(self, remote_name, local_name=None): ... - def list(self): ... + def list(self) -> _list[Plugin]: ... diff --git a/python/helpers/typeshed/stubs/docker/docker/models/resource.pyi b/python/helpers/typeshed/stubs/docker/docker/models/resource.pyi index 1d739c5fe4a1..4e22b67516ff 100644 --- a/python/helpers/typeshed/stubs/docker/docker/models/resource.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/models/resource.pyi @@ -1,6 +1,6 @@ -import builtins -from typing import Any, Generic, NoReturn, TypeVar -from typing_extensions import Self +from builtins import list as _list +from typing import Any, Generic, TypeVar +from typing_extensions import Never, Self from docker import DockerClient @@ -26,8 +26,8 @@ class Collection(Generic[_T]): model: type[_T] client: DockerClient def __init__(self, client: DockerClient | None = None) -> None: ... - def __call__(self, *args, **kwargs) -> NoReturn: ... - def list(self) -> builtins.list[_T]: ... + def __call__(self, *args, **kwargs) -> Never: ... + def list(self) -> _list[_T]: ... def get(self, key: str) -> _T: ... def create(self, attrs: Any | None = None) -> _T: ... def prepare_model(self, attrs: Model | dict[str, Any]) -> _T: ... diff --git a/python/helpers/typeshed/stubs/docker/docker/models/secrets.pyi b/python/helpers/typeshed/stubs/docker/docker/models/secrets.pyi index 802e58ffc796..b511220b6cdd 100644 --- a/python/helpers/typeshed/stubs/docker/docker/models/secrets.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/models/secrets.pyi @@ -1,3 +1,8 @@ +from _typeshed import Incomplete +from builtins import list as _list + +from docker.types import DriverConfig + from .resource import Collection, Model class Secret(Model): @@ -8,6 +13,10 @@ class Secret(Model): class SecretCollection(Collection[Secret]): model: type[Secret] - def create(self, **kwargs): ... # type: ignore[override] - def get(self, secret_id): ... - def list(self, **kwargs): ... + # Please keep in sync with docker.api.secret.SecretApiMixin.create_secret + def create( # type: ignore[override] + self, *, name: str, data: bytes, labels: dict[str, Incomplete] | None = None, driver: DriverConfig | None = None + ): ... + def get(self, secret_id: str): ... + # Please keep in sync with docker.api.secret.SecretApiMixin.secrets + def list(self, *, filters: dict[str, Incomplete] | None = None) -> _list[Secret]: ... diff --git a/python/helpers/typeshed/stubs/docker/docker/models/services.pyi b/python/helpers/typeshed/stubs/docker/docker/models/services.pyi index 62e3d7c4d1f0..1dc00693427e 100644 --- a/python/helpers/typeshed/stubs/docker/docker/models/services.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/models/services.pyi @@ -1,3 +1,5 @@ +from builtins import list as _list + from .resource import Collection, Model class Service(Model): @@ -9,15 +11,27 @@ class Service(Model): def remove(self): ... def tasks(self, filters=None): ... def update(self, **kwargs): ... - def logs(self, **kwargs): ... - def scale(self, replicas): ... + # Please keep in sync with docker.api.service.ServiceApiMixin.service_logs + def logs( + self, + *, + details: bool = False, + follow: bool = False, + stdout: bool = False, + stderr: bool = False, + since: int = 0, + timestamps: bool = False, + tail: str = "all", + ): ... + def scale(self, replicas: int | None): ... def force_update(self): ... class ServiceCollection(Collection[Service]): model: type[Service] def create(self, image, command=None, **kwargs): ... # type: ignore[override] def get(self, service_id, insert_defaults=None): ... - def list(self, **kwargs): ... + # Please keep in sync with docker.api.service.ServiceApiMixin.services + def list(self, *, filters=None, status=None) -> _list[Service]: ... CONTAINER_SPEC_KWARGS: list[str] TASK_TEMPLATE_KWARGS: list[str] diff --git a/python/helpers/typeshed/stubs/docker/docker/models/swarm.pyi b/python/helpers/typeshed/stubs/docker/docker/models/swarm.pyi index 6238c6c96e57..f8a5dd9f9934 100644 --- a/python/helpers/typeshed/stubs/docker/docker/models/swarm.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/models/swarm.pyi @@ -1,11 +1,13 @@ from collections.abc import Iterable from typing import Any +from docker.types.services import DriverConfig +from docker.types.swarm import SwarmExternalCA + from .resource import Model class Swarm(Model): id_attribute: str - def __init__(self, *args, **kwargs) -> None: ... @property def version(self) -> str | None: ... def get_unlock_key(self) -> dict[str, Any]: ... @@ -18,10 +20,36 @@ class Swarm(Model): subnet_size: int | None = None, data_path_addr: str | None = None, data_path_port: int | None = None, - **kwargs, + *, # Please keep in sync with docker.api.swarm.SwarmApiMixin.create_swarm_spec + task_history_retention_limit: int | None = None, + snapshot_interval: int | None = None, + keep_old_snapshots: int | None = None, + log_entries_for_slow_followers: int | None = None, + heartbeat_tick: int | None = None, + election_tick: int | None = None, + dispatcher_heartbeat_period: int | None = None, + node_cert_expiry: int | None = None, + external_ca: SwarmExternalCA | None = None, + external_cas: list[SwarmExternalCA] | None = None, + name: str | None = None, + labels: dict[str, str] | None = None, + signing_ca_cert: str | None = None, + signing_ca_key: str | None = None, + ca_force_rotate: int | None = None, + autolock_managers: bool | None = None, + log_driver: DriverConfig | None = None, ) -> str: ... - def join(self, *args, **kwargs) -> bool: ... - def leave(self, *args, **kwargs) -> bool: ... + # Please keep in sync with docker.api.swarm.SwarmApiMixin.join_swarm + def join( + self, + remote_addrs: list[str], + join_token: str, + listen_addr: str = "0.0.0.0:2377", + advertise_addr: str | None = None, + data_path_addr: str | None = None, + ) -> bool: ... + # Please keep in sync with docker.api.swarm.SwarmApiMixin.leave_swarm + def leave(self, force: bool = False) -> bool: ... def reload(self) -> None: ... def unlock(self, key: str) -> bool: ... def update( @@ -29,5 +57,22 @@ class Swarm(Model): rotate_worker_token: bool = False, rotate_manager_token: bool = False, rotate_manager_unlock_key: bool = False, - **kwargs, + *, # Please keep in sync with docker.api.swarm.SwarmApiMixin.create_swarm_spec + task_history_retention_limit: int | None = None, + snapshot_interval: int | None = None, + keep_old_snapshots: int | None = None, + log_entries_for_slow_followers: int | None = None, + heartbeat_tick: int | None = None, + election_tick: int | None = None, + dispatcher_heartbeat_period: int | None = None, + node_cert_expiry: int | None = None, + external_ca: SwarmExternalCA | None = None, + external_cas: list[SwarmExternalCA] | None = None, + name: str | None = None, + labels: dict[str, str] | None = None, + signing_ca_cert: str | None = None, + signing_ca_key: str | None = None, + ca_force_rotate: int | None = None, + autolock_managers: bool | None = None, + log_driver: DriverConfig | None = None, ) -> bool: ... diff --git a/python/helpers/typeshed/stubs/docker/docker/models/volumes.pyi b/python/helpers/typeshed/stubs/docker/docker/models/volumes.pyi index 2226dc844130..b33cfb30557c 100644 --- a/python/helpers/typeshed/stubs/docker/docker/models/volumes.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/models/volumes.pyi @@ -1,4 +1,4 @@ -import builtins +from builtins import list as _list from typing import Any from .resource import Collection, Model @@ -11,7 +11,16 @@ class Volume(Model): class VolumeCollection(Collection[Volume]): model: type[Volume] - def create(self, name: str | None = None, **kwargs) -> Volume: ... # type: ignore[override] + # Please keep in sync with docker.api.volume.VolumeApiMixin.create_volume + def create( # type: ignore[override] + self, + name: str | None = None, + *, + driver: str | None = None, + driver_opts: dict[str, Any] | None = None, + labels: dict[str, Any] | None = None, + ) -> Volume: ... def get(self, volume_id: str) -> Volume: ... - def list(self, **kwargs) -> builtins.list[Volume]: ... + # Please keep in sync with docker.api.volume.VolumeApiMixin.create_volume + def list(self, *, filters: dict[str, Any] | None = None) -> _list[Volume]: ... def prune(self, filters: dict[str, Any] | None = None) -> dict[str, Any]: ... diff --git a/python/helpers/typeshed/stubs/docker/docker/transport/npipesocket.pyi b/python/helpers/typeshed/stubs/docker/docker/transport/npipesocket.pyi index e7cc2538c8e3..f68d4785b082 100644 --- a/python/helpers/typeshed/stubs/docker/docker/transport/npipesocket.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/transport/npipesocket.pyi @@ -1,6 +1,7 @@ import io from _typeshed import ReadableBuffer -from typing import Any, Literal, NoReturn, TypeAlias +from typing import Any, Literal, TypeAlias +from typing_extensions import Never cERROR_PIPE_BUSY: int cSECURITY_SQOS_PRESENT: int @@ -24,11 +25,11 @@ class NpipeSocket: def getpeername(self) -> str: ... def getsockname(self) -> str: ... # NotImplementedError - def getsockopt(self, level, optname, buflen=None) -> NoReturn: ... + def getsockopt(self, level, optname, buflen=None) -> Never: ... # NotImplementedError - def ioctl(self, control, option) -> NoReturn: ... + def ioctl(self, control, option) -> Never: ... # NotImplementedError - def listen(self, backlog) -> NoReturn: ... + def listen(self, backlog) -> Never: ... def makefile(self, mode: str | None = None, bufsize: int | None = None) -> io.BufferedReader: ... def recv(self, bufsize: int, flags: int = 0) -> str: ... def recvfrom(self, bufsize: int, flags: int = 0) -> tuple[str, str]: ... @@ -41,7 +42,7 @@ class NpipeSocket: def settimeout(self, value: float | None) -> None: ... def gettimeout(self) -> int | None: ... # NotImplementedError - def setsockopt(self, level, optname, value) -> NoReturn: ... + def setsockopt(self, level, optname, value) -> Never: ... def shutdown(self, how) -> None: ... class NpipeFileIOBase(io.RawIOBase): diff --git a/python/helpers/typeshed/stubs/docker/docker/types/containers.pyi b/python/helpers/typeshed/stubs/docker/docker/types/containers.pyi index 0c9c177e30b5..98b38ffc069e 100644 --- a/python/helpers/typeshed/stubs/docker/docker/types/containers.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/types/containers.pyi @@ -20,9 +20,7 @@ class LogConfigTypesEnum: class LogConfig(DictType[Any]): types: builtins.type[LogConfigTypesEnum] - def __init__( - self, *, type: str = ..., Type: str = ..., config: dict[str, str] = ..., Config: dict[str, str] = ... - ) -> None: ... + def __init__(self, *, type: str = ..., Type: str = ..., config: dict[str, str] = {}, Config: dict[str, str] = {}) -> None: ... @property def type(self) -> str: ... diff --git a/python/helpers/typeshed/stubs/docker/docker/types/healthcheck.pyi b/python/helpers/typeshed/stubs/docker/docker/types/healthcheck.pyi index 25d3a25439ed..c113c3fb2b28 100644 --- a/python/helpers/typeshed/stubs/docker/docker/types/healthcheck.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/types/healthcheck.pyi @@ -6,16 +6,16 @@ class Healthcheck(DictType[Any]): def __init__( self, *, - test: str | list[str] | None = ..., - Test: str | list[str] | None = ..., - interval: int | None = ..., - Interval: int | None = ..., - timeout: int | None = ..., - Timeout: int | None = ..., - retries: int | None = ..., - Retries: int | None = ..., - start_period: int | None = ..., - StartPeriod: int | None = ..., + test: str | list[str] | None = None, + Test: str | list[str] | None = None, + interval: int | None = None, + Interval: int | None = None, + timeout: int | None = None, + Timeout: int | None = None, + retries: int | None = None, + Retries: int | None = None, + start_period: int | None = None, + StartPeriod: int | None = None, ) -> None: ... @property diff --git a/python/helpers/typeshed/stubs/docker/docker/utils/utils.pyi b/python/helpers/typeshed/stubs/docker/docker/utils/utils.pyi index 406a48aa8ba5..7b248df23535 100644 --- a/python/helpers/typeshed/stubs/docker/docker/utils/utils.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/utils/utils.pyi @@ -1,9 +1,9 @@ import datetime -from _typeshed import FileDescriptorOrPath, ReadableBuffer +from _typeshed import FileDescriptorOrPath, ReadableBuffer, Unused from collections.abc import Iterable, Mapping from shlex import _ShlexInstream -from typing import Literal, NamedTuple, NoReturn, TypedDict, TypeVar, overload, type_check_only -from typing_extensions import deprecated +from typing import Literal, NamedTuple, TypedDict, TypeVar, overload, type_check_only +from typing_extensions import Never, deprecated from ..tls import TLSConfig @@ -25,9 +25,9 @@ class URLComponents(NamedTuple): fragment: str | None @deprecated("utils.create_ipam_pool has been removed. Please use a docker.types.IPAMPool object instead.") -def create_ipam_pool(*args, **kwargs) -> NoReturn: ... +def create_ipam_pool(*args: Unused, **kwargs: Unused) -> Never: ... @deprecated("utils.create_ipam_config has been removed. Please use a docker.types.IPAMConfig object instead.") -def create_ipam_config(*args, **kwargs) -> NoReturn: ... +def create_ipam_config(*args: Unused, **kwargs: Unused) -> Never: ... def decode_json_header(header: str | ReadableBuffer): ... def compare_version(v1: str, v2: str) -> Literal[0, -1, 1]: ... def version_lt(v1: str, v2: str) -> bool: ... @@ -75,4 +75,4 @@ def format_extra_hosts( extra_hosts: Mapping[object, object], task: bool = False # keys and values are converted to str ) -> list[str]: ... @deprecated("utils.create_host_config has been removed. Please use a docker.types.HostConfig object instead.") -def create_host_config(self, *args, **kwargs) -> NoReturn: ... +def create_host_config(self, *args: Unused, **kwargs: Unused) -> Never: ... diff --git a/python/helpers/typeshed/stubs/docker/docker/version.pyi b/python/helpers/typeshed/stubs/docker/docker/version.pyi index bda5b5a7f4cc..c5dd95466063 100644 --- a/python/helpers/typeshed/stubs/docker/docker/version.pyi +++ b/python/helpers/typeshed/stubs/docker/docker/version.pyi @@ -1 +1,3 @@ -__version__: str +from typing import Final + +__version__: Final[str] diff --git a/python/helpers/typeshed/stubs/docutils/docutils/parsers/rst/states.pyi b/python/helpers/typeshed/stubs/docutils/docutils/parsers/rst/states.pyi index d6f7ad79dae4..d148d2521222 100644 --- a/python/helpers/typeshed/stubs/docutils/docutils/parsers/rst/states.pyi +++ b/python/helpers/typeshed/stubs/docutils/docutils/parsers/rst/states.pyi @@ -2,7 +2,8 @@ from _typeshed import Incomplete from collections.abc import Callable, Iterable, Sequence from re import Match, Pattern from types import ModuleType, SimpleNamespace as Struct -from typing import Any, ClassVar, Final, NoReturn, TypeAlias +from typing import Any, ClassVar, Final, TypeAlias +from typing_extensions import Never from docutils import ApplicationError, DataError, nodes from docutils.nodes import Node, system_message @@ -249,7 +250,7 @@ class RFC2822Body(Body): class SpecializedBody(Body): def invalid_input( self, match: Match[str] | None = None, context: list[str] | None = None, next_state: str | None = None - ) -> NoReturn: ... + ) -> Never: ... indent = invalid_input # type: ignore[assignment] bullet = invalid_input enumerator = invalid_input @@ -345,7 +346,7 @@ class SpecializedText(Text): def eof(self, context): ... def invalid_input( self, match: Match[str] | None = None, context: list[str] | None = None, next_state: str | None = None - ) -> NoReturn: ... + ) -> Never: ... blank = invalid_input indent = invalid_input underline = invalid_input @@ -377,7 +378,7 @@ class QuotedLiteralBlock(RSTState): def __init__(self, state_machine, debug: bool = False) -> None: ... def blank(self, match, context, next_state): ... def eof(self, context): ... - def indent(self, match: Match[str] | None, context: list[str], next_state: str | None) -> NoReturn: ... + def indent(self, match: Match[str] | None, context: list[str], next_state: str | None) -> Never: ... def initial_quoted( self, match: Match[str], context: list[str] | None, next_state: str | None ) -> tuple[list[str], str | None, list[str]]: ... diff --git a/python/helpers/typeshed/stubs/docutils/docutils/transforms/parts.pyi b/python/helpers/typeshed/stubs/docutils/docutils/transforms/parts.pyi index 219f64d7876a..39aa9e2aa8df 100644 --- a/python/helpers/typeshed/stubs/docutils/docutils/transforms/parts.pyi +++ b/python/helpers/typeshed/stubs/docutils/docutils/transforms/parts.pyi @@ -1,6 +1,7 @@ from _typeshed import Incomplete, Unused from collections.abc import Iterable, Sequence -from typing import ClassVar, Final, NoReturn +from typing import ClassVar, Final +from typing_extensions import Never from docutils import nodes from docutils.transforms import Transform @@ -28,7 +29,7 @@ class Contents(Transform): class ContentsFilter(nodes.TreeCopyVisitor): def get_entry_text(self) -> Sequence[nodes.Node]: ... - def ignore_node_but_process_children(self, node: Unused) -> NoReturn: ... + def ignore_node_but_process_children(self, node: Unused) -> Never: ... visit_problematic = ignore_node_but_process_children visit_reference = ignore_node_but_process_children visit_target = ignore_node_but_process_children diff --git a/python/helpers/typeshed/stubs/docutils/docutils/writers/_html_base.pyi b/python/helpers/typeshed/stubs/docutils/docutils/writers/_html_base.pyi index 9169869aa1a8..dccf180e85ce 100644 --- a/python/helpers/typeshed/stubs/docutils/docutils/writers/_html_base.pyi +++ b/python/helpers/typeshed/stubs/docutils/docutils/writers/_html_base.pyi @@ -1,7 +1,8 @@ from _typeshed import Incomplete, StrPath from collections.abc import Callable from re import Pattern -from typing import ClassVar, Final, NoReturn +from typing import ClassVar, Final +from typing_extensions import Never from docutils import nodes, writers from docutils.frontend import Values @@ -269,7 +270,7 @@ class HTMLTranslator(nodes.NodeVisitor): def depart_transition(self, node: nodes.transition) -> None: ... def visit_version(self, node: nodes.version) -> None: ... def depart_version(self, node: nodes.version) -> None: ... - def unimplemented_visit(self, node: nodes.Node) -> NoReturn: ... + def unimplemented_visit(self, node: nodes.Node) -> Never: ... class SimpleListChecker(nodes.GenericNodeVisitor): def visit_list_item(self, node: nodes.list_item) -> None: ... diff --git a/python/helpers/typeshed/stubs/docutils/docutils/writers/latex2e/__init__.pyi b/python/helpers/typeshed/stubs/docutils/docutils/writers/latex2e/__init__.pyi index 8879d2068d18..5b75055a0140 100644 --- a/python/helpers/typeshed/stubs/docutils/docutils/writers/latex2e/__init__.pyi +++ b/python/helpers/typeshed/stubs/docutils/docutils/writers/latex2e/__init__.pyi @@ -3,8 +3,8 @@ from _typeshed import Incomplete, StrPath from collections.abc import Callable, Iterable from io import TextIOWrapper from pathlib import Path -from typing import ClassVar, Final, Literal, NoReturn, TypeVar, overload -from typing_extensions import deprecated +from typing import ClassVar, Final, Literal, TypeVar, overload +from typing_extensions import Never, deprecated from docutils import nodes from docutils.frontend import Values @@ -420,4 +420,4 @@ class LaTeXTranslator(nodes.NodeVisitor): def depart_transition(self, node: nodes.transition) -> None: ... def visit_version(self, node: nodes.version) -> None: ... def depart_version(self, node: nodes.version) -> None: ... - def unimplemented_visit(self, node: nodes.Node) -> NoReturn: ... + def unimplemented_visit(self, node: nodes.Node) -> Never: ... diff --git a/python/helpers/typeshed/stubs/docutils/docutils/writers/manpage.pyi b/python/helpers/typeshed/stubs/docutils/docutils/writers/manpage.pyi index 6eb88a13c497..9b9606008bb3 100644 --- a/python/helpers/typeshed/stubs/docutils/docutils/writers/manpage.pyi +++ b/python/helpers/typeshed/stubs/docutils/docutils/writers/manpage.pyi @@ -1,7 +1,8 @@ import re from _typeshed import Incomplete from collections.abc import Callable -from typing import ClassVar, Final, NoReturn, Protocol, type_check_only +from typing import ClassVar, Final, Protocol, type_check_only +from typing_extensions import Never from docutils import nodes, writers from docutils.frontend import Values @@ -249,4 +250,4 @@ class Translator(nodes.NodeVisitor): def visit_version(self, node: nodes.version) -> None: ... def visit_warning(self, node: nodes.warning) -> None: ... def depart_warning(self, node: nodes.warning) -> None: ... - def unimplemented_visit(self, node: nodes.Node) -> NoReturn: ... + def unimplemented_visit(self, node: nodes.Node) -> Never: ... diff --git a/python/helpers/typeshed/stubs/ephem/ephem/__init__.pyi b/python/helpers/typeshed/stubs/ephem/ephem/__init__.pyi index a62d0f68dd4c..477799ef2be7 100644 --- a/python/helpers/typeshed/stubs/ephem/ephem/__init__.pyi +++ b/python/helpers/typeshed/stubs/ephem/ephem/__init__.pyi @@ -1,7 +1,7 @@ from collections.abc import Callable from datetime import datetime as _datetime, timedelta as _timedelta, tzinfo as _tzinfo -from typing import Final, NoReturn, overload -from typing_extensions import Self +from typing import Final, overload +from typing_extensions import Never, Self from . import _libastro @@ -226,7 +226,7 @@ def localtime(date: Date | float) -> _datetime: ... class _UTC(_tzinfo): ZERO: _timedelta - def tzname(self, dt: _datetime | None, /) -> NoReturn: ... + def tzname(self, dt: _datetime | None, /) -> Never: ... def utcoffset(self, dt: _datetime | None) -> _timedelta: ... def dst(self, dt: _datetime | None) -> _timedelta: ... diff --git a/python/helpers/typeshed/stubs/ephem/ephem/_libastro.pyi b/python/helpers/typeshed/stubs/ephem/ephem/_libastro.pyi index 1501df7a3b4d..1d21f7e04c70 100644 --- a/python/helpers/typeshed/stubs/ephem/ephem/_libastro.pyi +++ b/python/helpers/typeshed/stubs/ephem/ephem/_libastro.pyi @@ -1,8 +1,8 @@ import builtins from _typeshed import Unused from datetime import datetime as _datetime -from typing import Final, NoReturn, TypeAlias, TypedDict, overload, type_check_only -from typing_extensions import Self, deprecated, disjoint_base +from typing import Final, TypeAlias, TypedDict, overload, type_check_only +from typing_extensions import Never, Self, deprecated, disjoint_base _DateInitType: TypeAlias = ( Date @@ -66,7 +66,7 @@ sun_radius: Final[float] @disjoint_base class Angle(float): # type: ignore[type-var] - def __new__(cls, *args: Unused, **kwargs: Unused) -> NoReturn: ... + def __new__(cls, *args: Unused, **kwargs: Unused) -> Never: ... @property def norm(self) -> Angle: ... @property diff --git a/python/helpers/typeshed/stubs/et_xmlfile/et_xmlfile/xmlfile.pyi b/python/helpers/typeshed/stubs/et_xmlfile/et_xmlfile/xmlfile.pyi index 9e1f55e25689..ffa96d78670c 100644 --- a/python/helpers/typeshed/stubs/et_xmlfile/et_xmlfile/xmlfile.pyi +++ b/python/helpers/typeshed/stubs/et_xmlfile/et_xmlfile/xmlfile.pyi @@ -1,8 +1,7 @@ import types import xml.etree.ElementTree as ET -from _typeshed import Incomplete -from collections.abc import Generator -from contextlib import contextmanager +from collections.abc import Callable, Generator +from contextlib import _GeneratorContextManager, contextmanager from typing import Any class LxmlSyntaxError(Exception): ... @@ -10,7 +9,7 @@ class LxmlSyntaxError(Exception): ... class _IncrementalFileWriter: global_nsmap: dict[str, str] is_html: bool - def __init__(self, output_file: ET._FileWrite) -> None: ... + def __init__(self, output_file: Callable[[str], object]) -> None: ... @contextmanager def element( self, @@ -27,7 +26,7 @@ class _IncrementalFileWriter: class xmlfile: encoding: str - writer_cm: Incomplete + writer_cm: _GeneratorContextManager[tuple[Callable[[str], object], str]] | None def __init__( self, output_file: ET._FileWrite, buffered: bool = False, encoding: str = "utf-8", close: bool = False ) -> None: ... diff --git a/python/helpers/typeshed/stubs/fpdf2/fpdf/deprecation.pyi b/python/helpers/typeshed/stubs/fpdf2/fpdf/deprecation.pyi index a1399a56191a..7766bb38ab4c 100644 --- a/python/helpers/typeshed/stubs/fpdf2/fpdf/deprecation.pyi +++ b/python/helpers/typeshed/stubs/fpdf2/fpdf/deprecation.pyi @@ -1,10 +1,11 @@ from types import ModuleType -from typing import Any, NoReturn +from typing import Any +from typing_extensions import Never def support_deprecated_txt_arg(fn): ... class WarnOnDeprecatedModuleAttributes(ModuleType): - def __call__(self) -> NoReturn: ... + def __call__(self) -> Never: ... def __getattr__(self, name: str) -> Any: ... def __setattr__(self, name: str, value: Any) -> None: ... diff --git a/python/helpers/typeshed/stubs/geopandas/geopandas/array.pyi b/python/helpers/typeshed/stubs/geopandas/geopandas/array.pyi index 51cf935bd881..3c6a469b7802 100644 --- a/python/helpers/typeshed/stubs/geopandas/geopandas/array.pyi +++ b/python/helpers/typeshed/stubs/geopandas/geopandas/array.pyi @@ -1,8 +1,8 @@ import builtins from _typeshed import Incomplete, Unused from collections.abc import Callable, Collection -from typing import Any, ClassVar, Final, Literal, NoReturn, SupportsIndex, TypeAlias, TypeVar, overload -from typing_extensions import Self, deprecated +from typing import Any, ClassVar, Final, Literal, SupportsIndex, TypeAlias, TypeVar, overload +from typing_extensions import Never, Self, deprecated import numpy as np import pandas as pd @@ -245,8 +245,8 @@ class GeometryArray(ExtensionArray): @property def nbytes(self) -> int: ... def shift(self, periods: int = 1, fill_value: Geometry | None = None) -> GeometryArray: ... # type: ignore[override] - def argmin(self, skipna: bool = True) -> NoReturn: ... - def argmax(self, skipna: bool = True) -> NoReturn: ... + def argmin(self, skipna: bool = True) -> Never: ... + def argmax(self, skipna: bool = True) -> Never: ... def __array__(self, dtype: DTypeLike | None = None, copy: bool | None = None) -> _Array1D[np.object_]: ... def __eq__(self, other: object) -> _Array1D[np.bool_]: ... # type: ignore[override] def __ne__(self, other: object) -> _Array1D[np.bool_]: ... # type: ignore[override] diff --git a/python/helpers/typeshed/stubs/gevent/METADATA.toml b/python/helpers/typeshed/stubs/gevent/METADATA.toml index 387862ea0505..30de564b477e 100644 --- a/python/helpers/typeshed/stubs/gevent/METADATA.toml +++ b/python/helpers/typeshed/stubs/gevent/METADATA.toml @@ -1,4 +1,4 @@ -version = "26.5.*" +version = "26.7.*" upstream-repository = "https://github.com/gevent/gevent" dependencies = ["types-greenlet", "types-psutil>=7.2.0"] diff --git a/python/helpers/typeshed/stubs/gevent/gevent/_config.pyi b/python/helpers/typeshed/stubs/gevent/gevent/_config.pyi index bf5cd4f17c60..7015d9f4252f 100644 --- a/python/helpers/typeshed/stubs/gevent/gevent/_config.pyi +++ b/python/helpers/typeshed/stubs/gevent/gevent/_config.pyi @@ -1,5 +1,6 @@ from collections.abc import Callable, Sequence -from typing import Any, Generic, NoReturn, Protocol, TypeVar, overload, type_check_only +from typing import Any, Generic, Protocol, TypeVar, overload, type_check_only +from typing_extensions import Never from gevent._types import _Loop, _Resolver from gevent.fileobject import _FileObjectType @@ -21,7 +22,7 @@ class _SettingDescriptor(Protocol[_T]): class SettingType(type): def fmt_desc(cls, desc: str) -> str: ... -def validate_invalid(value: object) -> NoReturn: ... +def validate_invalid(value: object) -> Never: ... def validate_bool(value: str | bool) -> bool: ... def validate_anything(value: _T) -> _T: ... diff --git a/python/helpers/typeshed/stubs/gevent/gevent/_greenlet_primitives.pyi b/python/helpers/typeshed/stubs/gevent/gevent/_greenlet_primitives.pyi index 39c9dda40a22..60356ed148d6 100644 --- a/python/helpers/typeshed/stubs/gevent/gevent/_greenlet_primitives.pyi +++ b/python/helpers/typeshed/stubs/gevent/gevent/_greenlet_primitives.pyi @@ -1,6 +1,6 @@ from abc import abstractmethod -from typing import Any, NoReturn -from typing_extensions import disjoint_base +from typing import Any +from typing_extensions import Never, disjoint_base from gevent._types import _Loop from greenlet import greenlet @@ -16,6 +16,6 @@ class SwitchOutGreenletWithLoop(TrackedRawGreenlet): def loop(self, value: _Loop) -> None: ... def switch(self) -> Any: ... - def switch_out(self) -> NoReturn: ... + def switch_out(self) -> Never: ... __all__ = ["TrackedRawGreenlet", "SwitchOutGreenletWithLoop"] diff --git a/python/helpers/typeshed/stubs/google-cloud-ndb/google/cloud/ndb/model.pyi b/python/helpers/typeshed/stubs/google-cloud-ndb/google/cloud/ndb/model.pyi index 6a35eaf49d13..54233f0ab42e 100644 --- a/python/helpers/typeshed/stubs/google-cloud-ndb/google/cloud/ndb/model.pyi +++ b/python/helpers/typeshed/stubs/google-cloud-ndb/google/cloud/ndb/model.pyi @@ -1,8 +1,8 @@ import datetime from _typeshed import Unused from collections.abc import Callable, Iterable, Sequence -from typing import Any, Literal, NoReturn, TypeAlias -from typing_extensions import Self +from typing import Any, Literal, TypeAlias +from typing_extensions import Never, Self from google.cloud.ndb import exceptions, key as key_module, query as query_module, tasklets as tasklets_module @@ -58,10 +58,10 @@ class IndexState(_NotEqualMixin): def __hash__(self) -> int: ... class ModelAdapter: - # This actually returns NoReturn, but mypy can't handle that + # This actually returns Never, but mypy can't handle that def __new__(cls, *args, **kwargs) -> Self: ... -def make_connection(*args, **kwargs) -> NoReturn: ... +def make_connection(*args, **kwargs) -> Never: ... class ModelAttribute: ... @@ -118,7 +118,7 @@ class _CompressedValue(bytes): z_val: bytes def __init__(self, z_val: bytes) -> None: ... def __eq__(self, other: object) -> bool: ... - def __hash__(self) -> NoReturn: ... + def __hash__(self) -> Never: ... class BlobProperty(Property): def __init__( @@ -257,7 +257,7 @@ class MetaModel(type): class Model(_NotEqualMixin, metaclass=MetaModel): key: ModelKey def __init__(_self, **kwargs) -> None: ... - def __hash__(self) -> NoReturn: ... + def __hash__(self) -> Never: ... def __eq__(self, other: object) -> bool: ... @classmethod def gql(cls: type[Model], query_string: str, *args, **kwargs) -> query_module.Query: ... @@ -512,5 +512,5 @@ def delete_multi( force_writes: bool | None = ..., _options: object = None, ) -> list[None]: ... -def get_indexes_async(**options: Unused) -> NoReturn: ... -def get_indexes(**options: Unused) -> NoReturn: ... +def get_indexes_async(**options: Unused) -> Never: ... +def get_indexes(**options: Unused) -> Never: ... diff --git a/python/helpers/typeshed/stubs/grpcio/grpc/__init__.pyi b/python/helpers/typeshed/stubs/grpcio/grpc/__init__.pyi index 85f1af44e5a8..bd0210796ec4 100644 --- a/python/helpers/typeshed/stubs/grpcio/grpc/__init__.pyi +++ b/python/helpers/typeshed/stubs/grpcio/grpc/__init__.pyi @@ -4,8 +4,8 @@ import threading from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from concurrent import futures from types import ModuleType, TracebackType -from typing import Any, Generic, NoReturn, Protocol, TypeAlias, TypeVar, runtime_checkable, type_check_only -from typing_extensions import Self +from typing import Any, Generic, Protocol, TypeAlias, TypeVar, runtime_checkable, type_check_only +from typing_extensions import Never, Self from . import aio as aio @@ -433,9 +433,9 @@ class StreamStreamClientInterceptor(abc.ABC): class ServicerContext(RpcContext, metaclass=abc.ABCMeta): # misnamed parameter 'details', does not align with status.proto, where it is called 'message': @abc.abstractmethod - def abort(self, code: StatusCode, details: str) -> NoReturn: ... + def abort(self, code: StatusCode, details: str) -> Never: ... @abc.abstractmethod - def abort_with_status(self, status: Status) -> NoReturn: ... + def abort_with_status(self, status: Status) -> Never: ... # FIXME: The docs say "A map of strings to an iterable of bytes for each auth property". # Does that mean 'bytes' (which is iterable), or 'Iterable[bytes]'? diff --git a/python/helpers/typeshed/stubs/grpcio/grpc/aio/__init__.pyi b/python/helpers/typeshed/stubs/grpcio/grpc/aio/__init__.pyi index cb3c27ebaa58..13d347569d1b 100644 --- a/python/helpers/typeshed/stubs/grpcio/grpc/aio/__init__.pyi +++ b/python/helpers/typeshed/stubs/grpcio/grpc/aio/__init__.pyi @@ -15,8 +15,8 @@ from collections.abc import ( ) from concurrent import futures from types import TracebackType -from typing import Any, Final, Generic, Literal, NoReturn, TypeAlias, TypeVar, overload, type_check_only -from typing_extensions import Self +from typing import Any, Final, Generic, Literal, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, Self from grpc import ( CallCredentials, @@ -270,7 +270,7 @@ class _DoneCallback(Generic[_TRequest, _TResponse]): class ServicerContext(Generic[_TRequest, _TResponse], metaclass=abc.ABCMeta): @abc.abstractmethod - async def abort(self, code: StatusCode, details: str = "", trailing_metadata: _MetadataType = ()) -> NoReturn: ... + async def abort(self, code: StatusCode, details: str = "", trailing_metadata: _MetadataType = ()) -> Never: ... @abc.abstractmethod async def read(self) -> _TRequest: ... @abc.abstractmethod diff --git a/python/helpers/typeshed/stubs/gunicorn/gunicorn/asgi/parser.pyi b/python/helpers/typeshed/stubs/gunicorn/gunicorn/asgi/parser.pyi index 69606932ee00..f98f04a0f178 100644 --- a/python/helpers/typeshed/stubs/gunicorn/gunicorn/asgi/parser.pyi +++ b/python/helpers/typeshed/stubs/gunicorn/gunicorn/asgi/parser.pyi @@ -9,6 +9,22 @@ class ParseError(Exception): ... class InvalidProxyLine(ParseError): ... class InvalidProxyHeader(ParseError): ... +@type_check_only +class _ProxyProtocolInfo(TypedDict): + proxy_protocol: Literal["TCP4", "TCP6", "UDP4", "UDP6"] + client_addr: str + client_port: int + proxy_addr: str + proxy_port: int + +@type_check_only +class _ProxyProtocolInfoUnknown(TypedDict): + proxy_protocol: Literal["UNKNOWN", "LOCAL", "UNSPEC"] + client_addr: None + client_port: None + proxy_addr: None + proxy_port: None + PP_V2_SIGNATURE: Final[bytes] RFC9110_6_5_1_FORBIDDEN_TRAILER: Final[frozenset[bytes]] @@ -38,22 +54,6 @@ class UnsupportedTransferCoding(ParseError): ... class InvalidChunkSize(ParseError): ... class InvalidChunkExtension(ParseError): ... -@type_check_only -class _ProxyProtocolInfo(TypedDict): - proxy_protocol: Literal["TCP4", "TCP6", "UDP4", "UDP6"] - client_addr: str - client_port: int - proxy_addr: str - proxy_port: int - -@type_check_only -class _ProxyProtocolInfoUnknown(TypedDict): - proxy_protocol: Literal["UNKNOWN", "LOCAL", "UNSPEC"] - client_addr: None - client_port: None - proxy_addr: None - proxy_port: None - class PythonProtocol: __slots__ = ( "_on_message_begin", @@ -149,7 +149,7 @@ class CallbackRequest: content_length: int chunked: bool must_close: bool - proxy_protocol_info: dict[str, str | int | None] | None # TODO: Use TypedDict + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None def __init__(self) -> None: ... @classmethod diff --git a/python/helpers/typeshed/stubs/gunicorn/gunicorn/asgi/uwsgi.pyi b/python/helpers/typeshed/stubs/gunicorn/gunicorn/asgi/uwsgi.pyi index 651dcdd416d1..c76678bf8199 100644 --- a/python/helpers/typeshed/stubs/gunicorn/gunicorn/asgi/uwsgi.pyi +++ b/python/helpers/typeshed/stubs/gunicorn/gunicorn/asgi/uwsgi.pyi @@ -6,6 +6,7 @@ from gunicorn.config import Config from gunicorn.uwsgi.message import UWSGIRequest from .._types import _AddressType +from .parser import _ProxyProtocolInfo, _ProxyProtocolInfoUnknown class AsyncUWSGIRequest(UWSGIRequest): cfg: Config @@ -26,7 +27,7 @@ class AsyncUWSGIRequest(UWSGIRequest): uwsgi_vars: dict[str, str] modifier1: int modifier2: int - proxy_protocol_info: dict[str, str | int | None] | None # TODO: Use TypedDict + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None content_length: int chunked: bool diff --git a/python/helpers/typeshed/stubs/gunicorn/gunicorn/ctl/protocol.pyi b/python/helpers/typeshed/stubs/gunicorn/gunicorn/ctl/protocol.pyi index aa3e3ba92566..c4a8a62cee27 100644 --- a/python/helpers/typeshed/stubs/gunicorn/gunicorn/ctl/protocol.pyi +++ b/python/helpers/typeshed/stubs/gunicorn/gunicorn/ctl/protocol.pyi @@ -1,26 +1,45 @@ -from _typeshed import Incomplete from asyncio import StreamReader, StreamWriter from socket import socket -from typing import ClassVar +from typing import Any, ClassVar, Literal, TypeAlias, TypedDict, type_check_only + +@type_check_only +class _CtlRequest(TypedDict): + id: int + command: str + args: list[str] + +@type_check_only +class _CtlSuccessResponse(TypedDict): + id: int + status: Literal["ok"] + data: dict[str, Any] + +@type_check_only +class _CtlErrorResponse(TypedDict): + id: int + status: Literal["error"] + error: str + +_CtlResponse: TypeAlias = _CtlSuccessResponse | _CtlErrorResponse +_CtlMessage: TypeAlias = _CtlRequest | _CtlResponse class ProtocolError(Exception): ... class ControlProtocol: MAX_MESSAGE_SIZE: ClassVar[int] @staticmethod - def encode_message(data: dict[Incomplete, Incomplete]) -> bytes: ... + def encode_message(data: _CtlMessage) -> bytes: ... @staticmethod - def decode_message(data: bytes) -> dict[Incomplete, Incomplete]: ... + def decode_message(data: bytes) -> _CtlMessage: ... @staticmethod - def read_message(sock: socket) -> dict[Incomplete, Incomplete]: ... + def read_message(sock: socket) -> _CtlMessage: ... @staticmethod - def write_message(sock: socket, data: dict[Incomplete, Incomplete]) -> None: ... + def write_message(sock: socket, data: _CtlMessage) -> None: ... @staticmethod - async def read_message_async(reader: StreamReader) -> dict[Incomplete, Incomplete]: ... + async def read_message_async(reader: StreamReader) -> _CtlMessage: ... @staticmethod - async def write_message_async(writer: StreamWriter, data: dict[Incomplete, Incomplete]) -> None: ... + async def write_message_async(writer: StreamWriter, data: _CtlMessage) -> None: ... -# TODO: Use TypedDict for next return types -def make_request(request_id: int, command: str, args: list[str] | None = None) -> dict[str, Incomplete]: ... -def make_response(request_id: int, data: dict[Incomplete, Incomplete] | None = None) -> dict[str, Incomplete]: ... -def make_error_response(request_id: int, error: str) -> dict[str, Incomplete]: ... +def make_request(request_id: int, command: str, args: list[str] | None = None) -> _CtlRequest: ... +def make_response(request_id: int, data: dict[str, Any] | None = None) -> _CtlSuccessResponse: ... +def make_error_response(request_id: int, error: str) -> _CtlErrorResponse: ... diff --git a/python/helpers/typeshed/stubs/gunicorn/gunicorn/dirty/protocol.pyi b/python/helpers/typeshed/stubs/gunicorn/gunicorn/dirty/protocol.pyi index ce36f88dcd88..66135ae193bf 100644 --- a/python/helpers/typeshed/stubs/gunicorn/gunicorn/dirty/protocol.pyi +++ b/python/helpers/typeshed/stubs/gunicorn/gunicorn/dirty/protocol.pyi @@ -1,7 +1,10 @@ import asyncio import socket from _typeshed import Incomplete -from typing import ClassVar, Final +from typing import ClassVar, Final, Literal, TypeAlias, TypedDict, type_check_only +from typing_extensions import NotRequired + +from .errors import _DirtyErrorDict MAGIC: Final = b"GD" VERSION: Final = 0x01 @@ -39,6 +42,65 @@ HEADER_FORMAT: Final = ">2sBBIQ" HEADER_SIZE: Final[int] MAX_MESSAGE_SIZE: Final = 67108864 +@type_check_only +class _DirtyRequest(TypedDict): + type: Literal["request"] + id: int | str + app_path: str + action: str + args: list[Incomplete] + kwargs: dict[str, Incomplete] + +@type_check_only +class _DirtyResponse(TypedDict): + type: Literal["response"] + id: int | str + result: Incomplete + +@type_check_only +class _DirtyErrorResponse(TypedDict): + type: Literal["error"] + id: int | str + error: _DirtyErrorDict | dict[str, Incomplete] + +@type_check_only +class _DirtyChunkMessage(TypedDict): + type: Literal["chunk"] + id: int | str + data: Incomplete + +@type_check_only +class _DirtyEndMessage(TypedDict): + type: Literal["end"] + id: int | str + +@type_check_only +class _DirtyStashMessage(TypedDict): + type: Literal["stash"] + id: int | str + op: int + table: str + key: NotRequired[Incomplete] + value: NotRequired[Incomplete] + pattern: NotRequired[Incomplete] + +@type_check_only +class _DirtyManageMessage(TypedDict): + type: Literal["manage"] + id: int | str + op: int + count: int + +_DirtyMessage: TypeAlias = ( + _DirtyRequest + | _DirtyResponse + | _DirtyErrorResponse + | _DirtyChunkMessage + | _DirtyEndMessage + | _DirtyStashMessage + | _DirtyManageMessage +) + class BinaryProtocol: HEADER_SIZE: ClassVar[int] MAX_MESSAGE_SIZE: ClassVar[int] @@ -80,33 +142,30 @@ class BinaryProtocol: @staticmethod def decode_message(data: bytes) -> tuple[str, int, Incomplete]: ... @staticmethod - async def read_message_async(reader: asyncio.StreamReader) -> dict[str, Incomplete]: ... + async def read_message_async(reader: asyncio.StreamReader) -> _DirtyMessage: ... @staticmethod - async def write_message_async(writer: asyncio.StreamWriter, message: dict[str, Incomplete]) -> None: ... + async def write_message_async(writer: asyncio.StreamWriter, message: _DirtyMessage) -> None: ... @staticmethod def _recv_exactly(sock: socket.socket, n: int) -> bytes: ... @staticmethod - def read_message(sock: socket.socket) -> dict[str, Incomplete]: ... + def read_message(sock: socket.socket) -> _DirtyMessage: ... @staticmethod - def write_message(sock: socket.socket, message: dict[str, Incomplete]) -> None: ... + def write_message(sock: socket.socket, message: _DirtyMessage) -> None: ... @staticmethod - def _encode_from_dict(message: dict[str, Incomplete]) -> bytes: ... + def _encode_from_dict(message: _DirtyMessage) -> bytes: ... DirtyProtocol = BinaryProtocol -# TODO: Use TypedDict for results def make_request( request_id: int | str, app_path: str, action: str, args: tuple[Incomplete, ...] | None = None, kwargs: dict[str, Incomplete] | None = None, -) -> dict[str, Incomplete]: ... -def make_response(request_id: int | str, result) -> dict[str, Incomplete]: ... -def make_error_response(request_id: int | str, error) -> dict[str, Incomplete]: ... -def make_chunk_message(request_id: int | str, data) -> dict[str, Incomplete]: ... -def make_end_message(request_id: int | str) -> dict[str, Incomplete]: ... -def make_stash_message( - request_id: int | str, op: int, table: str, key=None, value=None, pattern=None -) -> dict[str, Incomplete]: ... -def make_manage_message(request_id: int | str, op: int, count: int = 1) -> dict[str, Incomplete]: ... +) -> _DirtyRequest: ... +def make_response(request_id: int | str, result) -> _DirtyResponse: ... +def make_error_response(request_id: int | str, error) -> _DirtyErrorResponse: ... +def make_chunk_message(request_id: int | str, data) -> _DirtyChunkMessage: ... +def make_end_message(request_id: int | str) -> _DirtyEndMessage: ... +def make_stash_message(request_id: int | str, op: int, table: str, key=None, value=None, pattern=None) -> _DirtyStashMessage: ... +def make_manage_message(request_id: int | str, op: int, count: int = 1) -> _DirtyManageMessage: ... diff --git a/python/helpers/typeshed/stubs/gunicorn/gunicorn/http/message.pyi b/python/helpers/typeshed/stubs/gunicorn/gunicorn/http/message.pyi index 4243ef9eb75a..4819ab116870 100644 --- a/python/helpers/typeshed/stubs/gunicorn/gunicorn/http/message.pyi +++ b/python/helpers/typeshed/stubs/gunicorn/gunicorn/http/message.pyi @@ -8,6 +8,7 @@ from gunicorn.http.body import Body from gunicorn.http.unreader import Unreader from .._types import _AddressType +from ..asgi.parser import _ProxyProtocolInfo, _ProxyProtocolInfoUnknown PP_V2_SIGNATURE: Final = b"\x0d\x0a\x0d\x0a\x00\x0d\x0a\x51\x55\x49\x54\x0a" @@ -66,7 +67,7 @@ class Request(Message): fragment: str | None limit_request_line: int req_number: int - proxy_protocol_info: dict[str, str | int | None] | None # TODO: Use TypedDict + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None def __init__(self, cfg: Config, unreader: Unreader, peer_addr: _AddressType, req_number: int = 1) -> None: ... def get_data(self, unreader: Unreader, buf: io.BytesIO, stop: bool = False) -> None: ... diff --git a/python/helpers/typeshed/stubs/gunicorn/gunicorn/http2/request.pyi b/python/helpers/typeshed/stubs/gunicorn/gunicorn/http2/request.pyi index 6f933b1c0265..b9a3a377d865 100644 --- a/python/helpers/typeshed/stubs/gunicorn/gunicorn/http2/request.pyi +++ b/python/helpers/typeshed/stubs/gunicorn/gunicorn/http2/request.pyi @@ -6,6 +6,7 @@ from gunicorn.config import Config from gunicorn.http2.stream import HTTP2Stream from .._types import _AddressType +from ..asgi.parser import _ProxyProtocolInfo, _ProxyProtocolInfoUnknown class HTTP2Body: def __init__(self, data: ReadableBuffer) -> None: ... @@ -33,7 +34,7 @@ class HTTP2Request: body: HTTP2Body must_close: bool req_number: int - proxy_protocol_info: dict[str, str | int | None] | None # TODO: Use TypedDict + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None priority_weight: int priority_depends_on: int diff --git a/python/helpers/typeshed/stubs/gunicorn/gunicorn/reloader.pyi b/python/helpers/typeshed/stubs/gunicorn/gunicorn/reloader.pyi index f6f0ff9cc92d..62371ed476e0 100644 --- a/python/helpers/typeshed/stubs/gunicorn/gunicorn/reloader.pyi +++ b/python/helpers/typeshed/stubs/gunicorn/gunicorn/reloader.pyi @@ -2,7 +2,8 @@ import sys import threading from collections.abc import Callable, Iterable from re import Pattern -from typing import Final, NoReturn, TypeAlias, TypedDict, type_check_only +from typing import Final, TypeAlias, TypedDict, type_check_only +from typing_extensions import Never COMPILED_EXT_RE: Final[Pattern[str]] @@ -33,9 +34,7 @@ if sys.platform == "linux": else: class InotifyReloader: - def __init__( - self, extra_files: Iterable[str] | None = None, callback: Callable[[str], None] | None = None - ) -> NoReturn: ... + def __init__(self, extra_files: Iterable[str] | None = None, callback: Callable[[str], None] | None = None) -> Never: ... _PreferredReloaderType: TypeAlias = type[InotifyReloader | Reloader] _ReloaderType: TypeAlias = InotifyReloader | Reloader # noqa: Y047 diff --git a/python/helpers/typeshed/stubs/gunicorn/gunicorn/util.pyi b/python/helpers/typeshed/stubs/gunicorn/gunicorn/util.pyi index 5bec0621ad15..bc71a50e5d2b 100644 --- a/python/helpers/typeshed/stubs/gunicorn/gunicorn/util.pyi +++ b/python/helpers/typeshed/stubs/gunicorn/gunicorn/util.pyi @@ -2,7 +2,8 @@ import types from _typeshed import FileDescriptorLike, FileDescriptorOrPath, StrOrBytesPath from inspect import _IntrospectableCallable, _ParameterKind from socket import socket -from typing import Any, Literal, NoReturn +from typing import Any, Literal +from typing_extensions import Never from urllib.parse import SplitResult from ._types import _AddressType, _WSGIAppType @@ -44,6 +45,6 @@ def has_fileno(obj: object) -> bool: ... def warn(msg: str) -> None: ... def make_fail_app(msg: str) -> _WSGIAppType: ... def split_request_uri(uri: str) -> SplitResult: ... -def reraise(tp: type[BaseException], value: BaseException | None, tb: types.TracebackType | None = None) -> NoReturn: ... +def reraise(tp: type[BaseException], value: BaseException | None, tb: types.TracebackType | None = None) -> Never: ... def bytes_to_str(b: bytes) -> str: ... def unquote_to_wsgi_str(string: str) -> str: ... diff --git a/python/helpers/typeshed/stubs/gunicorn/gunicorn/uwsgi/message.pyi b/python/helpers/typeshed/stubs/gunicorn/gunicorn/uwsgi/message.pyi index fbd9f318ebc7..b89c893ad508 100644 --- a/python/helpers/typeshed/stubs/gunicorn/gunicorn/uwsgi/message.pyi +++ b/python/helpers/typeshed/stubs/gunicorn/gunicorn/uwsgi/message.pyi @@ -5,6 +5,7 @@ from gunicorn.http.body import Body from gunicorn.http.unreader import Unreader from .._types import _AddressType +from ..asgi.parser import _ProxyProtocolInfo, _ProxyProtocolInfoUnknown MAX_UWSGI_VARS: Final = 1000 @@ -28,7 +29,7 @@ class UWSGIRequest: uwsgi_vars: dict[str, str] modifier1: int modifier2: int - proxy_protocol_info: dict[str, str | int | None] | None # TODO: Use TypedDict + proxy_protocol_info: _ProxyProtocolInfo | _ProxyProtocolInfoUnknown | None def __init__(self, cfg: Config, unreader: Unreader, peer_addr: _AddressType, req_number: int = 1) -> None: ... def force_close(self) -> None: ... diff --git a/python/helpers/typeshed/stubs/gunicorn/gunicorn/workers/gasgi.pyi b/python/helpers/typeshed/stubs/gunicorn/gunicorn/workers/gasgi.pyi index 368556ffab0c..564d6d375a9d 100644 --- a/python/helpers/typeshed/stubs/gunicorn/gunicorn/workers/gasgi.pyi +++ b/python/helpers/typeshed/stubs/gunicorn/gunicorn/workers/gasgi.pyi @@ -1,7 +1,7 @@ from _typeshed import Incomplete from asyncio.base_events import Server from asyncio.events import AbstractEventLoop -from typing import NoReturn +from typing_extensions import Never from gunicorn.asgi.lifespan import LifespanManager from gunicorn.config import Config @@ -28,5 +28,5 @@ class ASGIWorker(base.Worker): def handle_exit_signal(self) -> None: ... def handle_usr1_signal(self) -> None: ... def handle_winch_signal(self) -> None: ... - def handle_abort_signal(self) -> NoReturn: ... + def handle_abort_signal(self) -> Never: ... def run(self) -> None: ... diff --git a/python/helpers/typeshed/stubs/hvac/hvac/api/auth_methods/kubernetes.pyi b/python/helpers/typeshed/stubs/hvac/hvac/api/auth_methods/kubernetes.pyi index d351c9f5c7f1..15d674291da8 100644 --- a/python/helpers/typeshed/stubs/hvac/hvac/api/auth_methods/kubernetes.pyi +++ b/python/helpers/typeshed/stubs/hvac/hvac/api/auth_methods/kubernetes.pyi @@ -5,30 +5,30 @@ DEFAULT_MOUNT_POINT: str class Kubernetes(VaultApiBase): def configure( self, - kubernetes_host, - kubernetes_ca_cert=None, - token_reviewer_jwt=None, - pem_keys=None, - issuer=None, - mount_point="kubernetes", + kubernetes_host: str, + kubernetes_ca_cert: str | None = None, + token_reviewer_jwt: str | None = None, + pem_keys: list[str] | None = None, + issuer: str | None = None, + mount_point: str = "kubernetes", disable_local_ca_jwt: bool = False, ): ... - def read_config(self, mount_point="kubernetes"): ... + def read_config(self, mount_point: str = "kubernetes"): ... def create_role( self, - name, - bound_service_account_names, - bound_service_account_namespaces, - ttl=None, - max_ttl=None, - period=None, - policies=None, + name: str, + bound_service_account_names: list[str] | str, + bound_service_account_namespaces: list[str] | str, + ttl: str | None = None, + max_ttl: str | None = None, + period: str | None = None, + policies: list[str] | str | None = None, token_type: str = "", - mount_point="kubernetes", - alias_name_source=None, + mount_point: str = "kubernetes", + alias_name_source: str | None = None, audience: str | None = None, ): ... - def read_role(self, name, mount_point="kubernetes"): ... - def list_roles(self, mount_point="kubernetes"): ... - def delete_role(self, name, mount_point="kubernetes"): ... - def login(self, role, jwt, use_token: bool = True, mount_point="kubernetes"): ... + def read_role(self, name: str, mount_point: str = "kubernetes"): ... + def list_roles(self, mount_point: str = "kubernetes"): ... + def delete_role(self, name: str, mount_point: str = "kubernetes"): ... + def login(self, role: str, jwt: str, use_token: bool = True, mount_point: str = "kubernetes"): ... diff --git a/python/helpers/typeshed/stubs/hvac/hvac/api/secrets_engines/kv.pyi b/python/helpers/typeshed/stubs/hvac/hvac/api/secrets_engines/kv.pyi index 3a5f72c3356c..5c0ec3a0c7ca 100644 --- a/python/helpers/typeshed/stubs/hvac/hvac/api/secrets_engines/kv.pyi +++ b/python/helpers/typeshed/stubs/hvac/hvac/api/secrets_engines/kv.pyi @@ -1,5 +1,7 @@ import logging +from typing import Any +from hvac.adapters import Adapter from hvac.api.secrets_engines import KvV1, KvV2 from hvac.api.vault_api_base import VaultApiBase @@ -7,7 +9,7 @@ logger: logging.Logger class Kv(VaultApiBase): allowed_kv_versions: list[str] - def __init__(self, adapter, default_kv_version: str = "2") -> None: ... + def __init__(self, adapter: Adapter[Any], default_kv_version: str = "2") -> None: ... @property def v1(self) -> KvV1: ... @property diff --git a/python/helpers/typeshed/stubs/hvac/hvac/api/secrets_engines/kv_v1.pyi b/python/helpers/typeshed/stubs/hvac/hvac/api/secrets_engines/kv_v1.pyi index ed8da7fdf350..3a9fc7072ac9 100644 --- a/python/helpers/typeshed/stubs/hvac/hvac/api/secrets_engines/kv_v1.pyi +++ b/python/helpers/typeshed/stubs/hvac/hvac/api/secrets_engines/kv_v1.pyi @@ -3,7 +3,9 @@ from hvac.api.vault_api_base import VaultApiBase DEFAULT_MOUNT_POINT: str class KvV1(VaultApiBase): - def read_secret(self, path, mount_point="secret"): ... - def list_secrets(self, path, mount_point="secret"): ... - def create_or_update_secret(self, path, secret, method=None, mount_point="secret"): ... - def delete_secret(self, path, mount_point="secret"): ... + def read_secret(self, path: str, mount_point: str = "secret"): ... + def list_secrets(self, path: str, mount_point: str = "secret"): ... + def create_or_update_secret( + self, path: str, secret: dict[str, str], method: str | None = None, mount_point: str = "secret" + ): ... + def delete_secret(self, path: str, mount_point: str = "secret"): ... diff --git a/python/helpers/typeshed/stubs/hvac/hvac/api/secrets_engines/kv_v2.pyi b/python/helpers/typeshed/stubs/hvac/hvac/api/secrets_engines/kv_v2.pyi index 32c6a06a8014..7dcfdfb16748 100644 --- a/python/helpers/typeshed/stubs/hvac/hvac/api/secrets_engines/kv_v2.pyi +++ b/python/helpers/typeshed/stubs/hvac/hvac/api/secrets_engines/kv_v2.pyi @@ -3,25 +3,33 @@ from hvac.api.vault_api_base import VaultApiBase DEFAULT_MOUNT_POINT: str class KvV2(VaultApiBase): - def configure(self, max_versions: int = 10, cas_required=None, delete_version_after: str = "0s", mount_point="secret"): ... - def read_configuration(self, mount_point="secret"): ... - def read_secret(self, path, mount_point="secret", raise_on_deleted_version=None): ... - def read_secret_version(self, path, version=None, mount_point="secret", raise_on_deleted_version=None): ... - def create_or_update_secret(self, path, secret, cas=None, mount_point="secret"): ... - def patch(self, path, secret, mount_point="secret"): ... - def delete_latest_version_of_secret(self, path, mount_point="secret"): ... - def delete_secret_versions(self, path, versions, mount_point="secret"): ... - def undelete_secret_versions(self, path, versions, mount_point="secret"): ... - def destroy_secret_versions(self, path, versions, mount_point="secret"): ... - def list_secrets(self, path, mount_point="secret"): ... - def read_secret_metadata(self, path, mount_point="secret"): ... + def configure( + self, + max_versions: int = 10, + cas_required: bool | None = None, + delete_version_after: str = "0s", + mount_point: str = "secret", + ): ... + def read_configuration(self, mount_point: str = "secret"): ... + def read_secret(self, path: str, mount_point: str = "secret", raise_on_deleted_version: bool | None = None): ... + def read_secret_version( + self, path: str, version: int | None = None, mount_point: str = "secret", raise_on_deleted_version: bool | None = None + ): ... + def create_or_update_secret(self, path: str, secret: dict[str, str], cas: int | None = None, mount_point: str = "secret"): ... + def patch(self, path: str, secret: dict[str, str], mount_point: str = "secret"): ... + def delete_latest_version_of_secret(self, path: str, mount_point: str = "secret"): ... + def delete_secret_versions(self, path: str, versions: list[int], mount_point: str = "secret"): ... + def undelete_secret_versions(self, path: str, versions: list[int], mount_point: str = "secret"): ... + def destroy_secret_versions(self, path: str, versions: list[int], mount_point: str = "secret"): ... + def list_secrets(self, path: str, mount_point: str = "secret"): ... + def read_secret_metadata(self, path: str, mount_point: str = "secret"): ... def update_metadata( self, - path, - max_versions=None, - cas_required=None, + path: str, + max_versions: int | None = None, + cas_required: bool | None = None, delete_version_after: str = "0s", - mount_point="secret", - custom_metadata=None, + mount_point: str = "secret", + custom_metadata: dict[str, str] | None = None, ): ... - def delete_metadata_and_all_versions(self, path, mount_point="secret"): ... + def delete_metadata_and_all_versions(self, path: str, mount_point: str = "secret"): ... diff --git a/python/helpers/typeshed/stubs/hvac/hvac/api/vault_api_base.pyi b/python/helpers/typeshed/stubs/hvac/hvac/api/vault_api_base.pyi index c677beb3f85a..063f55d8fcf7 100644 --- a/python/helpers/typeshed/stubs/hvac/hvac/api/vault_api_base.pyi +++ b/python/helpers/typeshed/stubs/hvac/hvac/api/vault_api_base.pyi @@ -1,10 +1,10 @@ -from _typeshed import Incomplete from abc import ABCMeta from logging import Logger +from typing import Any from hvac.adapters import Adapter logger: Logger class VaultApiBase(metaclass=ABCMeta): - def __init__(self, adapter: Adapter[Incomplete]) -> None: ... + def __init__(self, adapter: Adapter[Any]) -> None: ... diff --git a/python/helpers/typeshed/stubs/hvac/hvac/api/vault_api_category.pyi b/python/helpers/typeshed/stubs/hvac/hvac/api/vault_api_category.pyi index d0dc0b6827fd..9d0e8be845bd 100644 --- a/python/helpers/typeshed/stubs/hvac/hvac/api/vault_api_category.pyi +++ b/python/helpers/typeshed/stubs/hvac/hvac/api/vault_api_category.pyi @@ -10,7 +10,7 @@ logger: Logger class VaultApiCategory(VaultApiBase, metaclass=ABCMeta): implemented_class_names: list[str] def __init__(self, adapter: Adapter[Any]) -> None: ... - def __getattr__(self, item): ... + def __getattr__(self, item: str): ... @property def adapter(self) -> Adapter[Any]: ... @@ -19,8 +19,8 @@ class VaultApiCategory(VaultApiBase, metaclass=ABCMeta): @property @abstractmethod - def implemented_classes(self): ... + def implemented_classes(self) -> list[type[VaultApiBase]]: ... @property def unimplemented_classes(self) -> list[str]: ... @staticmethod - def get_private_attr_name(class_name): ... + def get_private_attr_name(class_name: str) -> str: ... diff --git a/python/helpers/typeshed/stubs/hvac/hvac/utils.pyi b/python/helpers/typeshed/stubs/hvac/hvac/utils.pyi index 0afd5dc74e86..ba48033a43d4 100644 --- a/python/helpers/typeshed/stubs/hvac/hvac/utils.pyi +++ b/python/helpers/typeshed/stubs/hvac/hvac/utils.pyi @@ -1,6 +1,6 @@ from collections.abc import Callable, Iterable, Mapping -from typing import Any, NoReturn, TypedDict, TypeVar, type_check_only -from typing_extensions import NotRequired +from typing import Any, TypedDict, TypeVar, type_check_only +from typing_extensions import Never, NotRequired @type_check_only class _DeprecateProperty(TypedDict): @@ -20,7 +20,7 @@ def raise_for_error( errors: Iterable[str] | str | None = None, text: str | None = None, json: object | None = None, -) -> NoReturn: ... +) -> Never: ... def aliased_parameter( name: str, *aliases: str, removed_in_version: str | None, position: int | None = None, raise_on_multiple: bool = True ) -> Callable[..., Any]: ... diff --git a/python/helpers/typeshed/stubs/jmespath/jmespath/visitor.pyi b/python/helpers/typeshed/stubs/jmespath/jmespath/visitor.pyi index 5789b39b018e..9c5da94684d5 100644 --- a/python/helpers/typeshed/stubs/jmespath/jmespath/visitor.pyi +++ b/python/helpers/typeshed/stubs/jmespath/jmespath/visitor.pyi @@ -1,6 +1,7 @@ from _typeshed import Unused from collections.abc import Callable, MutableMapping -from typing import Any, ClassVar, NoReturn, TypedDict, TypeVar, type_check_only +from typing import Any, ClassVar, TypedDict, TypeVar, type_check_only +from typing_extensions import Never from jmespath.functions import Functions @@ -25,7 +26,7 @@ class Visitor: # `args` and `kwargs` are passed to the appropriate `visit_*` method. # Its return value is returned from visit. def visit(self, node: _TreeNode, *args: Any, **kwargs: Any) -> Any: ... - def default_visit(self, node: _TreeNode, *args: Unused, **kwargs: Unused) -> NoReturn: ... + def default_visit(self, node: _TreeNode, *args: Unused, **kwargs: Unused) -> Never: ... @type_check_only class _TreeNode(TypedDict): @@ -37,7 +38,7 @@ class TreeInterpreter(Visitor): COMPARATOR_FUNC: ClassVar[dict[str, Callable[[Any, Any], Any]]] MAP_TYPE: ClassVar[Callable[[], MutableMapping[Any, Any]]] def __init__(self, options: Options | None = None) -> None: ... - def default_visit(self, node: _TreeNode, *args: Unused, **kwargs: Unused) -> NoReturn: ... + def default_visit(self, node: _TreeNode, *args: Unused, **kwargs: Unused) -> Never: ... def visit_subexpression(self, node: _TreeNode, value: Any) -> Any: ... def visit_field(self, node: _TreeNode, value: Any) -> Any: ... def visit_comparator(self, node: _TreeNode, value: Any) -> Any: ... diff --git a/python/helpers/typeshed/stubs/mypy-extensions/mypy_extensions.pyi b/python/helpers/typeshed/stubs/mypy-extensions/mypy_extensions.pyi index 75721bf1844f..f4f7fa6faf76 100644 --- a/python/helpers/typeshed/stubs/mypy-extensions/mypy_extensions.pyi +++ b/python/helpers/typeshed/stubs/mypy-extensions/mypy_extensions.pyi @@ -75,8 +75,7 @@ def KwArg(type: _T) -> _T: ... def KwArg() -> Any: ... # Return type that indicates a function does not return. -# Deprecated: Use typing.NoReturn instead. -@deprecated("Use typing.NoReturn or typing.Never instead") +@deprecated("Use typing.Never instead") class NoReturn: ... # This is consistent with implementation. Usage intends for this as diff --git a/python/helpers/typeshed/stubs/netaddr/netaddr/ip/sets.pyi b/python/helpers/typeshed/stubs/netaddr/netaddr/ip/sets.pyi index 720336f82bfa..d8656f69b548 100644 --- a/python/helpers/typeshed/stubs/netaddr/netaddr/ip/sets.pyi +++ b/python/helpers/typeshed/stubs/netaddr/netaddr/ip/sets.pyi @@ -1,6 +1,6 @@ from collections.abc import Iterable, Iterator -from typing import NoReturn, TypeAlias -from typing_extensions import Self +from typing import TypeAlias +from typing_extensions import Never, Self from netaddr.ip import IPAddress, IPNetwork, IPRange, _IPNetworkAddr @@ -10,7 +10,7 @@ class IPSet: __slots__ = ("_cidrs", "__weakref__") def __init__(self, iterable: _IPIterable | None = None, flags: int = 0) -> None: ... def compact(self) -> None: ... - def __hash__(self) -> NoReturn: ... + def __hash__(self) -> Never: ... def __contains__(self, ip: _IPNetworkAddr) -> bool: ... def __bool__(self) -> bool: ... def __iter__(self) -> Iterator[IPAddress]: ... diff --git a/python/helpers/typeshed/stubs/networkx/networkx/algorithms/flow/utils.pyi b/python/helpers/typeshed/stubs/networkx/networkx/algorithms/flow/utils.pyi index 456660c90f0d..5bc9995b51c9 100644 --- a/python/helpers/typeshed/stubs/networkx/networkx/algorithms/flow/utils.pyi +++ b/python/helpers/typeshed/stubs/networkx/networkx/algorithms/flow/utils.pyi @@ -1,6 +1,6 @@ from _typeshed import Incomplete -from typing import NoReturn, overload -from typing_extensions import deprecated +from typing import overload +from typing_extensions import Never, deprecated from networkx.classes.graph import Graph, _Node from networkx.classes.multigraph import MultiGraph @@ -29,7 +29,7 @@ class GlobalRelabelThreshold: @overload @deprecated("MultiGraph and MultiDiGraph not supported (yet).") -def build_residual_network(G: MultiGraph[_Node], capacity, *, backend: str | None = None, **backend_kwargs) -> NoReturn: ... +def build_residual_network(G: MultiGraph[_Node], capacity, *, backend: str | None = None, **backend_kwargs) -> Never: ... @overload def build_residual_network(G: Graph[_Node], capacity, *, backend: str | None = None, **backend_kwargs): ... diff --git a/python/helpers/typeshed/stubs/networkx/networkx/algorithms/planarity.pyi b/python/helpers/typeshed/stubs/networkx/networkx/algorithms/planarity.pyi index e731f2d953be..b351c8f2c49f 100644 --- a/python/helpers/typeshed/stubs/networkx/networkx/algorithms/planarity.pyi +++ b/python/helpers/typeshed/stubs/networkx/networkx/algorithms/planarity.pyi @@ -1,7 +1,7 @@ from _typeshed import Incomplete, Unused from collections.abc import Generator, Iterable, Mapping, MutableSet, Reversible from decimal import Decimal -from typing import NoReturn +from typing_extensions import Never from networkx.classes.digraph import DiGraph from networkx.classes.graph import Graph, _EdgeData, _EdgePlus, _Node, _NodeData @@ -107,8 +107,8 @@ class PlanarEmbedding(DiGraph[_Node]): self, v: _Node, w: _Node, mark_half_edges: MutableSet[tuple[_Node, _Node]] | None = None ) -> list[_Node]: ... # Overriden in __init__ to always raise - def add_edge(self, u_of_edge: _Node, v_of_edge: _Node, **attr: Unused) -> NoReturn: ... - def add_edges_from(self, ebunch_to_add: Iterable[_EdgePlus[_Node]], **attr: Unused) -> NoReturn: ... + def add_edge(self, u_of_edge: _Node, v_of_edge: _Node, **attr: Unused) -> Never: ... + def add_edges_from(self, ebunch_to_add: Iterable[_EdgePlus[_Node]], **attr: Unused) -> Never: ... def add_weighted_edges_from( self, ebunch_to_add: Iterable[tuple[_Node, _Node, float | Decimal | None]], weight: str = "weight", **attr: Unused - ) -> NoReturn: ... + ) -> Never: ... diff --git a/python/helpers/typeshed/stubs/oauthlib/oauthlib/oauth2/rfc6749/errors.pyi b/python/helpers/typeshed/stubs/oauthlib/oauthlib/oauth2/rfc6749/errors.pyi index c0b8901d0b60..d76eea7373a8 100644 --- a/python/helpers/typeshed/stubs/oauthlib/oauthlib/oauth2/rfc6749/errors.pyi +++ b/python/helpers/typeshed/stubs/oauthlib/oauthlib/oauth2/rfc6749/errors.pyi @@ -1,5 +1,5 @@ from _typeshed import Incomplete -from typing import NoReturn +from typing_extensions import Never from oauthlib.common import Request @@ -147,4 +147,4 @@ class CustomOAuth2Error(OAuth2Error): request: Request | None = None, ) -> None: ... -def raise_from_error(error: str, params: dict[str, Incomplete] | None = None) -> NoReturn: ... +def raise_from_error(error: str, params: dict[str, Incomplete] | None = None) -> Never: ... diff --git a/python/helpers/typeshed/stubs/openpyxl/openpyxl/chart/data_source.pyi b/python/helpers/typeshed/stubs/openpyxl/openpyxl/chart/data_source.pyi index 78e269889e5a..fa6460de3ae9 100644 --- a/python/helpers/typeshed/stubs/openpyxl/openpyxl/chart/data_source.pyi +++ b/python/helpers/typeshed/stubs/openpyxl/openpyxl/chart/data_source.pyi @@ -1,5 +1,6 @@ from _typeshed import ConvertibleToInt, Incomplete, Unused -from typing import ClassVar, Literal, NoReturn, overload +from typing import ClassVar, Literal, overload +from typing_extensions import Never from openpyxl.descriptors import Strict from openpyxl.descriptors.base import Alias, Bool, Integer, String, Typed, _ConvertibleToBool @@ -109,7 +110,7 @@ class AxDataSource(Serialisable): @overload def __init__( self, numRef: None = None, numLit: None = None, strRef: None = None, strLit: None = None, multiLvlStrRef: None = None - ) -> NoReturn: ... + ) -> Never: ... @overload def __init__( self, diff --git a/python/helpers/typeshed/stubs/openpyxl/openpyxl/descriptors/nested.pyi b/python/helpers/typeshed/stubs/openpyxl/openpyxl/descriptors/nested.pyi index 44d98a3ebd2c..b2167ac7366d 100644 --- a/python/helpers/typeshed/stubs/openpyxl/openpyxl/descriptors/nested.pyi +++ b/python/helpers/typeshed/stubs/openpyxl/openpyxl/descriptors/nested.pyi @@ -1,6 +1,7 @@ from _typeshed import ConvertibleToFloat, ConvertibleToInt, Unused from collections.abc import Iterable -from typing import Any, ClassVar, Literal, NoReturn, TypeAlias, overload +from typing import Any, ClassVar, Literal, TypeAlias, overload +from typing_extensions import Never from openpyxl.descriptors import Strict from openpyxl.descriptors.base import Bool, Convertible, Descriptor, Float, Integer, MinMax, NoneSet, Set, String @@ -153,7 +154,7 @@ class NestedText(NestedValue[_T, _N]): def __set__(self: NestedText[int, Literal[False]], instance: Serialisable | Strict, value: ConvertibleToInt) -> None: ... # If expected type (_T) is not str, it's impossible to use an Element as the value @overload - def __set__(self: NestedText[_T, Literal[True]], instance: Serialisable | Strict, value: _HasTagAndGet[Any]) -> NoReturn: ... + def __set__(self: NestedText[_T, Literal[True]], instance: Serialisable | Strict, value: _HasTagAndGet[Any]) -> Never: ... # Anything else @overload def __set__(self: NestedText[_T, Literal[True]], instance: Serialisable | Strict, value: _T | int | Any | None) -> None: ... diff --git a/python/helpers/typeshed/stubs/openpyxl/openpyxl/descriptors/serialisable.pyi b/python/helpers/typeshed/stubs/openpyxl/openpyxl/descriptors/serialisable.pyi index b9e62a294ef3..4ea4e6bae42b 100644 --- a/python/helpers/typeshed/stubs/openpyxl/openpyxl/descriptors/serialisable.pyi +++ b/python/helpers/typeshed/stubs/openpyxl/openpyxl/descriptors/serialisable.pyi @@ -27,7 +27,7 @@ class Serialisable(metaclass=MetaSerialisable): idx_base: int # Needs overrides in many sub-classes. But a lot of subclasses are instantiated without overriding it, so can't be abstract # Subclasses "overrides" this property with a ClassVar, and Serialisable is too widely used, - # so it can't be typed as NoReturn either without introducing many false-positives. + # so it can't be typed as Never either without introducing many false-positives. @property def tagname(self) -> str: ... namespace: ClassVar[str | None] diff --git a/python/helpers/typeshed/stubs/openpyxl/openpyxl/worksheet/worksheet.pyi b/python/helpers/typeshed/stubs/openpyxl/openpyxl/worksheet/worksheet.pyi index 82244ad9daf1..be41858dc291 100644 --- a/python/helpers/typeshed/stubs/openpyxl/openpyxl/worksheet/worksheet.pyi +++ b/python/helpers/typeshed/stubs/openpyxl/openpyxl/worksheet/worksheet.pyi @@ -1,8 +1,8 @@ from _typeshed import ConvertibleToInt, Incomplete from collections.abc import Generator, Iterable, Iterator from types import GeneratorType -from typing import Any, Final, Literal, NoReturn, overload -from typing_extensions import deprecated +from typing import Any, Final, Literal, overload +from typing_extensions import Never, deprecated from openpyxl import _Decodable, _VisibilityType from openpyxl.cell import _AnyCellValue, _CellGetValue, _CellOrMergedCell, _CellSetValue @@ -245,7 +245,7 @@ class Worksheet(_WorkbookChild): # Will always raise: TypeError: 'set' object is not subscriptable @property @deprecated("Use ws.merged_cells.ranges") - def merged_cell_ranges(self) -> NoReturn: ... + def merged_cell_ranges(self) -> Never: ... def unmerge_cells( self, range_string: str | None = None, diff --git a/python/helpers/typeshed/stubs/paramiko/paramiko/client.pyi b/python/helpers/typeshed/stubs/paramiko/paramiko/client.pyi index e28309b2ff5b..b020f823fa83 100644 --- a/python/helpers/typeshed/stubs/paramiko/paramiko/client.pyi +++ b/python/helpers/typeshed/stubs/paramiko/paramiko/client.pyi @@ -1,6 +1,7 @@ from _typeshed import FileDescriptorOrPath from collections.abc import Iterable, Mapping -from typing import NoReturn, Protocol, type_check_only +from typing import Protocol, type_check_only +from typing_extensions import Never from paramiko.auth_strategy import AuthStrategy from paramiko.channel import Channel, ChannelFile, ChannelStderrFile, ChannelStdinFile @@ -79,7 +80,7 @@ class AutoAddPolicy(MissingHostKeyPolicy): def missing_host_key(self, client: SSHClient, hostname: str, key: PKey) -> None: ... class RejectPolicy(MissingHostKeyPolicy): - def missing_host_key(self, client: SSHClient, hostname: str, key: PKey) -> NoReturn: ... + def missing_host_key(self, client: SSHClient, hostname: str, key: PKey) -> Never: ... class WarningPolicy(MissingHostKeyPolicy): def missing_host_key(self, client: SSHClient, hostname: str, key: PKey) -> None: ... diff --git a/python/helpers/typeshed/stubs/parsimonious/parsimonious/grammar.pyi b/python/helpers/typeshed/stubs/parsimonious/parsimonious/grammar.pyi index efe971f205af..7871c183072c 100644 --- a/python/helpers/typeshed/stubs/parsimonious/parsimonious/grammar.pyi +++ b/python/helpers/typeshed/stubs/parsimonious/parsimonious/grammar.pyi @@ -2,7 +2,8 @@ import collections.abc from _typeshed import Incomplete from collections import OrderedDict from collections.abc import Callable, Mapping -from typing import Any, NoReturn +from typing import Any +from typing_extensions import Never from parsimonious.expressions import _CALLABLE_TYPE, Expression, Literal, Lookahead, OneOf, Regex, Sequence, TokenMatcher from parsimonious.nodes import Node, NodeVisitor @@ -55,6 +56,6 @@ class TokenRuleVisitor(RuleVisitor): def visit_spaceless_literal( self, spaceless_literal: Node, visited_children: collections.abc.Sequence[Any] ) -> TokenMatcher: ... - def visit_regex(self, node: Node, regex: collections.abc.Sequence[Any]) -> NoReturn: ... + def visit_regex(self, node: Node, regex: collections.abc.Sequence[Any]) -> Never: ... rule_grammar: Grammar diff --git a/python/helpers/typeshed/stubs/peewee/METADATA.toml b/python/helpers/typeshed/stubs/peewee/METADATA.toml index 2afd31f409f6..391b04704b37 100644 --- a/python/helpers/typeshed/stubs/peewee/METADATA.toml +++ b/python/helpers/typeshed/stubs/peewee/METADATA.toml @@ -1,4 +1,4 @@ -version = "4.0.8" +version = "4.2.6" upstream-repository = "https://github.com/coleifer/peewee" # We're not providing stubs for all playhouse modules right now # https://github.com/python/typeshed/pull/11731#issuecomment-2065729058 diff --git a/python/helpers/typeshed/stubs/peewee/peewee.pyi b/python/helpers/typeshed/stubs/peewee/peewee.pyi index d0d887816807..fbd003f762df 100644 --- a/python/helpers/typeshed/stubs/peewee/peewee.pyi +++ b/python/helpers/typeshed/stubs/peewee/peewee.pyi @@ -1,11 +1,11 @@ import re import threading -from _typeshed import Incomplete, SupportsKeysAndGetItem, Unused +from _typeshed import Incomplete, SupportsKeysAndGetItem from collections.abc import Callable, Generator, Iterable, Iterator from datetime import date, datetime, time from decimal import Decimal from types import TracebackType -from typing import Any, ClassVar, Final, Generic, Literal, NamedTuple, NoReturn, TypeAlias, TypedDict, overload, type_check_only +from typing import Any, ClassVar, Final, Generic, Literal, NamedTuple, TypeAlias, TypedDict, overload, type_check_only from typing_extensions import Self, TypeIs, TypeVar, Unpack from uuid import UUID @@ -13,8 +13,6 @@ def callable_(c: object) -> TypeIs[Callable[..., object]]: ... multi_types: tuple[type[Incomplete], ...] -def reraise(tp: Unused, value: BaseException, tb: TracebackType | None = None) -> NoReturn: ... - _T = TypeVar("_T") _VT = TypeVar("_VT") _F = TypeVar("_F", bound=Callable[..., Any]) @@ -22,6 +20,7 @@ _Model: TypeAlias = Model _M = TypeVar("_M", bound=Model, default=Model) # __get__/__set__ value type. Bare Field defaults to Field[Any]. _V = TypeVar("_V", default=Any) +_DatabaseType: TypeAlias = Database | DatabaseProxy # Common field kwargs, Unpack-ed into the field __new__ overloads. @type_check_only @@ -80,7 +79,7 @@ SNAKE_CASE_STEP2: Final[re.Pattern[str]] IDENTIFIER_RE: Final[re.Pattern[str]] def make_identifier(s: str) -> str: ... -def chunked(it, n) -> Generator[list[Incomplete]]: ... +def chunked(it: Iterable[_T], n: int) -> Generator[list[_T]]: ... class _callable_context_manager: def __call__(self, fn): ... @@ -204,6 +203,7 @@ class Source(Node): class _HashableSource: def __init__(self, *args, **kwargs) -> None: ... def alias(self, name) -> Self: ... + def clone(self) -> _HashableSource: ... def __hash__(self) -> int: ... def __eq__(self, other) -> Expression | bool: ... # type: ignore[override] def __ne__(self, other) -> Expression | bool: ... # type: ignore[override] @@ -227,7 +227,7 @@ class BaseTable(Source): class _BoundTableContext(_callable_context_manager): table: Incomplete database: Incomplete - def __init__(self, table, database) -> None: ... + def __init__(self, table, database: _DatabaseType) -> None: ... def __enter__(self): ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None @@ -241,8 +241,8 @@ class Table(_HashableSource, BaseTable): # type: ignore[misc] self, name, columns=None, primary_key=None, schema: str | None = None, alias=None, _model=None, _database=None ) -> None: ... def clone(self) -> Table: ... - def bind(self, database=None) -> Self: ... - def bind_ctx(self, database=None) -> _BoundTableContext: ... + def bind(self, database: _DatabaseType | None = None) -> Self: ... + def bind_ctx(self, database: _DatabaseType | None = None) -> _BoundTableContext: ... def select(self, *columns) -> Select: ... def insert(self, insert=None, columns=None, **kwargs) -> Insert: ... def replace(self, insert=None, columns=None, **kwargs): ... @@ -288,13 +288,11 @@ class ColumnBase(Node): def __add__(self, rhs: Any) -> Expression: ... __sub__: ClassVar[Callable[[Self, Any], Expression]] __mul__: ClassVar[Callable[[Self, Any], Expression]] - __div__: ClassVar[Callable[[Self, Any], Expression]] __truediv__: ClassVar[Callable[[Self, Any], Expression]] __xor__: ClassVar[Callable[[Self, Any], Expression]] def __radd__(self, rhs: Any) -> Expression: ... __rsub__: ClassVar[Callable[[Self, Any], Expression]] __rmul__: ClassVar[Callable[[Self, Any], Expression]] - __rdiv__: ClassVar[Callable[[Self, Any], Expression]] __rtruediv__: ClassVar[Callable[[Self, Any], Expression]] __rand__: ClassVar[Callable[[Self, Any], Expression]] __ror__: ClassVar[Callable[[Self, Any], Expression]] @@ -410,9 +408,12 @@ class Ordering(WrappedNode): collation: Incomplete nulls: Incomplete def __init__(self, node, direction, collation=None, nulls=None) -> None: ... - def collate(self, collation=None) -> Ordering: ... # type: ignore[override] + def collate(self, collation=None) -> Self: ... # type: ignore[override] def __sql__(self, ctx): ... +def Asc(node, collation=None, nulls=None) -> Ordering: ... +def Desc(node, collation=None, nulls=None) -> Ordering: ... + class Expression(ColumnBase): lhs: Incomplete op: Incomplete @@ -438,7 +439,7 @@ class SQL(ColumnBase): def __init__(self, sql, params=None) -> None: ... def __sql__(self, ctx): ... -def Check(constraint, name=None) -> Node: ... +def Check(constraint: str, name: str | None = None) -> SQL | NodeList: ... def Default(value) -> SQL: ... class Function(ColumnBase): @@ -519,6 +520,9 @@ class NodeList(ColumnBase): def __init__(self, nodes, glue: str = " ", parens: bool = False) -> None: ... def __sql__(self, ctx): ... +def CommaNodeList(nodes) -> NodeList: ... +def EnclosedNodeList(nodes) -> NodeList: ... + class _Namespace(Node): __slots__ = ("_name",) def __init__(self, name) -> None: ... @@ -540,6 +544,7 @@ class DQ(ColumnBase): Tuple: Incomplete class QualifiedNames(WrappedNode): + def __init__(self, node, scope: int = 16) -> None: ... def __sql__(self, ctx): ... class OnConflict(Node): @@ -565,7 +570,7 @@ class OnConflict(Node): class BaseQuery(Node): default_row_type: Incomplete def __init__(self, _database=None, **kwargs) -> None: ... - def bind(self, database=None) -> Self: ... + def bind(self, database: _DatabaseType | None = None) -> Self: ... def clone(self) -> Self: ... def dicts(self, as_dict: bool = True) -> Self: ... def tuples(self, as_tuple: bool = True) -> Self: ... @@ -573,9 +578,9 @@ class BaseQuery(Node): def objects(self, constructor=None) -> Self: ... def __sql__(self, ctx) -> None: ... def sql(self) -> tuple[str, list[Any]]: ... # Returns (sql, params), params are bound query values - def execute(self, database=None): ... - async def aexecute(self, database=None): ... - def iterator(self, database=None): ... + def execute(self, database: _DatabaseType | None = None): ... + async def aexecute(self, database: _DatabaseType | None = None): ... + def iterator(self, database: _DatabaseType | None = None): ... def __iter__(self): ... def __getitem__(self, value): ... def __len__(self) -> int: ... @@ -612,20 +617,20 @@ class SelectQuery(Query): def select_from(self, *columns) -> Select: ... class SelectBase(_HashableSource, Source, SelectQuery): # type: ignore[misc] - def peek(self, database=None, n: int = 1): ... - def first(self, database=None, n: int = 1): ... - def scalar(self, database=None, as_tuple: bool = False, as_dict: bool = False): ... - def scalars(self, database=None) -> Generator[Incomplete]: ... - def count(self, database=None, clear_limit: bool = False) -> int: ... - def exists(self, database=None) -> bool: ... - def get(self, database=None): ... + def peek(self, database: _DatabaseType | None = None, n: int = 1): ... + def first(self, database: _DatabaseType | None = None, n: int = 1): ... + def scalar(self, database: _DatabaseType | None = None, as_tuple: bool = False, as_dict: bool = False): ... + def scalars(self, database: _DatabaseType | None = None) -> Generator[Incomplete]: ... + def count(self, database: _DatabaseType | None = None, clear_limit: bool = False) -> int: ... + def exists(self, database: _DatabaseType | None = None) -> bool: ... + def get(self, database: _DatabaseType | None = None): ... class CompoundSelectQuery(SelectBase): lhs: Incomplete op: Incomplete rhs: Incomplete def __init__(self, lhs, op, rhs) -> None: ... - def exists(self, database=None) -> bool: ... + def exists(self, database: _DatabaseType | None = None) -> bool: ... def __sql__(self, ctx): ... class Select(SelectBase): @@ -642,7 +647,7 @@ class Select(SelectBase): **kwargs, ) -> None: ... def clone(self) -> Self: ... - def columns(self, *columns, **kwargs) -> Self: ... + def columns(self, *columns) -> Self: ... select = columns def select_extend(self, *columns) -> Self: ... @@ -672,8 +677,8 @@ class _WriteQuery(Query): def cte(self, name, recursive: bool = False, columns=None, materialized=None) -> CTE: ... def returning(self, *returning) -> Self: ... def apply_returning(self, ctx): ... - def execute_returning(self, database): ... - def handle_result(self, database, cursor): ... + def execute_returning(self, database: _DatabaseType): ... + def handle_result(self, database: _DatabaseType, cursor): ... def __sql__(self, ctx): ... class Update(_WriteQuery): @@ -697,7 +702,7 @@ class Insert(_WriteQuery): def get_default_data(self): ... def get_default_columns(self) -> list[Incomplete] | None: ... def __sql__(self, ctx): ... - def handle_result(self, database, cursor): ... + def handle_result(self, database: _DatabaseType, cursor): ... class Delete(_WriteQuery): def __sql__(self, ctx): ... @@ -753,12 +758,17 @@ class ColumnMetadata(NamedTuple): primary_key: Incomplete table: Incomplete default: Incomplete + full_type: str | None = None + identity: bool = False class ForeignKeyMetadata(NamedTuple): column: Incomplete dest_table: Incomplete dest_column: Incomplete table: Incomplete + name: str | None = None + on_delete: str | None = None + on_update: str | None = None class ViewMetadata(NamedTuple): name: Incomplete @@ -799,12 +809,12 @@ class Database(_callable_context_manager): param: str quote: str server_version: Incomplete - commit_select: bool compound_select_parentheses: Incomplete for_update: bool index_schema_prefix: bool index_using_precedes_table: bool - limit_max: Incomplete + index_value_literals: bool + limit_max: int | None nulls_ordering: bool returning_clause: bool safe_create_index: bool @@ -814,9 +824,10 @@ class Database(_callable_context_manager): autoconnect: Incomplete thread_safe: Incomplete connect_params: Incomplete + def __deepcopy__(self, memo: Any) -> Self: ... def __init__( self, - database, + database: str | None, thread_safe: bool = True, autorollback: bool = False, field_types=None, @@ -827,7 +838,7 @@ class Database(_callable_context_manager): ) -> None: ... database: Incomplete deferred: Incomplete - def init(self, database, **kwargs) -> None: ... + def init(self, database: str | None, **kwargs) -> None: ... def __enter__(self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None @@ -890,15 +901,16 @@ class SqliteDatabase(Database): field_types: Incomplete operations: Incomplete index_schema_prefix: bool + index_value_literals: bool limit_max: int server_version: Incomplete truncate_table: bool nulls_ordering: bool def __init__( - self, database, pragmas=None, regexp_function: bool = False, rank_functions: bool = False, *args, **kwargs + self, database: str | None, pragmas=None, regexp_function: bool = False, rank_functions: bool = False, *args, **kwargs ) -> None: ... returning_clause: Incomplete - def init(self, database, pragmas=None, timeout: int = 5, returning_clause=None, **kwargs) -> None: ... + def init(self, database: str | None, pragmas=None, timeout: int = 5, returning_clause=None, **kwargs) -> None: ... def pragma(self, key, value=..., permanent: bool = False, schema: str | None = None): ... cache_size: Incomplete foreign_keys: Incomplete @@ -935,7 +947,6 @@ class SqliteDatabase(Database): def attach(self, filename, name) -> bool: ... def detach(self, name) -> bool: ... def last_insert_id(self, cursor, query_type=None): ... - def rows_affected(self, cursor): ... def begin(self, lock_type=None) -> None: ... def get_tables(self, schema: str | None = None) -> list[str]: ... def get_views(self, schema: str | None = None) -> list[ViewMetadata]: ... @@ -966,6 +977,8 @@ class _BasePsycopgAdapter: @overload def isolation_level_str(self, isolation_level: _T) -> _T: ... + def server_side_cursor(self, conn): ... + class Psycopg2Adapter(_BasePsycopgAdapter): json_type: Incomplete jsonb_type: Incomplete @@ -996,7 +1009,6 @@ class PostgresqlDatabase(Database): field_types: Incomplete operations: Incomplete param: str - commit_select: bool compound_select_parentheses: Incomplete for_update: bool nulls_ordering: bool @@ -1006,7 +1018,7 @@ class PostgresqlDatabase(Database): psycopg3_adapter: Incomplete def init( self, - database, + database: str | None, register_unicode: bool = True, encoding=None, isolation_level=None, @@ -1016,7 +1028,6 @@ class PostgresqlDatabase(Database): ) -> None: ... def is_connection_usable(self) -> bool: ... def last_insert_id(self, cursor, query_type=None): ... - def rows_affected(self, cursor): ... def begin(self, isolation_level: str | None = None) -> None: ... def get_tables(self, schema: str | None = None) -> list[str]: ... def get_views(self, schema: str | None = None) -> list[ViewMetadata]: ... @@ -1042,7 +1053,6 @@ class MySQLDatabase(Database): operations: Incomplete param: str quote: str - commit_select: bool compound_select_parentheses: Incomplete for_update: bool index_using_precedes_table: bool @@ -1050,7 +1060,8 @@ class MySQLDatabase(Database): safe_create_index: bool safe_drop_index: bool sql_mode: str - def init(self, database, **kwargs) -> None: ... + mariadb: bool + def init(self, database: str | None, mariadb: bool | None = None, **kwargs) -> None: ... def is_connection_usable(self) -> bool: ... def default_values_insert(self, ctx): ... def begin(self, isolation_level: str | None = None) -> None: ... @@ -1192,7 +1203,6 @@ class Field(ColumnBase, Generic[_V]): auto_increment: bool default_index_type: Incomplete field_type: ClassVar[str] - unpack: bool null: Incomplete index: Incomplete unique: Incomplete @@ -1255,7 +1265,7 @@ class BigAutoField(AutoField[_V]): def __new__(cls, *args: Any, **kwargs: Unpack[_FieldKwargs]) -> BigAutoField[int]: ... class IdentityField(AutoField[_V]): - def __new__(cls, *args: Any, **kwargs: Unpack[_FieldKwargs]) -> IdentityField[int]: ... + def __new__(cls, *args: Any, generate_always: bool = False, **kwargs: Unpack[_FieldKwargs]) -> IdentityField[int]: ... class PrimaryKeyField(AutoField[_V]): def __new__(cls, *args: Any, **kwargs: Unpack[_FieldKwargs]) -> PrimaryKeyField[int]: ... @@ -1351,6 +1361,24 @@ class BlobField(FieldDatabaseHook, Field[_V]): def db_value(self, value): ... +class JSONPath(ColumnBase): + def __init__(self, field, keys=..., as_text: bool = False) -> None: ... + def __getitem__(self, key) -> JSONPath: ... + def path(self, *keys) -> JSONPath: ... + def as_text(self, as_text: bool = True) -> Self: ... + def as_int(self) -> Cast: ... + def as_float(self) -> Cast: ... + def set(self, value) -> Expression: ... + def insert(self, value) -> Expression: ... + def replace(self, value) -> Expression: ... + def append(self, value) -> Expression: ... + def remove(self) -> Expression: ... + def length(self) -> Expression: ... + def contained_by(self, value) -> Expression: ... + def has_key(self, key) -> Expression: ... + def has_keys(self, key_list) -> Expression: ... + def has_any_keys(self, key_list) -> Expression: ... + class JSONField(FieldDatabaseHook, Field): def __init__(self, dumps=None, loads=None, **kwargs) -> None: ... def path(self, *keys): ... @@ -1433,7 +1461,7 @@ class DateTimeField(_BaseFormattedField[_V]): cls, formats: list[str] | None = ..., *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs] ) -> DateTimeField[datetime]: ... - formats: Incomplete + formats: list[str] def adapt(self, value): ... def to_timestamp(self): ... def truncate(self, part): ... @@ -1460,7 +1488,7 @@ class DateField(_BaseFormattedField[_V]): cls, formats: list[str] | None = ..., *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs] ) -> DateField[date]: ... - formats: Incomplete + formats: list[str] def adapt(self, value): ... def to_timestamp(self): ... def truncate(self, part): ... @@ -1481,7 +1509,7 @@ class TimeField(_BaseFormattedField[_V]): cls, formats: list[str] | None = ..., *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs] ) -> TimeField[time]: ... - formats: Incomplete + formats: list[str] def adapt(self, value): ... @property def hour(self): ... @@ -1495,14 +1523,17 @@ class TimestampField(BigIntegerField[_V]): resolution: Incomplete ticks_to_microsecond: Incomplete utc: Incomplete + formats: list[str] @overload - def __new__(cls, *args: Any, null: Literal[True], **kwargs: Unpack[_FieldKwargs]) -> TimestampField[datetime | None]: ... + def __new__( + cls, *args, resolution: int = 1, utc: bool = False, null: Literal[True], **kwargs: Unpack[_FieldKwargs] + ) -> TimestampField[datetime | None]: ... @overload - def __new__(cls, *args: Any, null: Literal[False] = ..., **kwargs: Unpack[_FieldKwargs]) -> TimestampField[datetime]: ... + def __new__( + cls, *args, resolution: int = 1, utc: bool = False, null: Literal[False] = False, **kwargs: Unpack[_FieldKwargs] + ) -> TimestampField[datetime]: ... - def local_to_utc(self, dt) -> datetime: ... - def utc_to_local(self, dt) -> datetime: ... def get_timestamp(self, value) -> float: ... def db_value(self, value) -> int | None: ... def python_value(self, value): ... @@ -1677,7 +1708,7 @@ class _SortedFieldList: class SchemaManager: model: Incomplete context_options: Incomplete - def __init__(self, model, database=None, **context_options) -> None: ... + def __init__(self, model, database: _DatabaseType | None = None, **context_options) -> None: ... @property def database(self): ... @@ -1731,7 +1762,7 @@ class Metadata: def __init__( self, model, - database=None, + database: _DatabaseType | None = None, table_name=None, indexes=None, primary_key=None, @@ -1770,7 +1801,6 @@ class Metadata: @property def entity(self) -> Entity: ... - def get_rel_for_model(self, model) -> tuple[list[Incomplete], list[Incomplete]]: ... def add_field(self, field_name, field, set_attribute: bool = True) -> None: ... def remove_field(self, field_name) -> None: ... auto_increment: Incomplete @@ -1778,7 +1808,7 @@ class Metadata: def get_primary_keys(self): ... def get_default_dict(self): ... def fields_to_index(self) -> list[Incomplete]: ... - def set_database(self, database) -> None: ... + def set_database(self, database: _DatabaseType) -> None: ... def set_table_name(self, table_name) -> None: ... class SubclassAwareMetadata(Metadata): @@ -1798,7 +1828,6 @@ class ModelBase(type): def __contains__(self, key) -> bool: ... def __len__(self) -> int: ... def __bool__(self) -> bool: ... - def __nonzero__(self) -> bool: ... def __sql__(self, ctx): ... class _BoundModelsContext(_callable_context_manager): @@ -1806,7 +1835,7 @@ class _BoundModelsContext(_callable_context_manager): database: Incomplete bind_refs: Incomplete bind_backrefs: Incomplete - def __init__(self, models, database, bind_refs, bind_backrefs) -> None: ... + def __init__(self, models, database: _DatabaseType, bind_refs, bind_backrefs) -> None: ... def __enter__(self): ... def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None @@ -1820,7 +1849,7 @@ class Model(metaclass=ModelBase): @classmethod def validate_model(cls) -> None: ... @classmethod - def alias(cls, alias=None) -> ModelAlias: ... + def alias(cls, alias=None) -> ModelAlias[Self]: ... @classmethod def select(cls, *fields) -> ModelSelect[Self]: ... @classmethod @@ -1846,7 +1875,7 @@ class Model(metaclass=ModelBase): @classmethod def bulk_update(cls, model_list, fields, batch_size=None): ... @classmethod - def noop(cls) -> NoopModelSelect: ... + def noop(cls) -> NoopModelSelect[Self]: ... @classmethod def get(cls, *query, **filters) -> Self: ... @classmethod @@ -1875,9 +1904,9 @@ class Model(metaclass=ModelBase): def __ne__(self, other) -> Expression | bool: ... # type: ignore[override] def __sql__(self, ctx): ... @classmethod - def bind(cls, database, bind_refs: bool = True, bind_backrefs: bool = True, _exclude=None) -> bool: ... + def bind(cls, database: _DatabaseType, bind_refs: bool = True, bind_backrefs: bool = True, _exclude=None) -> bool: ... @classmethod - def bind_ctx(cls, database, bind_refs: bool = True, bind_backrefs: bool = True) -> _BoundModelsContext: ... + def bind_ctx(cls, database: _DatabaseType, bind_refs: bool = True, bind_backrefs: bool = True) -> _BoundModelsContext: ... @classmethod def table_exists(cls): ... @classmethod @@ -1891,12 +1920,12 @@ class Model(metaclass=ModelBase): @classmethod def add_index(cls, *fields, **kwargs) -> None: ... -class ModelAlias(Node): - def __init__(self, model, alias=None) -> None: ... +class ModelAlias(Node, Generic[_M]): + def __init__(self, model: type[_M], alias=None) -> None: ... def __getattr__(self, attr: str): ... def __setattr__(self, attr: str, value) -> None: ... def get_field_aliases(self) -> list[Incomplete]: ... - def select(self, *selection) -> ModelSelect: ... + def select(self, *selection) -> ModelSelect[_M]: ... def __call__(self, **kwargs): ... def __sql__(self, ctx): ... @@ -1935,9 +1964,11 @@ class BaseModelSelect(_ModelQueryHelper): def except_(self, rhs) -> ModelCompoundSelectQuery: ... __sub__ = except_ def __iter__(self): ... - def prefetch(self, *subqueries): ... - def get(self, database=None): ... - def get_or_none(self, database=None): ... + def prefetch(self, *subqueries, prefetch_type: int = ...): ... + def with_related(self, *loads: Load | ForeignKeyField[Any] | BackrefAccessor) -> Self: ... + def iterator(self, database: _DatabaseType | None = ...) -> Iterator[Any]: ... + def get(self, database: _DatabaseType | None = None): ... + def get_or_none(self, database: _DatabaseType | None = None): ... def group_by(self, *columns) -> Self: ... class ModelCompoundSelectQuery(BaseModelSelect, CompoundSelectQuery): # type: ignore[misc] @@ -1948,8 +1979,8 @@ class ModelSelect(BaseModelSelect, Select, Generic[_M]): # type: ignore[misc] model: type[_M] def __init__(self, model, fields_or_models, is_default: bool = False) -> None: ... def __iter__(self) -> Iterator[_M]: ... - def get(self, database=None) -> _M: ... - def get_or_none(self, database=None) -> _M | None: ... + def get(self, database: _DatabaseType | None = None) -> _M: ... + def get_or_none(self, database: _DatabaseType | None = None) -> _M | None: ... def clone(self) -> Self: ... def select(self, *fields_or_models) -> ModelSelect[_M]: ... def select_extend(self, *columns) -> Self: ... @@ -1963,7 +1994,7 @@ class ModelSelect(BaseModelSelect, Select, Generic[_M]): # type: ignore[misc] def create_table(self, name, safe: bool = True, **meta): ... def __sql_selection__(self, ctx, is_subquery: bool = False): ... -class NoopModelSelect(ModelSelect): +class NoopModelSelect(ModelSelect[_M]): def __sql__(self, ctx): ... class _ModelWriteQueryHelper(_ModelQueryHelper): @@ -1982,7 +2013,7 @@ class ModelInsert(_ModelWriteQueryHelper, Insert): # type: ignore[misc] class ModelDelete(_ModelWriteQueryHelper, Delete): ... # type: ignore[misc] -class ManyToManyQuery(ModelSelect): +class ManyToManyQuery(ModelSelect[_M]): def __init__(self, instance, accessor, rel, *args, **kwargs) -> None: ... def add(self, value, clear_existing: bool = False) -> None: ... def remove(self, value): ... @@ -2026,10 +2057,8 @@ class ModelObjectCursorWrapper(ModelDictCursorWrapper): class ModelCursorWrapper(BaseModelCursorWrapper): from_list: Incomplete joins: Incomplete - dicts: bool - def __init__(self, cursor, model, select, from_list, joins, dicts: bool = False) -> None: ... - key_to_constructor: Incomplete - src_is_dest: dict[Incomplete, Incomplete] + def __init__(self, cursor, model, select, from_list, joins) -> None: ... + key_to_constructor: dict[Incomplete, tuple[Incomplete, Incomplete]] src_to_dest: list[tuple[Incomplete, Incomplete, Incomplete, bool, Incomplete, bool]] column_keys: list[Incomplete] def initialize(self) -> None: ... @@ -2045,13 +2074,21 @@ class _PrefetchQuery(NamedTuple): model: Incomplete class PrefetchQuery(_PrefetchQuery): - def __new__( - cls, query, fields=None, is_backref: bool | None = None, rel_models=None, field_to_name=None, model=None - ) -> Self: ... + def __new__(cls, query, fields=None, is_backref: bool | None = None, rel_models=None, field_to_name=None) -> Self: ... def populate_instance(self, instance, id_map) -> None: ... def store_instance(self, instance, id_map) -> None: ... -def prefetch(sq, *subqueries): ... +def prefetch(sq, *subqueries, prefetch_type: int = ...): ... + +class Load(Node): + def __init__( + self, + rel: ForeignKeyField[Any] | BackrefAccessor, + query: ModelSelect[Any] | None = ..., + strategy: int = ..., + per_parent: int | None = ..., + ) -> None: ... + def then(self, *children: Load | ForeignKeyField[Any] | BackrefAccessor) -> Self: ... __all__ = [ "AnyField", @@ -2104,6 +2141,7 @@ __all__ = [ "IPField", "JOIN", "JSONField", + "Load", "ManyToManyField", "Model", "ModelIndex", diff --git a/python/helpers/typeshed/stubs/pika/@tests/stubtest_allowlist.txt b/python/helpers/typeshed/stubs/pika/@tests/stubtest_allowlist.txt index 30b2bf8aeb3c..260f43d685f2 100644 --- a/python/helpers/typeshed/stubs/pika/@tests/stubtest_allowlist.txt +++ b/python/helpers/typeshed/stubs/pika/@tests/stubtest_allowlist.txt @@ -1,3 +1,6 @@ +# bytes alias for Python 3 compatibility +pika.spec.str + # Behind a TYPE_CHECKING guard at runtime. pika.adapters.select_connection.SELECT_ERROR_T pika.adapters.select_connection.POLLER_PARAMS @@ -12,3 +15,29 @@ pika.connection.ConnectionParameters.T # Arguments have a sentinel default, which is not reflected in the stubs. pika.connection.ConnectionParameters.__init__ + +# These are defined as None, but on initialization are set as callable attributes. +pika.adapters.base_connection._StreamingProtocolShim.connection_made +pika.adapters.base_connection._StreamingProtocolShim.connection_lost +pika.adapters.base_connection._StreamingProtocolShim.eof_received +pika.adapters.base_connection._StreamingProtocolShim.data_received + +# The following methods are not defined directly on this class; +# they are resolved via __getattr__. +pika.adapters.base_connection._StreamingProtocolShim.add_on_close_callback +pika.adapters.base_connection._StreamingProtocolShim.add_on_connection_blocked_callback +pika.adapters.base_connection._StreamingProtocolShim.add_on_connection_unblocked_callback +pika.adapters.base_connection._StreamingProtocolShim.add_on_open_callback +pika.adapters.base_connection._StreamingProtocolShim.add_on_open_error_callback +pika.adapters.base_connection._StreamingProtocolShim.channel +pika.adapters.base_connection._StreamingProtocolShim.update_secret +pika.adapters.base_connection._StreamingProtocolShim.close +pika.adapters.base_connection._StreamingProtocolShim.is_closed +pika.adapters.base_connection._StreamingProtocolShim.is_closing +pika.adapters.base_connection._StreamingProtocolShim.is_open +pika.adapters.base_connection._StreamingProtocolShim.basic_nack +pika.adapters.base_connection._StreamingProtocolShim.consumer_cancel_notify +pika.adapters.base_connection._StreamingProtocolShim.exchange_exchange_bindings +pika.adapters.base_connection._StreamingProtocolShim.publisher_confirms +pika.adapters.base_connection._StreamingProtocolShim.create_connection +pika.adapters.base_connection._StreamingProtocolShim.ioloop diff --git a/python/helpers/typeshed/stubs/pika/METADATA.toml b/python/helpers/typeshed/stubs/pika/METADATA.toml index d1f0f47d68cd..87c644180e73 100644 --- a/python/helpers/typeshed/stubs/pika/METADATA.toml +++ b/python/helpers/typeshed/stubs/pika/METADATA.toml @@ -5,6 +5,7 @@ extra-description = """\ The `types-pika` package contains alternate, more complete type stubs, that \ are maintained outside of typeshed.\ """ +optional-dependencies = ["types-gevent"] [tool.stubtest] stubtest-dependencies = ["gevent", "tornado", "twisted"] diff --git a/python/helpers/typeshed/stubs/pika/pika/adapters/asyncio_connection.pyi b/python/helpers/typeshed/stubs/pika/pika/adapters/asyncio_connection.pyi index 3665ddc1a4f4..7789841db6a9 100644 --- a/python/helpers/typeshed/stubs/pika/pika/adapters/asyncio_connection.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/adapters/asyncio_connection.pyi @@ -1,25 +1,29 @@ +import asyncio from _typeshed import Incomplete -from asyncio import AbstractEventLoop, Future, Handle from collections.abc import Callable, Sequence from logging import Logger -from typing_extensions import Self -from ..connection import Connection, Parameters -from .base_connection import BaseConnection -from .utils import io_services_utils -from .utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException -from .utils.nbio_interface import AbstractFileDescriptorServices, AbstractIOReference, AbstractIOServices, AbstractTimerReference +from pika.adapters.base_connection import BaseConnection +from pika.adapters.utils import io_services_utils +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import ( + AbstractFileDescriptorServices, + AbstractIOReference, + AbstractIOServices, + AbstractTimerReference, +) +from pika.connection import Connection, Parameters LOGGER: Logger -class AsyncioConnection(BaseConnection): +class AsyncioConnection(BaseConnection[asyncio.AbstractEventLoop]): def __init__( self, parameters: Parameters | None = None, - on_open_callback: Callable[[Self], object] | None = None, - on_open_error_callback: Callable[[Self, BaseException], object] | None = None, - on_close_callback: Callable[[Self, BaseException], object] | None = None, - custom_ioloop: AbstractEventLoop | None = None, + on_open_callback: Callable[[Connection], object] | None = None, + on_open_error_callback: Callable[[Connection, BaseException], object] | None = None, + on_close_callback: Callable[[Connection, BaseException], object] | None = None, + custom_ioloop: asyncio.AbstractEventLoop | AbstractIOServices | None = None, internal_connection_workflow: bool = True, ) -> None: ... @classmethod @@ -27,7 +31,7 @@ class AsyncioConnection(BaseConnection): cls, connection_configs: Sequence[Parameters], on_done: Callable[[Connection | AMQPConnectorException], object], - custom_ioloop: AbstractEventLoop | None = None, + custom_ioloop: asyncio.AbstractEventLoop | None = None, workflow: AbstractAMQPConnectionWorkflow | None = None, ) -> AbstractAMQPConnectionWorkflow: ... @@ -37,8 +41,8 @@ class _AsyncioIOServicesAdapter( AbstractIOServices, AbstractFileDescriptorServices, ): - def __init__(self, loop: AbstractEventLoop | None = None) -> None: ... - def get_native_ioloop(self) -> AbstractEventLoop: ... + def __init__(self, loop: asyncio.AbstractEventLoop | None = None) -> None: ... + def get_native_ioloop(self) -> asyncio.AbstractEventLoop: ... def close(self) -> None: ... def run(self) -> None: ... def stop(self) -> None: ... @@ -46,9 +50,9 @@ class _AsyncioIOServicesAdapter( def call_later(self, delay: float, callback: Callable[[], object]) -> _TimerHandle: ... def getaddrinfo( self, - host: str, - port: int, - on_done: Callable[..., object], + host: str | bytes | None, + port: str | bytes | int | None, + on_done: Callable[[BaseConnection[asyncio.AbstractEventLoop] | BaseException], object], # type: ignore[override] family: int = 0, socktype: int = 0, proto: int = 0, @@ -60,9 +64,13 @@ class _AsyncioIOServicesAdapter( def remove_writer(self, fd: int) -> bool: ... class _TimerHandle(AbstractTimerReference): - def __init__(self, handle: Handle) -> None: ... + def __init__(self, handle: asyncio.Handle) -> None: ... def cancel(self) -> None: ... class _AsyncioIOReference(AbstractIOReference): - def __init__(self, future: Future[Incomplete], on_done: Callable[[BaseConnection | BaseException], object]) -> None: ... + def __init__( + self, + future: asyncio.Future[Incomplete], + on_done: Callable[[BaseConnection[asyncio.AbstractEventLoop] | BaseException], object], + ) -> None: ... def cancel(self) -> bool: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/adapters/base_connection.pyi b/python/helpers/typeshed/stubs/pika/pika/adapters/base_connection.pyi index 71468c334ed2..ab9b4dc94ac1 100644 --- a/python/helpers/typeshed/stubs/pika/pika/adapters/base_connection.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/adapters/base_connection.pyi @@ -1,35 +1,112 @@ import abc from _typeshed import Incomplete -from collections.abc import Callable +from collections.abc import Callable, Sequence from logging import Logger +from typing import Final, Generic, Literal, TypeVar from typing_extensions import Self -from ..adapters.utils.nbio_interface import AbstractIOServices, AbstractStreamProtocol -from ..connection import Connection, Parameters +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import AbstractIOServices, AbstractStreamProtocol, AbstractStreamTransport +from pika.callback import CallbackManager +from pika.channel import Channel +from pika.connection import Connection, Parameters +from pika.frame import Method +from pika.spec import Connection as SpecConnection LOGGER: Logger -class BaseConnection(Connection, metaclass=abc.ABCMeta): +_IOLoop = TypeVar("_IOLoop") + +class BaseConnection(Connection, Generic[_IOLoop], metaclass=abc.ABCMeta): def __init__( self, parameters: Parameters | None, - on_open_callback: Callable[[Self], object] | None, - on_open_error_callback: Callable[[Self, BaseException], object] | None, - on_close_callback: Callable[[Self, BaseException], object] | None, + on_open_callback: Callable[[Connection], object] | None, + on_open_error_callback: Callable[[Connection, BaseException], object] | None, + on_close_callback: Callable[[Connection, BaseException], object] | None, nbio: AbstractIOServices, internal_connection_workflow: bool = True, ) -> None: ... @classmethod @abc.abstractmethod - def create_connection(cls, connection_configs, on_done, custom_ioloop=None, workflow=None): ... + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Connection | AMQPConnectorException], object], + custom_ioloop: _IOLoop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... @property - def ioloop(self): ... + def ioloop(self) -> _IOLoop: ... -class _StreamingProtocolShim(AbstractStreamProtocol): - connection_made: Incomplete - connection_lost: Incomplete - eof_received: Incomplete - data_received: Incomplete - conn: Incomplete - def __init__(self, conn) -> None: ... - def __getattr__(self, attr: str): ... +class _StreamingProtocolShim(AbstractStreamProtocol, Generic[_IOLoop]): + conn: BaseConnection[_IOLoop] + def __init__(self, conn: BaseConnection[_IOLoop]) -> None: ... + # These are defined as None, but on initialization are set as callable attributes + def connection_made(self, transport: AbstractStreamTransport) -> None: ... + def connection_lost(self, error: BaseException | None) -> None: ... + def eof_received(self) -> bool: ... + def data_received(self, data: bytes) -> None: ... + + # Next attributes are accessed via getattr() from connection.Connection class: + ON_CONNECTION_CLOSED: Final = "_on_connection_closed" + ON_CONNECTION_ERROR: Final = "_on_connection_error" + ON_CONNECTION_OPEN_OK: Final = "_on_connection_open_ok" + CONNECTION_CLOSED: Final = 0 + CONNECTION_INIT: Final = 1 + CONNECTION_PROTOCOL: Final = 2 + CONNECTION_START: Final = 3 + CONNECTION_TUNE: Final = 4 + CONNECTION_OPEN: Final = 5 + CONNECTION_CLOSING: Final = 6 + connection_state: Literal[0, 1, 2, 3, 4, 5, 6] # one of the constants above + params: Parameters + callbacks: CallbackManager + server_capabilities: dict[str, bool] | None + server_properties: dict[str, Incomplete] | None + known_hosts: str | None + def add_on_close_callback(self, callback: Callable[[Self, BaseException], object]) -> None: ... + def add_on_connection_blocked_callback(self, callback: Callable[[Self, Method[SpecConnection.Blocked]], object]) -> None: ... + def add_on_connection_unblocked_callback( + self, callback: Callable[[Self, Method[SpecConnection.Unblocked]], object] + ) -> None: ... + def add_on_open_callback(self, callback: Callable[[Self], object]) -> None: ... + def add_on_open_error_callback( + self, callback: Callable[[Self, BaseException], object], remove_default: bool = True + ) -> None: ... + def channel( + self, channel_number: int | None = None, on_open_callback: Callable[[Channel], object] | None = None + ) -> Channel: ... + def update_secret( + self, + new_secret: str | bytes, + reason: str | bytes, + callback: Callable[[Method[SpecConnection.UpdateSecretOk]], object] | None = None, + ) -> None: ... + def close(self, reply_code: int = 200, reply_text: str = "Normal shutdown") -> None: ... + @property + def is_closed(self) -> bool: ... + @property + def is_closing(self) -> bool: ... + @property + def is_open(self) -> bool: ... + @property + def basic_nack(self) -> bool: ... + @property + def consumer_cancel_notify(self) -> bool: ... + @property + def exchange_exchange_bindings(self) -> bool: ... + @property + def publisher_confirms(self) -> bool: ... + + # Next attributes are accessed via getattr() from BaseConnection class: + @classmethod + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Connection | AMQPConnectorException], object], + custom_ioloop: _IOLoop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... + @property + def ioloop(self) -> _IOLoop: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/adapters/blocking_connection.pyi b/python/helpers/typeshed/stubs/pika/pika/adapters/blocking_connection.pyi index 9aabeb7befa8..5dd25332bacb 100644 --- a/python/helpers/typeshed/stubs/pika/pika/adapters/blocking_connection.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/adapters/blocking_connection.pyi @@ -1,79 +1,66 @@ -from _typeshed import Incomplete, Unused -from collections.abc import Callable, Generator, Sequence +from _typeshed import Incomplete +from collections import deque +from collections.abc import Callable, Generator, Mapping, Sequence from logging import Logger from types import TracebackType -from typing import Any, NamedTuple, TypeVar +from typing import Final, Generic, TypeVar, overload from typing_extensions import Self -from ..connection import Parameters -from ..exchange_type import ExchangeType -from ..frame import Method -from ..spec import Basic, BasicProperties, Connection, Exchange, Queue, Tx +from pika import connection +from pika.adapters.select_connection import SelectConnection +from pika.channel import Channel +from pika.exchange_type import ExchangeType +from pika.frame import Method +from pika.spec import Basic, BasicProperties, Connection, Exchange, Queue, Tx T = TypeVar("T", bound=Connection.Blocked | Connection.Unblocked) # noqa: Y001 LOGGER: Logger -class _CallbackResult: - __slots__ = ("_value_class", "_ready", "_values") - def __init__(self, value_class=None) -> None: ... - def reset(self) -> None: ... - def __bool__(self) -> bool: ... - __nonzero__: Incomplete - def __enter__(self): ... - def __exit__(self, *args: Unused, **kwargs: Unused) -> None: ... - def is_ready(self): ... - @property - def ready(self): ... - def signal_once(self, *_args, **_kwargs) -> None: ... - def set_value_once(self, *args, **kwargs) -> None: ... - def append_element(self, *args, **kwargs) -> None: ... - @property - def value(self): ... - @property - def elements(self): ... - class _IoloopTimerContext: - def __init__(self, duration, connection) -> None: ... - def __enter__(self): ... - def __exit__(self, *_args: Unused, **_kwargs: Unused) -> None: ... - def is_ready(self): ... - -class _TimerEvt: - __slots__ = ("timer_id", "_callback") - timer_id: Incomplete - def __init__(self, callback) -> None: ... - def dispatch(self) -> None: ... - -class _ConnectionBlockedUnblockedEvtBase: - __slots__ = ("_callback", "_method_frame") - def __init__(self, callback, method_frame) -> None: ... - def dispatch(self) -> None: ... - -class _ConnectionBlockedEvt(_ConnectionBlockedUnblockedEvtBase): ... -class _ConnectionUnblockedEvt(_ConnectionBlockedUnblockedEvtBase): ... - -class BlockingConnection: - class _OnClosedArgs(NamedTuple): - connection: Incomplete - error: Incomplete - - class _OnChannelOpenedArgs(NamedTuple): - channel: Incomplete - - def __init__(self, parameters: Parameters | Sequence[Parameters] | None = None, _impl_class=None) -> None: ... + def __init__(self, duration: float, connection: SelectConnection) -> None: ... def __enter__(self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... - def add_on_connection_blocked_callback(self, callback) -> None: ... - def add_on_connection_unblocked_callback(self, callback) -> None: ... - def call_later(self, delay, callback): ... - def add_callback_threadsafe(self, callback) -> None: ... - def remove_timeout(self, timeout_id) -> None: ... - def update_secret(self, new_secret, reason) -> None: ... + def is_ready(self) -> bool: ... + +class _TimerEvt: + __slots__ = ("timer_id", "_callback") + timer_id: object | None + def __init__(self, callback: Callable[[], None]) -> None: ... + def dispatch(self) -> None: ... + +class _ConnectionBlockedUnblockedEvtBase(Generic[T]): + __slots__ = ("_callback", "_method_frame") + def __init__(self, callback: Callable[[Method[T]], None], method_frame: Method[T]) -> None: ... + def dispatch(self) -> None: ... + +class _ConnectionBlockedEvt(_ConnectionBlockedUnblockedEvtBase[Connection.Blocked]): ... +class _ConnectionUnblockedEvt(_ConnectionBlockedUnblockedEvtBase[Connection.Unblocked]): ... + +class BlockingConnection: + def __init__( + self, + parameters: connection.Parameters | Sequence[connection.Parameters] | None = None, + _impl_class: SelectConnection | None = None, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None + ) -> None: ... + def add_on_connection_blocked_callback( + self, callback: Callable[[connection.Connection, Method[Connection.Blocked]], None] + ) -> None: ... + def add_on_connection_unblocked_callback( + self, callback: Callable[[connection.Connection, Method[Connection.Unblocked]], None] + ) -> None: ... + def call_later(self, delay: float, callback: Callable[[], None]) -> object: ... + def add_callback_threadsafe(self, callback: Callable[..., None]) -> None: ... + def remove_timeout(self, timeout_id: object) -> None: ... + def update_secret(self, new_secret: str, reason: str) -> None: ... def close(self, reply_code: int = 200, reply_text: str = "Normal shutdown") -> None: ... - def process_data_events(self, time_limit: int | None = 0) -> None: ... + def process_data_events(self, time_limit: float | None = 0) -> None: ... def sleep(self, duration: float) -> None: ... def channel(self, channel_number: int | None = None) -> BlockingChannel: ... @property @@ -97,127 +84,153 @@ class _ChannelPendingEvt: ... class _ConsumerDeliveryEvt(_ChannelPendingEvt): __slots__ = ("method", "properties", "body") - method: Incomplete - properties: Incomplete - body: Incomplete - def __init__(self, method, properties, body) -> None: ... + method: Basic.Deliver + properties: BasicProperties + body: bytes + def __init__(self, method: Basic.Deliver, properties: BasicProperties, body: bytes) -> None: ... class _ConsumerCancellationEvt(_ChannelPendingEvt): __slots__ = ("method_frame",) - method_frame: Incomplete - def __init__(self, method_frame) -> None: ... + method_frame: Method[Basic.Cancel] + def __init__(self, method_frame: Method[Basic.Cancel]) -> None: ... @property - def method(self): ... + def method(self) -> Basic.Cancel: ... class _ReturnedMessageEvt(_ChannelPendingEvt): __slots__ = ("callback", "channel", "method", "properties", "body") - callback: Incomplete - channel: Incomplete - method: Incomplete - properties: Incomplete - body: Incomplete - def __init__(self, callback, channel, method, properties, body) -> None: ... + callback: Callable[[BlockingChannel, Basic.Return, BasicProperties, bytes], None] + channel: BlockingChannel + method: Basic.Return + properties: BasicProperties + body: bytes + def __init__( + self, + callback: Callable[[BlockingChannel, Basic.Return, BasicProperties, bytes], None], + channel: BlockingChannel, + method: Basic.Return, + properties: BasicProperties, + body: bytes, + ) -> None: ... def dispatch(self) -> None: ... class ReturnedMessage: __slots__ = ("method", "properties", "body") - method: Incomplete - properties: Incomplete - body: Incomplete - def __init__(self, method, properties, body) -> None: ... + method: Basic.Return + properties: BasicProperties + body: bytes + def __init__(self, method: Basic.Return, properties: BasicProperties, body: bytes) -> None: ... class _ConsumerInfo: __slots__ = ("consumer_tag", "auto_ack", "on_message_callback", "alternate_event_sink", "state") - SETTING_UP: int - ACTIVE: int - TEARING_DOWN: int - CANCELLED_BY_BROKER: int - consumer_tag: Incomplete - auto_ack: Incomplete - on_message_callback: Incomplete - alternate_event_sink: Incomplete - state: Incomplete - def __init__(self, consumer_tag, auto_ack, on_message_callback=None, alternate_event_sink=None) -> None: ... + SETTING_UP: Final = 1 + ACTIVE: Final = 2 + TEARING_DOWN: Final = 3 + CANCELLED_BY_BROKER: Final = 4 + consumer_tag: str + auto_ack: bool + on_message_callback: Callable[[BlockingChannel, Basic.Deliver, BasicProperties, bytes], None] | None + alternate_event_sink: Callable[[_ChannelPendingEvt], None] | None + state: int + + @overload + def __init__( + self, + consumer_tag: str, + auto_ack: bool, + # Only one of them must be non-None: + on_message_callback: Callable[[BlockingChannel, Basic.Deliver, BasicProperties, bytes], None], + alternate_event_sink: None = None, + ) -> None: ... + @overload + def __init__( + self, + consumer_tag: str, + auto_ack: bool, + # Only one of them must be non-None: + on_message_callback: None = None, + alternate_event_sink: Callable[[_ChannelPendingEvt], None] = ..., + ) -> None: ... + @property - def setting_up(self): ... + def setting_up(self) -> bool: ... @property - def active(self): ... + def active(self) -> bool: ... @property - def tearing_down(self): ... + def tearing_down(self) -> bool: ... @property - def cancelled_by_broker(self): ... + def cancelled_by_broker(self) -> bool: ... class _QueueConsumerGeneratorInfo: __slots__ = ("params", "consumer_tag", "pending_events") - params: Incomplete - consumer_tag: Incomplete - pending_events: Incomplete - def __init__(self, params, consumer_tag) -> None: ... + params: tuple[str, bool, bool] + consumer_tag: str + pending_events: deque[_ChannelPendingEvt] + def __init__(self, params: tuple[str, bool, bool], consumer_tag: str) -> None: ... class BlockingChannel: - class _RxMessageArgs(NamedTuple): - channel: Incomplete - method: Incomplete - properties: Incomplete - body: Incomplete - - class _MethodFrameCallbackResultArgs(NamedTuple): - method_frame: Incomplete - - class _OnMessageConfirmationReportArgs(NamedTuple): - method_frame: Incomplete - - class _FlowOkCallbackResultArgs(NamedTuple): - active: Incomplete - - def __init__(self, channel_impl, connection) -> None: ... + def __init__(self, channel_impl: Channel, connection: BlockingConnection) -> None: ... def __int__(self) -> int: ... - def __enter__(self): ... + def __enter__(self) -> Self: ... def __exit__( self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... @property - def channel_number(self): ... + def channel_number(self) -> int: ... @property - def connection(self): ... + def connection(self) -> BlockingConnection: ... @property - def is_closed(self): ... + def is_closed(self) -> bool: ... @property - def is_open(self): ... + def is_open(self) -> bool: ... @property - def consumer_tags(self): ... - def close(self, reply_code: int = 0, reply_text: str = "Normal shutdown"): ... - def flow(self, active): ... - def add_on_cancel_callback(self, callback) -> None: ... - def add_on_return_callback(self, callback): ... + def consumer_tags(self) -> list[str]: ... + def close(self, reply_code: int = 0, reply_text: str = "Normal shutdown") -> None: ... + def flow(self, active: bool) -> bool: ... + def add_on_cancel_callback(self, callback: Callable[[Method[Basic.Cancel]], None]) -> None: ... + def add_on_return_callback( + self, callback: Callable[[BlockingChannel, Basic.Return, BasicProperties, bytes], None] + ) -> None: ... def basic_consume( self, queue: str, - on_message_callback: Callable[[BlockingChannel, Basic.Deliver, BasicProperties, bytes], object], + on_message_callback: Callable[[BlockingChannel, Basic.Deliver, BasicProperties, bytes], None], auto_ack: bool = False, exclusive: bool = False, consumer_tag: str | None = None, - arguments: dict[str, Any] | None = None, + arguments: Mapping[str, Incomplete] | None = None, ) -> str: ... - def basic_cancel(self, consumer_tag: str) -> Sequence[tuple[Basic.Deliver, BasicProperties, bytes]]: ... + def basic_cancel(self, consumer_tag: str) -> list[tuple[Basic.Deliver, BasicProperties, bytes]]: ... def start_consuming(self) -> None: ... def stop_consuming(self, consumer_tag: str | None = None) -> None: ... + + @overload def consume( self, queue: str, auto_ack: bool = False, exclusive: bool = False, - arguments: dict[str, Any] | None = None, - inactivity_timeout: float | None = None, + arguments: Mapping[str, Incomplete] | None = None, + inactivity_timeout: None = None, # different between overloads consumer_tag: str | None = None, - ) -> Generator[tuple[Basic.Deliver | None, BasicProperties | None, bytes | None]]: ... + ) -> Generator[tuple[Basic.Deliver, BasicProperties, bytes]]: ... + @overload + def consume( + self, + queue: str, + auto_ack: bool = False, + exclusive: bool = False, + arguments: Mapping[str, Incomplete] | None = None, + inactivity_timeout: float = ..., # different between overloads + consumer_tag: str | None = None, + ) -> Generator[tuple[Basic.Deliver, BasicProperties, bytes] | tuple[None, None, None]]: ... + def get_waiting_message_count(self) -> int: ... def cancel(self) -> int: ... def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None: ... def basic_nack(self, delivery_tag: int = 0, multiple: bool = False, requeue: bool = True) -> None: ... def basic_get( self, queue: str, auto_ack: bool = False - ) -> tuple[Basic.GetOk | None, BasicProperties | None, bytes | None]: ... + ) -> tuple[Basic.GetOk, BasicProperties, bytes] | tuple[None, None, None]: ... def basic_publish( self, exchange: str, @@ -238,18 +251,18 @@ class BlockingChannel: durable: bool = False, auto_delete: bool = False, internal: bool = False, - arguments: dict[str, Any] | None = None, + arguments: Mapping[str, Incomplete] | None = None, ) -> None: ... def exchange_delete(self, exchange: str | None = None, if_unused: bool = False) -> Method[Exchange.DeleteOk]: ... def exchange_bind( - self, destination: str, source: str, routing_key: str = "", arguments: dict[str, Any] | None = None + self, destination: str, source: str, routing_key: str = "", arguments: Mapping[str, Incomplete] | None = None ) -> Method[Exchange.BindOk]: ... def exchange_unbind( self, destination: str | None = None, source: str | None = None, routing_key: str = "", - arguments: dict[str, Any] | None = None, + arguments: Mapping[str, Incomplete] | None = None, ) -> Method[Exchange.UnbindOk]: ... def queue_declare( self, @@ -258,15 +271,15 @@ class BlockingChannel: durable: bool = False, exclusive: bool = False, auto_delete: bool = False, - arguments: dict[str, Any] | None = None, + arguments: Mapping[str, Incomplete] | None = None, ) -> Method[Queue.DeclareOk]: ... def queue_delete(self, queue: str, if_unused: bool = False, if_empty: bool = False) -> Method[Queue.DeleteOk]: ... def queue_purge(self, queue: str) -> Method[Queue.PurgeOk]: ... def queue_bind( - self, queue: str, exchange: str, routing_key: str | None = None, arguments: dict[str, Any] | None = None + self, queue: str, exchange: str, routing_key: str | None = None, arguments: Mapping[str, Incomplete] | None = None ) -> Method[Queue.BindOk]: ... def queue_unbind( - self, queue: str, exchange: str, routing_key: str | None = None, arguments: dict[str, Any] | None = None + self, queue: str, exchange: str, routing_key: str | None = None, arguments: Mapping[str, Incomplete] | None = None ) -> Method[Queue.UnbindOk]: ... def tx_select(self) -> Method[Tx.SelectOk]: ... def tx_commit(self) -> Method[Tx.CommitOk]: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/adapters/gevent_connection.pyi b/python/helpers/typeshed/stubs/pika/pika/adapters/gevent_connection.pyi index ab30dd6c4f83..1f323796d6c1 100644 --- a/python/helpers/typeshed/stubs/pika/pika/adapters/gevent_connection.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/adapters/gevent_connection.pyi @@ -1,55 +1,92 @@ +from collections.abc import Callable, Sequence from logging import Logger +from typing import Final +from gevent._types import _Loop, _TimerWatcher +from gevent.hub import Hub from pika.adapters.base_connection import BaseConnection -from pika.adapters.utils.nbio_interface import AbstractIOReference -from pika.adapters.utils.selector_ioloop_adapter import AbstractSelectorIOLoop, SelectorIOServicesAdapter +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import AbstractIOReference, AbstractIOServices +from pika.adapters.utils.selector_ioloop_adapter import AbstractSelectorIOLoop, SelectorIOServicesAdapter, _SupportsCancel +from pika.connection import Connection, Parameters LOGGER: Logger -class GeventConnection(BaseConnection): +class GeventConnection(BaseConnection[_Loop]): def __init__( self, - parameters=None, - on_open_callback=None, - on_open_error_callback=None, - on_close_callback=None, - custom_ioloop=None, + parameters: Parameters | None = None, + on_open_callback: Callable[[Connection], object] | None = None, + on_open_error_callback: Callable[[Connection, BaseException], object] | None = None, + on_close_callback: Callable[[Connection, BaseException], object] | None = None, + custom_ioloop: _Loop | AbstractIOServices | None = None, internal_connection_workflow: bool = True, ) -> None: ... @classmethod - def create_connection(cls, connection_configs, on_done, custom_ioloop=None, workflow=None): ... + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Connection | AMQPConnectorException], object], + custom_ioloop: _Loop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... class _TSafeCallbackQueue: def __init__(self) -> None: ... @property - def fd(self): ... - def add_callback_threadsafe(self, callback) -> None: ... + def fd(self) -> int: ... + def add_callback_threadsafe(self, callback: Callable[[], None]) -> None: ... def run_next_callback(self) -> None: ... -class _GeventSelectorIOLoop(AbstractSelectorIOLoop): - READ: int - WRITE: int - ERROR: int - def __init__(self, gevent_hub=None) -> None: ... +class _GeventSelectorIOLoop(AbstractSelectorIOLoop[_TimerWatcher]): + READ: Final[int] + WRITE: Final[int] + ERROR: Final[int] + def __init__(self, gevent_hub: Hub | None = None) -> None: ... def close(self) -> None: ... def start(self) -> None: ... def stop(self) -> None: ... - def add_callback(self, callback) -> None: ... - def call_later(self, delay, callback): ... - def remove_timeout(self, timeout_handle) -> None: ... - def add_handler(self, fd, handler, events) -> None: ... - def update_handler(self, fd, events) -> None: ... - def remove_handler(self, fd) -> None: ... + def add_callback(self, callback: Callable[[], object]) -> None: ... + def call_later(self, delay: float, callback: Callable[[], object]) -> _TimerWatcher: ... + def remove_timeout(self, timeout_handle: _TimerWatcher) -> None: ... + def add_handler(self, fd: int, handler: Callable[[int, int], None], events: int) -> None: ... + def update_handler(self, fd: int, events: int) -> None: ... + def remove_handler(self, fd: int) -> None: ... class _GeventSelectorIOServicesAdapter(SelectorIOServicesAdapter): - def getaddrinfo(self, host, port, on_done, family: int = 0, socktype: int = 0, proto: int = 0, flags: int = 0): ... + def getaddrinfo( + self, + host: str | bytes | None, + port: str | bytes | int | None, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + family: int = 0, + socktype: int = 0, + proto: int = 0, + flags: int = 0, + ) -> AbstractIOReference: ... class _GeventIOLoopIOHandle(AbstractIOReference): - def __init__(self, subject) -> None: ... - def cancel(self): ... + def __init__(self, subject: _SupportsCancel) -> None: ... + def cancel(self) -> bool: ... class _GeventAddressResolver: __slots__ = ("_loop", "_on_done", "_greenlet", "_ga_host", "_ga_port", "_ga_family", "_ga_socktype", "_ga_proto", "_ga_flags") - def __init__(self, native_loop, host, port, family, socktype, proto, flags, on_done) -> None: ... + def __init__( + self, + native_loop: AbstractSelectorIOLoop, + host: str | bytes | None, + port: str | bytes | int | None, + family: int, + socktype: int, + proto: int, + flags: int, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + ) -> None: ... def start(self) -> None: ... - def cancel(self): ... + def cancel(self) -> bool: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/adapters/select_connection.pyi b/python/helpers/typeshed/stubs/pika/pika/adapters/select_connection.pyi index 86ef12c83e88..d1309477191c 100644 --- a/python/helpers/typeshed/stubs/pika/pika/adapters/select_connection.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/adapters/select_connection.pyi @@ -1,54 +1,62 @@ import abc import select -from _typeshed import Incomplete -from collections.abc import Callable +from collections.abc import Callable, Sequence from logging import Logger -from typing import Final, Literal, TypeAlias, TypedDict +from typing import ClassVar, Final, Literal, TypeAlias, TypedDict import pika.compat from pika.adapters.base_connection import BaseConnection +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import AbstractIOServices from pika.adapters.utils.selector_ioloop_adapter import AbstractSelectorIOLoop +from pika.connection import Connection, Parameters -SELECT_ERROR_T: TypeAlias = OSError | InterruptedError | select.error +SELECT_ERROR_T: TypeAlias = OSError | IOError | InterruptedError | select.error class POLLER_PARAMS(TypedDict): get_wait_seconds: Callable[[], float | None] - process_timeouts: Callable[[], object] + process_timeouts: Callable[[], None] LOGGER: Logger SELECT_TYPE: Literal["epoll", "kqueue", "poll"] | None -class SelectConnection(BaseConnection): +class SelectConnection(BaseConnection[IOLoop]): def __init__( self, - parameters=None, - on_open_callback=None, - on_open_error_callback=None, - on_close_callback=None, - custom_ioloop=None, + parameters: Parameters | None = None, + on_open_callback: Callable[[Connection], object] | None = None, + on_open_error_callback: Callable[[Connection, BaseException], object] | None = None, + on_close_callback: Callable[[Connection, BaseException], object] | None = None, + custom_ioloop: IOLoop | AbstractIOServices | None = None, internal_connection_workflow: bool = True, ) -> None: ... @classmethod - def create_connection(cls, connection_configs, on_done, custom_ioloop=None, workflow=None): ... + def create_connection( + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Connection | AMQPConnectorException], object], + custom_ioloop: IOLoop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... class _Timeout: __slots__ = ("deadline", "callback") - deadline: Incomplete - callback: Incomplete - def __init__(self, deadline, callback) -> None: ... - def __eq__(self, other): ... - def __ne__(self, other): ... - def __lt__(self, other): ... - def __gt__(self, other): ... - def __le__(self, other): ... - def __ge__(self, other): ... + deadline: float + callback: Callable[[], None] + def __init__(self, deadline: float, callback: Callable[[], None]) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: object) -> bool: ... + def __gt__(self, other: object) -> bool: ... + def __le__(self, other: object) -> bool: ... + def __ge__(self, other: object) -> bool: ... class _Timer: def __init__(self) -> None: ... def close(self) -> None: ... - def call_later(self, delay, callback): ... - def remove_timeout(self, timeout) -> None: ... - def get_remaining_interval(self): ... + def call_later(self, delay: float, callback: Callable[[], None]) -> _Timeout: ... + def remove_timeout(self, timeout: _Timeout) -> None: ... + def get_remaining_interval(self) -> float | None: ... def process_timeouts(self) -> None: ... class PollEvents: @@ -57,20 +65,20 @@ class PollEvents: ERROR: Final[int] HANGUP: Final[int] -class IOLoop(AbstractSelectorIOLoop): - READ: Incomplete - WRITE: Incomplete - ERROR: Incomplete +class IOLoop(AbstractSelectorIOLoop[_Timeout]): + READ: Final[int] + WRITE: Final[int] + ERROR: Final[int] def __init__(self) -> None: ... def close(self) -> None: ... - def call_later(self, delay, callback): ... - def remove_timeout(self, timeout_handle) -> None: ... - def add_callback_threadsafe(self, callback) -> None: ... - add_callback: Incomplete + def call_later(self, delay: float, callback: Callable[[], object]) -> _Timeout: ... + def remove_timeout(self, timeout_handle: _Timeout) -> None: ... + def add_callback_threadsafe(self, callback: Callable[[], object]) -> None: ... + add_callback = add_callback_threadsafe def process_timeouts(self) -> None: ... - def add_handler(self, fd, handler, events) -> None: ... - def update_handler(self, fd, events) -> None: ... - def remove_handler(self, fd) -> None: ... + def add_handler(self, fd: int, handler: Callable[[int, int], None], events: int) -> None: ... + def update_handler(self, fd: int, events: int) -> None: ... + def remove_handler(self, fd: int) -> None: ... def start(self) -> None: ... def stop(self) -> None: ... def activate_poller(self) -> None: ... @@ -78,32 +86,32 @@ class IOLoop(AbstractSelectorIOLoop): def poll(self) -> None: ... class _PollerBase(pika.compat.AbstractBase, metaclass=abc.ABCMeta): - POLL_TIMEOUT_MULT: int - def __init__(self, get_wait_seconds, process_timeouts) -> None: ... + POLL_TIMEOUT_MULT: ClassVar[int] + def __init__(self, get_wait_seconds: Callable[[], float | None], process_timeouts: Callable[[], None]) -> None: ... def close(self) -> None: ... def wake_threadsafe(self) -> None: ... - def add_handler(self, fileno, handler, events) -> None: ... - def update_handler(self, fileno, events) -> None: ... - def remove_handler(self, fileno) -> None: ... + def add_handler(self, fileno: int, handler: Callable[[int, int], None], events: int) -> None: ... + def update_handler(self, fileno: int, events: int) -> None: ... + def remove_handler(self, fileno: int) -> None: ... def activate_poller(self) -> None: ... def deactivate_poller(self) -> None: ... def start(self) -> None: ... def stop(self) -> None: ... @abc.abstractmethod - def poll(self): ... + def poll(self) -> None: ... class SelectPoller(_PollerBase): - POLL_TIMEOUT_MULT: int + POLL_TIMEOUT_MULT: ClassVar[int] def poll(self) -> None: ... class KQueuePoller(_PollerBase): - def __init__(self, get_wait_seconds, process_timeouts) -> None: ... + def __init__(self, get_wait_seconds: Callable[[], float | None], process_timeouts: Callable[[], None]) -> None: ... def poll(self) -> None: ... class PollPoller(_PollerBase): - POLL_TIMEOUT_MULT: int - def __init__(self, get_wait_seconds, process_timeouts) -> None: ... + POLL_TIMEOUT_MULT: ClassVar[int] + def __init__(self, get_wait_seconds: Callable[[], float | None], process_timeouts: Callable[[], None]) -> None: ... def poll(self) -> None: ... class EPollPoller(PollPoller): - POLL_TIMEOUT_MULT: int + POLL_TIMEOUT_MULT: ClassVar[int] diff --git a/python/helpers/typeshed/stubs/pika/pika/adapters/tornado_connection.pyi b/python/helpers/typeshed/stubs/pika/pika/adapters/tornado_connection.pyi index 9207ef355d0e..31ac6c9518d9 100644 --- a/python/helpers/typeshed/stubs/pika/pika/adapters/tornado_connection.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/adapters/tornado_connection.pyi @@ -1,21 +1,32 @@ from _typeshed import Incomplete +from collections.abc import Callable, Sequence from logging import Logger +from typing import TypeAlias -from pika.adapters import base_connection +from pika.adapters.base_connection import BaseConnection +from pika.adapters.utils.connection_workflow import AbstractAMQPConnectionWorkflow, AMQPConnectorException +from pika.adapters.utils.nbio_interface import AbstractIOServices +from pika.connection import Connection, Parameters + +_IOLoop: TypeAlias = Incomplete # actual type is tornado.ioloop.IOLoop LOGGER: Logger -class TornadoConnection(base_connection.BaseConnection): +class TornadoConnection(BaseConnection[_IOLoop]): def __init__( self, - parameters: Incomplete | None = ..., - on_open_callback: Incomplete | None = ..., - on_open_error_callback: Incomplete | None = ..., - on_close_callback: Incomplete | None = ..., - custom_ioloop: Incomplete | None = ..., - internal_connection_workflow: bool = ..., + parameters: Parameters | None = None, + on_open_callback: Callable[[Connection], object] | None = None, + on_open_error_callback: Callable[[Connection, BaseException], object] | None = None, + on_close_callback: Callable[[Connection, BaseException], object] | None = None, + custom_ioloop: _IOLoop | AbstractIOServices | None = None, + internal_connection_workflow: bool = True, ) -> None: ... @classmethod def create_connection( - cls, connection_configs, on_done, custom_ioloop: Incomplete | None = ..., workflow: Incomplete | None = ... - ): ... + cls, + connection_configs: Sequence[Parameters], + on_done: Callable[[Connection | AMQPConnectorException], object], + custom_ioloop: _IOLoop | None = None, + workflow: AbstractAMQPConnectionWorkflow | None = None, + ) -> AbstractAMQPConnectionWorkflow: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/adapters/twisted_connection.pyi b/python/helpers/typeshed/stubs/pika/pika/adapters/twisted_connection.pyi index 9d8d90ef333e..204fc2d61603 100644 --- a/python/helpers/typeshed/stubs/pika/pika/adapters/twisted_connection.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/adapters/twisted_connection.pyi @@ -2,12 +2,20 @@ # We don't want to force it as a dependency but that means we also can't test it with type-checkers given the current setup. from _typeshed import Incomplete -from collections.abc import Callable +from collections.abc import Callable, Iterable, Mapping from logging import Logger -from typing import Any, Generic, NamedTuple, TypeVar +from typing import Generic, NamedTuple, TypeVar +from pika import amqp_object from pika.adapters.utils.nbio_interface import AbstractTimerReference -from twisted.internet.base import DelayedCall # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] +from pika.channel import Channel +from pika.connection import Connection, ConnectionParameters, Parameters +from pika.exchange_type import ExchangeType +from pika.spec import BasicProperties +from twisted.internet.base import ( # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] + DelayedCall, + ReactorBase, +) from twisted.internet.defer import ( # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] Deferred, DeferredQueue, @@ -16,107 +24,110 @@ from twisted.internet.interfaces import ITransport # type: ignore[import-not-fo from twisted.internet.protocol import Protocol # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] from twisted.python.failure import Failure # type: ignore[import-not-found] # pyright: ignore[reportMissingImports] -from ..connection import Connection, Parameters +LOGGER: Logger _T = TypeVar("_T") -LOGGER: Logger - class ClosableDeferredQueue(DeferredQueue[_T], Generic[_T]): # pyright: ignore[reportUntypedBaseClass] # noqa: Y060 closed: Failure | BaseException | None - def __init__(self, size: Incomplete | None = ..., backlog: Incomplete | None = ...) -> None: ... + def __init__(self, size: int | None = None, backlog: int | None = None) -> None: ... # Returns a Deferred with an error if fails. None if success def put(self, obj: _T) -> Deferred[Failure | BaseException] | None: ... # type: ignore[override] # ignore is not needed for mypy, but is for stubtest def get(self) -> Deferred[Failure | BaseException | _T]: ... # type: ignore[override] # ignore is not needed for mypy, but is for stubtest - pending: Incomplete - def close(self, reason: BaseException | None) -> None: ... + pending: list[_T] + def close(self, reason: Failure | BaseException | None) -> None: ... class ReceivedMessage(NamedTuple): - channel: Incomplete - method: Incomplete - properties: Incomplete - body: Incomplete + channel: TwistedChannel + method: amqp_object.Method + properties: BasicProperties + body: bytes class TwistedChannel: on_closed: Deferred[Incomplete | Failure | BaseException | None] - def __init__(self, channel) -> None: ... + def __init__(self, channel: Channel) -> None: ... @property - def channel_number(self): ... + def channel_number(self) -> int: ... @property - def connection(self): ... + def connection(self) -> Connection: ... @property - def is_closed(self): ... + def is_closed(self) -> bool: ... @property - def is_closing(self): ... + def is_closing(self) -> bool: ... @property - def is_open(self): ... + def is_open(self) -> bool: ... @property - def flow_active(self): ... + def flow_active(self) -> bool: ... @property - def consumer_tags(self): ... - def callback_deferred(self, deferred, replies) -> None: ... - def add_on_return_callback(self, callback): ... - def basic_ack(self, delivery_tag: int = ..., multiple: bool = ...): ... - def basic_cancel(self, consumer_tag: str = ...) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def consumer_tags(self) -> list[str]: ... + def callback_deferred(self, deferred: Deferred[Incomplete], replies: Iterable[Incomplete]) -> None: ... + def add_on_return_callback(self, callback: Callable[[ReceivedMessage], None]) -> None: ... + def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None: ... + def basic_cancel(self, consumer_tag: str = "") -> Deferred[Incomplete | Failure | BaseException | None]: ... def basic_consume( self, - queue, - auto_ack: bool = ..., - exclusive: bool = ..., - consumer_tag: Incomplete | None = ..., - arguments: Incomplete | None = ..., + queue: str, + auto_ack: bool = False, + exclusive: bool = False, + consumer_tag: str | None = None, + arguments: Mapping[str, Incomplete] | None = None, ) -> Deferred[Incomplete | Failure | BaseException]: ... - def basic_get(self, queue, auto_ack: bool = ...) -> Deferred[Incomplete | Failure | BaseException | None]: ... - def basic_nack(self, delivery_tag: Incomplete | None = ..., multiple: bool = ..., requeue: bool = ...): ... + def basic_get(self, queue: str, auto_ack: bool = False) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def basic_nack(self, delivery_tag: int = 0, multiple: bool = False, requeue: bool = True) -> None: ... def basic_publish( - self, exchange, routing_key, body, properties: Incomplete | None = ..., mandatory: bool = ... + self, + exchange: str, + routing_key: str, + body: str | bytes, + properties: BasicProperties | None = None, + mandatory: bool = False, ) -> Deferred[Incomplete | Failure | BaseException]: ... def basic_qos( - self, prefetch_size: int = ..., prefetch_count: int = ..., global_qos: bool = ... + self, prefetch_size: int = 0, prefetch_count: int = 0, global_qos: bool = False ) -> Deferred[Incomplete | Failure | BaseException | None]: ... - def basic_reject(self, delivery_tag, requeue: bool = ...): ... - def basic_recover(self, requeue: bool = ...) -> Deferred[Incomplete | Failure | BaseException | None]: ... - def close(self, reply_code: int = ..., reply_text: str = ...): ... + def basic_reject(self, delivery_tag: int, requeue: bool = True): ... + def basic_recover(self, requeue: bool = False) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def close(self, reply_code: int = 0, reply_text: str = "Normal shutdown"): ... def confirm_delivery(self) -> Deferred[Incomplete | None]: ... def exchange_bind( - self, destination, source, routing_key: str = ..., arguments: Incomplete | None = ... + self, destination: str, source: str, routing_key: str = "", arguments: Mapping[str, Incomplete] | None = None ) -> Deferred[Incomplete | Failure | BaseException | None]: ... def exchange_declare( self, exchange, - exchange_type=..., - passive: bool = ..., - durable: bool = ..., - auto_delete: bool = ..., - internal: bool = ..., - arguments: Incomplete | None = ..., + exchange_type: str | ExchangeType = ..., + passive: bool = False, + durable: bool = False, + auto_delete: bool = False, + internal: bool = False, + arguments: Mapping[str, Incomplete] | None = None, ) -> Deferred[Incomplete | Failure | BaseException | None]: ... def exchange_delete( - self, exchange: Incomplete | None = ..., if_unused: bool = ... + self, exchange: str | None = None, if_unused: bool = False ) -> Deferred[Incomplete | Failure | BaseException | None]: ... def exchange_unbind( - self, destination: str, source: str, routing_key: str = "", arguments: dict[str, Any] | None = None + self, destination: str, source: str, routing_key: str = "", arguments: Mapping[str, Incomplete] | None = None ) -> Deferred[Incomplete | Failure | BaseException | None]: ... def flow(self, active: bool = True) -> Deferred[Incomplete | Failure | BaseException | None]: ... def open(self): ... def queue_bind( - self, queue, exchange, routing_key: Incomplete | None = ..., arguments: Incomplete | None = ... + self, queue: str, exchange: str, routing_key: str | None = None, arguments: Mapping[str, Incomplete] | None = None ) -> Deferred[Incomplete | Failure | BaseException | None]: ... def queue_declare( self, - queue, - passive: bool = ..., - durable: bool = ..., - exclusive: bool = ..., - auto_delete: bool = ..., - arguments: Incomplete | None = ..., + queue: str, + passive: bool = False, + durable: bool = False, + exclusive: bool = False, + auto_delete: bool = False, + arguments: Mapping[str, Incomplete] | None = None, ) -> Deferred[Incomplete | Failure | BaseException | None]: ... def queue_delete( - self, queue, if_unused: bool = ..., if_empty: bool = ... + self, queue: str, if_unused: bool = False, if_empty: bool = False ) -> Deferred[Incomplete | Failure | BaseException | None]: ... - def queue_purge(self, queue) -> Deferred[Incomplete | Failure | BaseException | None]: ... + def queue_purge(self, queue: str) -> Deferred[Incomplete | Failure | BaseException | None]: ... def queue_unbind( - self, queue: str, exchange: str | None, routing_key: str | None = None, arguments: dict[str, Any] | None = None + self, queue: str, exchange: str | None, routing_key: str | None = None, arguments: Mapping[str, Incomplete] | None = None ) -> Deferred[Incomplete | Failure | BaseException | None]: ... def tx_commit(self) -> Deferred[Incomplete | Failure | BaseException | None]: ... def tx_rollback(self) -> Deferred[Incomplete | Failure | BaseException | None]: ... @@ -127,28 +138,30 @@ class _TwistedConnectionAdapter(Connection): self, parameters: Parameters | None, on_open_callback: Callable[[Connection], object] | None, - on_open_error_callback: Callable[[Connection, Exception], object] | None, + on_open_error_callback: Callable[[Connection, BaseException], object] | None, on_close_callback: Callable[[Connection, Exception], object] | None, - custom_reactor=None, + custom_reactor: ReactorBase | None = None, ) -> None: ... def connection_made(self, transport: ITransport) -> None: ... def connection_lost(self, error: Exception) -> None: ... - def data_received(self, data) -> None: ... + def data_received(self, data: bytes) -> None: ... class TwistedProtocolConnection(Protocol): # pyright: ignore[reportUntypedBaseClass] ready: Deferred[None] | None closed: Deferred[None] | Failure | BaseException | None - def __init__(self, parameters: Incomplete | None = ..., custom_reactor: Incomplete | None = ...) -> None: ... - def channel(self, channel_number: Incomplete | None = ...): ... + def __init__(self, parameters: ConnectionParameters | None = None, custom_reactor: ReactorBase | None = None) -> None: ... + def channel(self, channel_number: int | None = None) -> Deferred[TwistedChannel]: ... @property - def is_open(self): ... + def is_open(self) -> bool: ... @property - def is_closed(self): ... - def close(self, reply_code: int = ..., reply_text: str = ...) -> Deferred[None] | Failure | BaseException | None: ... - def dataReceived(self, data) -> None: ... + def is_closed(self) -> bool: ... + def close( + self, reply_code: int = 200, reply_text: str = "Normal shutdown" + ) -> Deferred[None] | Failure | BaseException | None: ... + def dataReceived(self, data: bytes) -> None: ... def connectionLost(self, reason: Failure | BaseException = ...) -> None: ... def makeConnection(self, transport: ITransport) -> None: ... - def connectionReady(self): ... + def connectionReady(self) -> TwistedProtocolConnection | Deferred[TwistedProtocolConnection]: ... class _TimerHandle(AbstractTimerReference): def __init__(self, handle: DelayedCall) -> None: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/adapters/utils/connection_workflow.pyi b/python/helpers/typeshed/stubs/pika/pika/adapters/utils/connection_workflow.pyi index 1adf533f8ce9..a2284221bde8 100644 --- a/python/helpers/typeshed/stubs/pika/pika/adapters/utils/connection_workflow.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/adapters/utils/connection_workflow.pyi @@ -1,6 +1,9 @@ from _typeshed import Incomplete +from collections.abc import Callable, Iterable, Sequence import pika.compat +import pika.connection +from pika.adapters.utils.nbio_interface import AbstractIOServices, AbstractStreamProtocol class AMQPConnectorException(Exception): ... class AMQPConnectorStackTimeout(AMQPConnectorException): ... @@ -8,8 +11,8 @@ class AMQPConnectorAborted(AMQPConnectorException): ... class AMQPConnectorWrongState(AMQPConnectorException): ... class AMQPConnectorPhaseErrorBase(AMQPConnectorException): - exception: Incomplete - def __init__(self, exception, *args) -> None: ... + exception: BaseException + def __init__(self, exception: BaseException, *args: object) -> None: ... class AMQPConnectorSocketConnectError(AMQPConnectorPhaseErrorBase): ... class AMQPConnectorTransportSetupError(AMQPConnectorPhaseErrorBase): ... @@ -18,20 +21,41 @@ class AMQPConnectionWorkflowAborted(AMQPConnectorException): ... class AMQPConnectionWorkflowWrongState(AMQPConnectorException): ... class AMQPConnectionWorkflowFailed(AMQPConnectorException): - exceptions: Incomplete - def __init__(self, exceptions, *args) -> None: ... + exceptions: tuple[BaseException, ...] + def __init__(self, exceptions: Iterable[BaseException], *args: object) -> None: ... class AMQPConnector: - def __init__(self, conn_factory, nbio) -> None: ... - def start(self, addr_record, conn_params, on_done) -> None: ... + def __init__( + self, conn_factory: Callable[[pika.connection.Parameters], AbstractStreamProtocol], nbio: AbstractIOServices + ) -> None: ... + def start( + self, + addr_record: tuple[ # tuple taken result of socket.getaddrinfo + int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes] + ], + conn_params: pika.connection.Parameters, + on_done: Callable[[pika.connection.Connection | BaseException], None], + ) -> None: ... def abort(self) -> None: ... class AbstractAMQPConnectionWorkflow(pika.compat.AbstractBase): - def start(self, connection_configs, connector_factory, native_loop, on_done) -> None: ... + def start( + self, + connection_configs: Sequence[pika.connection.Parameters], + connector_factory: Callable[..., Incomplete], + native_loop, + on_done: Callable[[pika.connection.Connection | AMQPConnectorException], None], + ) -> None: ... def abort(self) -> None: ... class AMQPConnectionWorkflow(AbstractAMQPConnectionWorkflow): def __init__(self, _until_first_amqp_attempt: bool = False) -> None: ... - def set_io_services(self, nbio) -> None: ... - def start(self, connection_configs, connector_factory, native_loop, on_done) -> None: ... + def set_io_services(self, nbio: AbstractIOServices) -> None: ... + def start( + self, + connection_configs: Sequence[pika.connection.Parameters], + connector_factory: Callable[..., Incomplete], + native_loop, + on_done: Callable[[pika.connection.Connection | AMQPConnectorException], None], + ) -> None: ... def abort(self) -> None: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/adapters/utils/io_services_utils.pyi b/python/helpers/typeshed/stubs/pika/pika/adapters/utils/io_services_utils.pyi index 3f99e672ee31..604e533bc5f3 100644 --- a/python/helpers/typeshed/stubs/pika/pika/adapters/utils/io_services_utils.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/adapters/utils/io_services_utils.pyi @@ -1,43 +1,89 @@ import abc +from collections.abc import Callable +from socket import socket +from ssl import SSLContext, SSLSocket +from typing import Any -from pika.adapters.utils.nbio_interface import AbstractIOReference, AbstractStreamTransport +from pika.adapters.utils.nbio_interface import ( + AbstractFileDescriptorServices, + AbstractIOReference, + AbstractIOServices, + AbstractStreamProtocol, + AbstractStreamTransport, +) +from pika.adapters.utils.selector_ioloop_adapter import _SupportsCancel -def check_callback_arg(callback, name) -> None: ... -def check_fd_arg(fd) -> None: ... +def check_callback_arg(callback: Callable[..., Any], name: str) -> None: ... +def check_fd_arg(fd: int) -> None: ... class SocketConnectionMixin: - def connect_socket(self, sock, resolved_addr, on_done): ... + def connect_socket( + self, sock: socket, resolved_addr: tuple[str, int], on_done: Callable[[BaseException | None], None] + ) -> _AsyncServiceAsyncHandle: ... class StreamingConnectionMixin: - def create_streaming_connection(self, protocol_factory, sock, on_done, ssl_context=None, server_hostname=None): ... + def create_streaming_connection( + self, + protocol_factory: Callable[[], AbstractStreamProtocol], + sock: socket, + on_done: Callable[[tuple[AbstractStreamTransport, AbstractStreamProtocol] | BaseException], None], + ssl_context: SSLContext | None = None, + server_hostname: str | None = None, + ) -> AbstractIOReference: ... class _AsyncServiceAsyncHandle(AbstractIOReference): - def __init__(self, subject) -> None: ... - def cancel(self): ... + def __init__(self, subject: _SupportsCancel) -> None: ... + def cancel(self) -> bool: ... class _AsyncSocketConnector: - def __init__(self, nbio, sock, resolved_addr, on_done) -> None: ... - def start(self): ... - def cancel(self): ... + def __init__( + self, + nbio: AbstractIOServices | AbstractFileDescriptorServices, + sock: socket, + resolved_addr: tuple[str, int], + on_done: Callable[[BaseException | None], None], + ) -> None: ... + def start(self) -> AbstractIOReference: ... + def cancel(self) -> bool: ... class _AsyncStreamConnector: - def __init__(self, nbio, protocol_factory, sock, ssl_context, server_hostname, on_done) -> None: ... - def start(self): ... - def cancel(self): ... + def __init__( + self, + nbio: AbstractIOServices | AbstractFileDescriptorServices, + protocol_factory: Callable[[], AbstractStreamProtocol], + sock: socket, + ssl_context: SSLContext, + server_hostname: str | None, + on_done: Callable[[tuple[AbstractStreamTransport, AbstractStreamProtocol] | BaseException], None], + ) -> None: ... + def start(self) -> AbstractIOReference: ... + def cancel(self) -> bool: ... class _AsyncTransportBase(AbstractStreamTransport, metaclass=abc.ABCMeta): class RxEndOfFile(OSError): def __init__(self) -> None: ... - def __init__(self, sock, protocol, nbio) -> None: ... + def __init__( + self, + sock: socket | SSLSocket, + protocol: AbstractStreamProtocol, + nbio: AbstractIOServices | AbstractFileDescriptorServices, + ) -> None: ... def abort(self) -> None: ... - def get_protocol(self): ... - def get_write_buffer_size(self): ... + def get_protocol(self) -> AbstractStreamProtocol: ... + def get_write_buffer_size(self) -> int: ... class _AsyncPlaintextTransport(_AsyncTransportBase): - def __init__(self, sock, protocol, nbio) -> None: ... - def write(self, data) -> None: ... + def __init__( + self, + sock: socket | SSLSocket, + protocol: AbstractStreamProtocol, + nbio: AbstractIOServices | AbstractFileDescriptorServices, + ) -> None: ... + def write(self, data: bytes) -> None: ... class _AsyncSSLTransport(_AsyncTransportBase): - def __init__(self, sock, protocol, nbio) -> None: ... - def write(self, data) -> None: ... + def __init__( + self, sock: SSLSocket, protocol: AbstractStreamProtocol, nbio: AbstractIOServices | AbstractFileDescriptorServices + ) -> None: ... + def write(self, data: bytes) -> None: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/adapters/utils/nbio_interface.pyi b/python/helpers/typeshed/stubs/pika/pika/adapters/utils/nbio_interface.pyi index 14c721842d29..6b963642813e 100644 --- a/python/helpers/typeshed/stubs/pika/pika/adapters/utils/nbio_interface.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/adapters/utils/nbio_interface.pyi @@ -1,61 +1,85 @@ import abc +from collections.abc import Callable +from socket import socket +from ssl import SSLContext import pika.compat class AbstractIOServices(pika.compat.AbstractBase, metaclass=abc.ABCMeta): @abc.abstractmethod - def get_native_ioloop(self): ... + def get_native_ioloop(self) -> object: ... @abc.abstractmethod - def close(self): ... + def close(self) -> None: ... @abc.abstractmethod - def run(self): ... + def run(self) -> None: ... @abc.abstractmethod - def stop(self): ... + def stop(self) -> None: ... @abc.abstractmethod - def add_callback_threadsafe(self, callback): ... + def add_callback_threadsafe(self, callback: Callable[..., None]) -> None: ... @abc.abstractmethod - def call_later(self, delay, callback): ... + def call_later(self, delay: float, callback: Callable[..., None]) -> AbstractTimerReference: ... @abc.abstractmethod - def getaddrinfo(self, host, port, on_done, family: int = 0, socktype: int = 0, proto: int = 0, flags: int = 0): ... + def getaddrinfo( + self, + host: str | bytes | None, + port: str | bytes | int | None, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + family: int = 0, + socktype: int = 0, + proto: int = 0, + flags: int = 0, + ) -> AbstractIOReference: ... @abc.abstractmethod - def connect_socket(self, sock, resolved_addr, on_done): ... + def connect_socket( + self, sock: socket, resolved_addr: tuple[str, int], on_done: Callable[[BaseException | None], None] + ) -> AbstractIOReference: ... @abc.abstractmethod - def create_streaming_connection(self, protocol_factory, sock, on_done, ssl_context=None, server_hostname=None): ... + def create_streaming_connection( + self, + protocol_factory: Callable[[], AbstractStreamProtocol], + sock: socket, + on_done: Callable[[tuple[AbstractStreamTransport, AbstractStreamProtocol] | BaseException], None], + ssl_context: SSLContext | None = None, + server_hostname: str | None = None, + ) -> AbstractIOReference: ... -class AbstractFileDescriptorServices(pika.compat.AbstractBase, metaclass=abc.ABCMeta): +class AbstractFileDescriptorServices(pika.compat.AbstractBase): @abc.abstractmethod - def set_reader(self, fd, on_readable): ... + def set_reader(self, fd: int, on_readable: Callable[[], None]) -> None: ... @abc.abstractmethod - def remove_reader(self, fd): ... + def remove_reader(self, fd: int) -> bool: ... @abc.abstractmethod - def set_writer(self, fd, on_writable): ... + def set_writer(self, fd: int, on_writable: Callable[[], None]) -> None: ... @abc.abstractmethod - def remove_writer(self, fd): ... + def remove_writer(self, fd: int) -> bool: ... -class AbstractTimerReference(pika.compat.AbstractBase, metaclass=abc.ABCMeta): +class AbstractTimerReference(pika.compat.AbstractBase): @abc.abstractmethod - def cancel(self): ... + def cancel(self) -> None: ... -class AbstractIOReference(pika.compat.AbstractBase, metaclass=abc.ABCMeta): +class AbstractIOReference(pika.compat.AbstractBase): @abc.abstractmethod - def cancel(self): ... + def cancel(self) -> bool: ... -class AbstractStreamProtocol(pika.compat.AbstractBase, metaclass=abc.ABCMeta): +class AbstractStreamProtocol(pika.compat.AbstractBase): @abc.abstractmethod - def connection_made(self, transport): ... + def connection_made(self, transport: AbstractStreamTransport) -> None: ... @abc.abstractmethod - def connection_lost(self, error): ... + def connection_lost(self, error: BaseException | None) -> None: ... @abc.abstractmethod - def eof_received(self): ... + def eof_received(self) -> bool | None: ... @abc.abstractmethod - def data_received(self, data): ... + def data_received(self, data: bytes) -> None: ... -class AbstractStreamTransport(pika.compat.AbstractBase, metaclass=abc.ABCMeta): +class AbstractStreamTransport(pika.compat.AbstractBase): @abc.abstractmethod - def abort(self): ... + def abort(self) -> None: ... @abc.abstractmethod - def get_protocol(self): ... + def get_protocol(self) -> AbstractStreamProtocol: ... @abc.abstractmethod - def write(self, data): ... + def write(self, data: bytes) -> None: ... @abc.abstractmethod - def get_write_buffer_size(self): ... + def get_write_buffer_size(self) -> int: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/adapters/utils/selector_ioloop_adapter.pyi b/python/helpers/typeshed/stubs/pika/pika/adapters/utils/selector_ioloop_adapter.pyi index 17f1305f95fc..020017eacaf4 100644 --- a/python/helpers/typeshed/stubs/pika/pika/adapters/utils/selector_ioloop_adapter.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/adapters/utils/selector_ioloop_adapter.pyi @@ -1,78 +1,111 @@ import abc -from _typeshed import Incomplete +from collections.abc import Callable from logging import Logger +from typing import Final, Generic, Protocol, TypeVar, type_check_only from pika.adapters.utils import io_services_utils, nbio_interface LOGGER: Logger -class AbstractSelectorIOLoop(metaclass=abc.ABCMeta): +_Timeout = TypeVar("_Timeout", bound=object, default=object) + +@type_check_only +class _SupportsCancel(Protocol): + def cancel(self) -> bool: ... + +class AbstractSelectorIOLoop(Generic[_Timeout], metaclass=abc.ABCMeta): @property @abc.abstractmethod - def READ(self): ... + def READ(self) -> int: ... @property @abc.abstractmethod - def WRITE(self): ... + def WRITE(self) -> int: ... @property @abc.abstractmethod - def ERROR(self): ... + def ERROR(self) -> int: ... @abc.abstractmethod - def close(self): ... + def close(self) -> None: ... @abc.abstractmethod - def start(self): ... + def start(self) -> None: ... @abc.abstractmethod - def stop(self): ... + def stop(self) -> None: ... @abc.abstractmethod - def call_later(self, delay, callback): ... + def call_later(self, delay: float, callback: Callable[[], object]) -> _Timeout: ... @abc.abstractmethod - def remove_timeout(self, timeout_handle): ... + def remove_timeout(self, timeout_handle: _Timeout) -> None: ... @abc.abstractmethod - def add_callback(self, callback): ... + def add_callback(self, callback: Callable[[], object]) -> None: ... @abc.abstractmethod - def add_handler(self, fd, handler, events): ... + def add_handler(self, fd: int, handler: Callable[[int, int], None], events: int) -> None: ... @abc.abstractmethod - def update_handler(self, fd, events): ... + def update_handler(self, fd: int, events: int) -> None: ... @abc.abstractmethod - def remove_handler(self, fd): ... + def remove_handler(self, fd: int) -> None: ... class SelectorIOServicesAdapter( io_services_utils.SocketConnectionMixin, io_services_utils.StreamingConnectionMixin, nbio_interface.AbstractIOServices, nbio_interface.AbstractFileDescriptorServices, + Generic[_Timeout], ): - def __init__(self, native_loop) -> None: ... - def get_native_ioloop(self): ... + def __init__(self, native_loop: AbstractSelectorIOLoop[_Timeout]) -> None: ... + def get_native_ioloop(self) -> AbstractSelectorIOLoop[_Timeout]: ... def close(self) -> None: ... def run(self) -> None: ... def stop(self) -> None: ... - def add_callback_threadsafe(self, callback) -> None: ... - def call_later(self, delay, callback): ... - def getaddrinfo(self, host, port, on_done, family: int = 0, socktype: int = 0, proto: int = 0, flags: int = 0): ... - def set_reader(self, fd, on_readable) -> None: ... - def remove_reader(self, fd): ... - def set_writer(self, fd, on_writable) -> None: ... - def remove_writer(self, fd): ... + def add_callback_threadsafe(self, callback: Callable[[], None]) -> None: ... + def call_later(self, delay: float, callback: Callable[[], None]) -> _TimerHandle: ... + def getaddrinfo( + self, + host: str | bytes | None, + port: str | bytes | int | None, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + family: int = 0, + socktype: int = 0, + proto: int = 0, + flags: int = 0, + ) -> nbio_interface.AbstractIOReference: ... + def set_reader(self, fd: int, on_readable: Callable[[], None]) -> None: ... + def remove_reader(self, fd: int) -> bool: ... + def set_writer(self, fd: int, on_writable: Callable[[], None]) -> None: ... + def remove_writer(self, fd: int) -> bool: ... class _FileDescriptorCallbacks: __slots__ = ("reader", "writer") - reader: Incomplete - writer: Incomplete - def __init__(self, reader=None, writer=None) -> None: ... + reader: Callable[[], None] + writer: Callable[[], None] + def __init__(self, reader: Callable[[], None] | None = None, writer: Callable[[], None] | None = None) -> None: ... class _TimerHandle(nbio_interface.AbstractTimerReference): - def __init__(self, handle, loop) -> None: ... + def __init__(self, handle: object, loop: AbstractSelectorIOLoop) -> None: ... def cancel(self) -> None: ... class _SelectorIOLoopIOHandle(nbio_interface.AbstractIOReference): - def __init__(self, subject) -> None: ... - def cancel(self): ... + def __init__(self, subject: _SupportsCancel) -> None: ... + def cancel(self) -> bool: ... class _AddressResolver: - NOT_STARTED: int - ACTIVE: int - CANCELED: int - COMPLETED: int - def __init__(self, native_loop, host, port, family, socktype, proto, flags, on_done) -> None: ... - def start(self): ... - def cancel(self): ... + NOT_STARTED: Final = 0 + ACTIVE: Final = 1 + CANCELED: Final = 2 + COMPLETED: Final = 3 + def __init__( + self, + native_loop: AbstractSelectorIOLoop, + host: str | bytes | None, + port: str | bytes | int | None, + family: int, + socktype: int, + proto: int, + flags: int, + on_done: Callable[ # list is result of socket.getaddrinfo + [list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]] | BaseException], + None, + ], + ) -> None: ... + def start(self) -> _SelectorIOLoopIOHandle: ... + def cancel(self) -> bool: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/callback.pyi b/python/helpers/typeshed/stubs/pika/pika/callback.pyi index c5fe764fafce..852fc1643dc5 100644 --- a/python/helpers/typeshed/stubs/pika/pika/callback.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/callback.pyi @@ -1,24 +1,27 @@ -from collections.abc import Callable +from _typeshed import Incomplete +from collections.abc import Callable, Mapping from logging import Logger -from typing import Literal, TypeAlias +from typing import Any, Final, Literal, ParamSpec, TypeAlias, TypeVar from .amqp_object import AMQPObject +_P = ParamSpec("_P") +_R = TypeVar("_R") AMQPValue: TypeAlias = type[AMQPObject] | AMQPObject | int | str LOGGER: Logger def name_or_value(value: AMQPValue) -> str: ... -def sanitize_prefix(function): ... -def check_for_prefix_and_key(function): ... +def sanitize_prefix(function: Callable[_P, _R]) -> Callable[_P, _R]: ... +def check_for_prefix_and_key(function: Callable[_P, _R]) -> Callable[_P, _R | Literal[False]]: ... class CallbackManager: - CALLS: str - ARGUMENTS: str - DUPLICATE_WARNING: str - CALLBACK: str - ONE_SHOT: str - ONLY_CALLER: str + CALLS: Final = "calls" + ARGUMENTS: Final = "arguments" + DUPLICATE_WARNING: Final = 'Duplicate callback found for "%s:%s"' + CALLBACK: Final = "callback" + ONE_SHOT: Final = "one_shot" + ONLY_CALLER: Final = "only" def __init__(self) -> None: ... def add( self, @@ -28,13 +31,24 @@ class CallbackManager: callback: Callable[..., object], one_shot: bool = True, only_caller: object | None = None, - arguments=None, + arguments: Mapping[str, Incomplete] | None = None, ) -> tuple[str | int, str | object]: ... def clear(self) -> None: ... def cleanup(self, prefix: str | int) -> bool: ... - def pending(self, prefix: str | int, key: str | object) -> int | None: ... - def process(self, prefix: str | int, key: AMQPValue, caller, *args, **keywords) -> bool: ... + def pending(self, prefix: str | int, key: AMQPValue) -> int | None: ... + def process( + self, + prefix: str | int, + key: AMQPValue, + caller, + *args: Any, # Arguments depends on callbacks stored on self._stack + **keywords: Any, + ) -> bool: ... def remove( - self, prefix: str | int, key: AMQPValue, callback_value: Callable[..., object] | None = None, arguments=None - ) -> Literal[True]: ... - def remove_all(self, prefix: str | int, key: AMQPValue) -> None: ... + self, + prefix: str | int, + key: AMQPValue, + callback_value: Callable[..., object] | None = None, + arguments: Mapping[str, Incomplete] | None = None, + ) -> bool: ... + def remove_all(self, prefix: str | int, key: AMQPValue) -> Literal[False] | None: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/channel.pyi b/python/helpers/typeshed/stubs/pika/pika/channel.pyi index c0252bbb65a8..7fdbbd93d7b6 100644 --- a/python/helpers/typeshed/stubs/pika/pika/channel.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/channel.pyi @@ -1,18 +1,20 @@ from _typeshed import Incomplete -from collections.abc import Callable +from collections.abc import Callable, Iterable, Mapping from logging import Logger -from typing import Any, Final +from typing import Final, TypeVar from typing_extensions import Self +from . import amqp_object from .callback import CallbackManager from .connection import Connection -from .data import _ArgumentMapping from .exchange_type import ExchangeType from .frame import Body, Header, Method from .spec import Basic, BasicProperties, Confirm, Exchange, Queue, Tx +_Method = TypeVar("_Method", bound=amqp_object.Method) + LOGGER: Logger -MAX_CHANNELS: Final[int] +MAX_CHANNELS: Final = 65535 class Channel: CLOSED: Final = 0 @@ -27,11 +29,11 @@ class Channel: def __init__(self, connection: Connection, channel_number: int, on_open_callback: Callable[[Self], object]) -> None: ... def __int__(self) -> int: ... - def add_callback(self, callback, replies, one_shot: bool = True) -> None: ... - def add_on_cancel_callback(self, callback) -> None: ... - def add_on_close_callback(self, callback) -> None: ... - def add_on_flow_callback(self, callback) -> None: ... - def add_on_return_callback(self, callback) -> None: ... + def add_callback(self, callback: Callable[..., object], replies: Iterable[Incomplete], one_shot: bool = True) -> None: ... + def add_on_cancel_callback(self, callback: Callable[[Method[Basic.Cancel]], object]) -> None: ... + def add_on_close_callback(self, callback: Callable[[Channel, Exception], object]) -> None: ... + def add_on_flow_callback(self, callback: Callable[[bool], object]) -> None: ... + def add_on_return_callback(self, callback: Callable[[Channel, Basic.Return, BasicProperties, bytes], object]) -> None: ... def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None: ... def basic_cancel( self, consumer_tag: str = "", callback: Callable[[Method[Basic.CancelOk]], object] | None = None @@ -43,7 +45,7 @@ class Channel: auto_ack: bool = False, exclusive: bool = False, consumer_tag: str | None = None, - arguments: _ArgumentMapping | None = None, + arguments: Mapping[str, Incomplete] | None = None, callback: Callable[[Method[Basic.ConsumeOk]], object] | None = None, ) -> str: ... def basic_get( @@ -82,7 +84,7 @@ class Channel: destination: str, source: str, routing_key: str = "", - arguments: _ArgumentMapping | None = None, + arguments: Mapping[str, Incomplete] | None = None, callback: Callable[[Method[Exchange.BindOk]], object] | None = None, ) -> None: ... def exchange_declare( @@ -93,7 +95,7 @@ class Channel: durable: bool = False, auto_delete: bool = False, internal: bool = False, - arguments: _ArgumentMapping | None = None, + arguments: Mapping[str, Incomplete] | None = None, callback: Callable[[Method[Exchange.DeclareOk]], object] | None = None, ) -> None: ... def exchange_delete( @@ -107,7 +109,7 @@ class Channel: destination: str | None = None, source: str | None = None, routing_key: str = "", - arguments: _ArgumentMapping | None = None, + arguments: Mapping[str, Incomplete] | None = None, callback: Callable[[Method[Exchange.UnbindOk]], object] | None = None, ) -> None: ... def flow(self, active: bool, callback: Callable[[bool], object] | None = None) -> None: ... @@ -125,7 +127,7 @@ class Channel: queue: str, exchange: str, routing_key: str | None = None, - arguments: _ArgumentMapping | None = None, + arguments: Mapping[str, Incomplete] | None = None, callback: Callable[[Method[Queue.BindOk]], object] | None = None, ) -> None: ... def queue_declare( @@ -135,7 +137,7 @@ class Channel: durable: bool = False, exclusive: bool = False, auto_delete: bool = False, - arguments: _ArgumentMapping | None = None, + arguments: Mapping[str, Incomplete] | None = None, callback: Callable[[Method[Queue.DeclareOk]], object] | None = None, ) -> None: ... def queue_delete( @@ -151,7 +153,7 @@ class Channel: queue: str, exchange: str | None = None, routing_key: str | None = None, - arguments: _ArgumentMapping | None = None, + arguments: Mapping[str, Incomplete] | None = None, callback: Callable[[Method[Queue.UnbindOk]], object] | None = None, ): ... def tx_commit(self, callback: Callable[[Method[Tx.CommitOk]], object] | None = None) -> None: ... @@ -160,4 +162,4 @@ class Channel: class ContentFrameAssembler: def __init__(self) -> None: ... - def process(self, frame_value: Method[Any] | Header | Body) -> tuple[Incomplete, Incomplete, bytes] | None: ... + def process(self, frame_value: Method[_Method] | Header | Body) -> tuple[Method[_Method], Header, bytes] | None: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/connection.pyi b/python/helpers/typeshed/stubs/pika/pika/connection.pyi index 99eace9f7218..0264ccc017e0 100644 --- a/python/helpers/typeshed/stubs/pika/pika/connection.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/connection.pyi @@ -3,17 +3,17 @@ import ssl from _typeshed import Incomplete from collections.abc import Callable from logging import Logger -from typing import Final +from typing import Final, Literal from typing_extensions import Self from .callback import CallbackManager from .channel import Channel from .compat import AbstractBase -from .credentials import _Credentials +from .credentials import PlainCredentials, _Credentials from .frame import Method from .spec import Connection as SpecConnection -PRODUCT: str +PRODUCT: Final = "Pika Python Client Library" LOGGER: Logger class Parameters: @@ -35,26 +35,26 @@ class Parameters: "_virtual_host", "_tcp_options", ) - DEFAULT_USERNAME: str - DEFAULT_PASSWORD: str - DEFAULT_BLOCKED_CONNECTION_TIMEOUT: None - DEFAULT_CHANNEL_MAX: int - DEFAULT_CLIENT_PROPERTIES: None - DEFAULT_CREDENTIALS: Incomplete - DEFAULT_CONNECTION_ATTEMPTS: int - DEFAULT_FRAME_MAX: int + DEFAULT_USERNAME: Final = "guest" + DEFAULT_PASSWORD: Final = "guest" + DEFAULT_BLOCKED_CONNECTION_TIMEOUT: Final = None + DEFAULT_CHANNEL_MAX: Final = 65535 + DEFAULT_CLIENT_PROPERTIES: Final = None + DEFAULT_CREDENTIALS: Final[PlainCredentials] + DEFAULT_CONNECTION_ATTEMPTS: Final = 1 + DEFAULT_FRAME_MAX: Final = 131072 DEFAULT_HEARTBEAT_TIMEOUT: None - DEFAULT_HOST: str - DEFAULT_LOCALE: str - DEFAULT_PORT: int - DEFAULT_RETRY_DELAY: float - DEFAULT_SOCKET_TIMEOUT: float - DEFAULT_STACK_TIMEOUT: float - DEFAULT_SSL: bool - DEFAULT_SSL_OPTIONS: None - DEFAULT_SSL_PORT: int - DEFAULT_VIRTUAL_HOST: str - DEFAULT_TCP_OPTIONS: None + DEFAULT_HOST: Final = "localhost" + DEFAULT_LOCALE: Final = "en_US" + DEFAULT_PORT: Final = 5672 + DEFAULT_RETRY_DELAY: Final = 2.0 + DEFAULT_SOCKET_TIMEOUT: Final = 10.0 + DEFAULT_STACK_TIMEOUT: Final = 15.0 + DEFAULT_SSL: Final = False + DEFAULT_SSL_OPTIONS: Final = None + DEFAULT_SSL_PORT: Final = 5671 + DEFAULT_VIRTUAL_HOST: Final = "/" + DEFAULT_TCP_OPTIONS: Final = None def __init__(self) -> None: ... def __eq__(self, other: object) -> bool: ... def __ne__(self, other: object) -> bool: ... @@ -135,13 +135,12 @@ class Parameters: def virtual_host(self, value: str) -> None: ... @property - def tcp_options(self) -> dict[Incomplete, Incomplete] | None: ... + def tcp_options(self) -> dict[str, Incomplete] | None: ... @tcp_options.setter - def tcp_options(self, value: dict[Incomplete, Incomplete] | None) -> None: ... + def tcp_options(self, value: dict[str, Incomplete] | None) -> None: ... class ConnectionParameters(Parameters): __slots__ = () - def __init__( self, host: str = ..., @@ -158,8 +157,8 @@ class ConnectionParameters(Parameters): stack_timeout: float | None = ..., locale: str = ..., blocked_connection_timeout: float | None = ..., - client_properties: dict[Incomplete, Incomplete] | None = ..., - tcp_options: dict[Incomplete, Incomplete] | None = ..., + client_properties: dict[str, Incomplete] | None = ..., + tcp_options: dict[str, Incomplete] | None = ..., ) -> None: ... class URLParameters(Parameters): @@ -173,22 +172,22 @@ class SSLOptions: def __init__(self, context: ssl.SSLContext, server_hostname: str | None = None) -> None: ... class Connection(AbstractBase, metaclass=abc.ABCMeta): - ON_CONNECTION_CLOSED: Final[str] - ON_CONNECTION_ERROR: Final[str] - ON_CONNECTION_OPEN_OK: Final[str] - CONNECTION_CLOSED: Final[int] - CONNECTION_INIT: Final[int] - CONNECTION_PROTOCOL: Final[int] - CONNECTION_START: Final[int] - CONNECTION_TUNE: Final[int] - CONNECTION_OPEN: Final[int] - CONNECTION_CLOSING: Final[int] - connection_state: int # one of the constants above + ON_CONNECTION_CLOSED: Final = "_on_connection_closed" + ON_CONNECTION_ERROR: Final = "_on_connection_error" + ON_CONNECTION_OPEN_OK: Final = "_on_connection_open_ok" + CONNECTION_CLOSED: Final = 0 + CONNECTION_INIT: Final = 1 + CONNECTION_PROTOCOL: Final = 2 + CONNECTION_START: Final = 3 + CONNECTION_TUNE: Final = 4 + CONNECTION_OPEN: Final = 5 + CONNECTION_CLOSING: Final = 6 + connection_state: Literal[0, 1, 2, 3, 4, 5, 6] # one of the constants above params: Parameters callbacks: CallbackManager - server_capabilities: Incomplete - server_properties: Incomplete - known_hosts: Incomplete + server_capabilities: dict[str, bool] | None + server_properties: dict[str, Incomplete] | None + known_hosts: str | None def __init__( self, parameters: Parameters | None = None, @@ -209,7 +208,12 @@ class Connection(AbstractBase, metaclass=abc.ABCMeta): def channel( self, channel_number: int | None = None, on_open_callback: Callable[[Channel], object] | None = None ) -> Channel: ... - def update_secret(self, new_secret, reason, callback=None) -> None: ... + def update_secret( + self, + new_secret: str | bytes, + reason: str | bytes, + callback: Callable[[Method[SpecConnection.UpdateSecretOk]], object] | None = None, + ) -> None: ... def close(self, reply_code: int = 200, reply_text: str = "Normal shutdown") -> None: ... @property def is_closed(self) -> bool: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/data.pyi b/python/helpers/typeshed/stubs/pika/pika/data.pyi index 3e3b289c22a4..18ad67c71a6b 100644 --- a/python/helpers/typeshed/stubs/pika/pika/data.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/data.pyi @@ -7,8 +7,8 @@ _Value: TypeAlias = str | bytes | bool | int | Decimal | datetime | _ArgumentMap _ArgumentMapping: TypeAlias = Mapping[str, _Value] def encode_short_string(pieces: list[bytes], value: str | bytes) -> int: ... -def decode_short_string(encoded: bytes, offset: int) -> tuple[str, int]: ... +def decode_short_string(encoded: bytes, offset: int) -> tuple[str | bytes, int]: ... def encode_table(pieces: list[bytes], table: _ArgumentMapping) -> int: ... def encode_value(pieces: list[bytes], value: _Value) -> int: ... -def decode_table(encoded: bytes, offset: int) -> tuple[dict[str, _Value], int]: ... +def decode_table(encoded: bytes, offset: int) -> tuple[dict[str | bytes, _Value], int]: ... def decode_value(encoded: bytes, offset: int) -> tuple[_Value, int]: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/frame.pyi b/python/helpers/typeshed/stubs/pika/pika/frame.pyi index f0019be803bf..8b547d8478ee 100644 --- a/python/helpers/typeshed/stubs/pika/pika/frame.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/frame.pyi @@ -2,14 +2,14 @@ from abc import abstractmethod from logging import Logger from typing import Generic, TypeVar -from .amqp_object import AMQPObject, Method as AMQPMethod +from . import amqp_object from .spec import BasicProperties -_M = TypeVar("_M", bound=AMQPMethod) +_M = TypeVar("_M", bound=amqp_object.Method) LOGGER: Logger -class Frame(AMQPObject): +class Frame(amqp_object.AMQPObject): frame_type: int channel_number: int def __init__(self, frame_type: int, channel_number: int) -> None: ... @@ -36,7 +36,7 @@ class Heartbeat(Frame): def __init__(self) -> None: ... def marshal(self) -> bytes: ... -class ProtocolHeader(AMQPObject): +class ProtocolHeader(amqp_object.AMQPObject): frame_type: int major: int minor: int @@ -44,4 +44,4 @@ class ProtocolHeader(AMQPObject): def __init__(self, major: int | None = None, minor: int | None = None, revision: int | None = None) -> None: ... def marshal(self) -> bytes: ... -def decode_frame(data_in: bytes) -> tuple[int, Frame | None]: ... +def decode_frame(data_in: bytes) -> tuple[int, Frame | ProtocolHeader | None]: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/heartbeat.pyi b/python/helpers/typeshed/stubs/pika/pika/heartbeat.pyi index 757fb6246551..1c6ec89dfc60 100644 --- a/python/helpers/typeshed/stubs/pika/pika/heartbeat.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/heartbeat.pyi @@ -1,12 +1,14 @@ from logging import Logger +from pika.connection import Connection + LOGGER: Logger class HeartbeatChecker: - def __init__(self, connection, timeout) -> None: ... + def __init__(self, connection: Connection, timeout: float) -> None: ... @property - def bytes_received_on_connection(self): ... + def bytes_received_on_connection(self) -> int: ... @property - def connection_is_idle(self): ... + def connection_is_idle(self) -> bool: ... def received(self) -> None: ... def stop(self) -> None: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/spec.pyi b/python/helpers/typeshed/stubs/pika/pika/spec.pyi index 8ce6fb2e2adb..eee768972a16 100644 --- a/python/helpers/typeshed/stubs/pika/pika/spec.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/spec.pyi @@ -1,52 +1,45 @@ -import builtins from _typeshed import Incomplete +from builtins import type as _type from collections.abc import Mapping -from datetime import datetime -from decimal import Decimal -from typing import ClassVar, Final, Literal, TypeAlias +from typing import ClassVar, Final, Literal from typing_extensions import Self from pika.amqp_object import Class, Method, Properties +from pika.data import _ArgumentMapping from pika.delivery_mode import DeliveryMode -# Ouch. Since str = bytes at runtime, we need a type alias for "str". -_str: TypeAlias = builtins.str # noqa: Y042 -_Value: TypeAlias = _str | bytes | bool | int | Decimal | datetime | _ArgumentMapping | list[_Value] | None -_ArgumentMapping: TypeAlias = Mapping[_str, _Value] -str = builtins.bytes - PROTOCOL_VERSION: Final[tuple[int, int, int]] -PORT: Final[int] -ACCESS_REFUSED: Final[int] -CHANNEL_ERROR: Final[int] -COMMAND_INVALID: Final[int] -CONNECTION_FORCED: Final[int] -CONTENT_TOO_LARGE: Final[int] -FRAME_BODY: Final[int] -FRAME_END: Final[int] -FRAME_END_SIZE: Final[int] -FRAME_ERROR: Final[int] -FRAME_HEADER: Final[int] -FRAME_HEADER_SIZE: Final[int] -FRAME_HEARTBEAT: Final[int] -FRAME_MAX_SIZE: Final[int] -FRAME_METHOD: Final[int] -FRAME_MIN_SIZE: Final[int] -INTERNAL_ERROR: Final[int] -INVALID_PATH: Final[int] -NOT_ALLOWED: Final[int] -NOT_FOUND: Final[int] -NOT_IMPLEMENTED: Final[int] -NO_CONSUMERS: Final[int] -NO_ROUTE: Final[int] -PERSISTENT_DELIVERY_MODE: Final[int] -PRECONDITION_FAILED: Final[int] -REPLY_SUCCESS: Final[int] -RESOURCE_ERROR: Final[int] -RESOURCE_LOCKED: Final[int] -SYNTAX_ERROR: Final[int] -TRANSIENT_DELIVERY_MODE: Final[int] -UNEXPECTED_FRAME: Final[int] +PORT: Final = 5672 +ACCESS_REFUSED: Final = 403 +CHANNEL_ERROR: Final = 504 +COMMAND_INVALID: Final = 503 +CONNECTION_FORCED: Final = 320 +CONTENT_TOO_LARGE: Final = 311 +FRAME_BODY: Final = 3 +FRAME_END: Final = 206 +FRAME_END_SIZE: Final = 1 +FRAME_ERROR: Final = 501 +FRAME_HEADER: Final = 2 +FRAME_HEADER_SIZE: Final = 7 +FRAME_HEARTBEAT: Final = 8 +FRAME_MAX_SIZE: Final = 131072 +FRAME_METHOD: Final = 1 +FRAME_MIN_SIZE: Final = 4096 +INTERNAL_ERROR: Final = 541 +INVALID_PATH: Final = 402 +NOT_ALLOWED: Final = 530 +NOT_FOUND: Final = 404 +NOT_IMPLEMENTED: Final = 540 +NO_CONSUMERS: Final = 313 +NO_ROUTE: Final = 312 +PERSISTENT_DELIVERY_MODE: Final = 2 +PRECONDITION_FAILED: Final = 406 +REPLY_SUCCESS: Final = 200 +RESOURCE_ERROR: Final = 506 +RESOURCE_LOCKED: Final = 405 +SYNTAX_ERROR: Final = 502 +TRANSIENT_DELIVERY_MODE: Final = 1 +UNEXPECTED_FRAME: Final = 505 class Connection(Class): INDEX: ClassVar[int] @@ -56,15 +49,15 @@ class Connection(Class): version_major: int version_minor: int server_properties: _ArgumentMapping | None - mechanisms: _str - locales: _str + mechanisms: str + locales: str def __init__( self, version_major: int = 0, version_minor: int = 9, server_properties: _ArgumentMapping | None = None, - mechanisms: _str = "PLAIN", - locales: _str = "en_US", + mechanisms: str = "PLAIN", + locales: str = "en_US", ) -> None: ... @property def synchronous(self) -> Literal[True]: ... @@ -74,15 +67,15 @@ class Connection(Class): class StartOk(Method): INDEX: ClassVar[int] client_properties: _ArgumentMapping | None - mechanism: _str - response: _str | None - locale: _str + mechanism: str + response: str | None + locale: str def __init__( self, client_properties: _ArgumentMapping | None = None, - mechanism: _str = "PLAIN", - response: _str | None = None, - locale: _str = "en_US", + mechanism: str = "PLAIN", + response: str | None = None, + locale: str = "en_US", ) -> None: ... @property def synchronous(self) -> Literal[False]: ... @@ -91,8 +84,8 @@ class Connection(Class): class Secure(Method): INDEX: ClassVar[int] - challenge: _str | None - def __init__(self, challenge: _str | None = None) -> None: ... + challenge: str | None + def __init__(self, challenge: str | None = None) -> None: ... @property def synchronous(self) -> Literal[True]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -100,8 +93,8 @@ class Connection(Class): class SecureOk(Method): INDEX: ClassVar[int] - response: _str - def __init__(self, response: _str | None = None) -> None: ... + response: str + def __init__(self, response: str | None = None) -> None: ... @property def synchronous(self) -> Literal[False]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -131,10 +124,10 @@ class Connection(Class): class Open(Method): INDEX: ClassVar[int] - virtual_host: _str - capabilities: _str + virtual_host: str + capabilities: str insist: bool - def __init__(self, virtual_host: _str = "/", capabilities: _str = "", insist: bool = False) -> None: ... + def __init__(self, virtual_host: str = "/", capabilities: str = "", insist: bool = False) -> None: ... @property def synchronous(self) -> Literal[True]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -142,8 +135,8 @@ class Connection(Class): class OpenOk(Method): INDEX: ClassVar[int] - known_hosts: _str - def __init__(self, known_hosts: _str = "") -> None: ... + known_hosts: str + def __init__(self, known_hosts: str = "") -> None: ... @property def synchronous(self) -> Literal[False]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -151,11 +144,13 @@ class Connection(Class): class Close(Method): INDEX: ClassVar[int] - reply_code: Incomplete - reply_text: Incomplete - class_id: Incomplete - method_id: Incomplete - def __init__(self, reply_code=None, reply_text: _str = "", class_id=None, method_id=None) -> None: ... + reply_code: int | None + reply_text: str + class_id: int | None + method_id: int | None + def __init__( + self, reply_code: int | None = None, reply_text: str = "", class_id: int | None = None, method_id: int | None = None + ) -> None: ... @property def synchronous(self) -> Literal[True]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -171,8 +166,8 @@ class Connection(Class): class Blocked(Method): INDEX: ClassVar[int] - reason: Incomplete - def __init__(self, reason: _str = "") -> None: ... + reason: str + def __init__(self, reason: str = "") -> None: ... @property def synchronous(self) -> Literal[False]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -188,10 +183,10 @@ class Connection(Class): class UpdateSecret(Method): INDEX: ClassVar[int] - new_secret: Incomplete - reason: Incomplete - mechanisms: _str - def __init__(self, new_secret, reason) -> None: ... + new_secret: str + reason: str + mechanisms: str + def __init__(self, new_secret: str, reason: str) -> None: ... @property def synchronous(self) -> Literal[True]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -210,8 +205,8 @@ class Channel(Class): class Open(Method): INDEX: ClassVar[int] - out_of_band: _str - def __init__(self, out_of_band: _str = "") -> None: ... + out_of_band: str + def __init__(self, out_of_band: str = "") -> None: ... @property def synchronous(self) -> Literal[True]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -219,8 +214,8 @@ class Channel(Class): class OpenOk(Method): INDEX: ClassVar[int] - channel_id: _str - def __init__(self, channel_id: _str = "") -> None: ... + channel_id: str + def __init__(self, channel_id: str = "") -> None: ... @property def synchronous(self) -> Literal[False]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -246,11 +241,13 @@ class Channel(Class): class Close(Method): INDEX: ClassVar[int] - reply_code: Incomplete - reply_text: Incomplete - class_id: Incomplete - method_id: Incomplete - def __init__(self, reply_code=None, reply_text: _str = "", class_id=None, method_id=None) -> None: ... + reply_code: int | None + reply_text: str + class_id: int | None + method_id: int | None + def __init__( + self, reply_code: int | None = None, reply_text: str = "", class_id: int | None = None, method_id: int | None = None + ) -> None: ... @property def synchronous(self) -> Literal[True]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -269,7 +266,7 @@ class Access(Class): class Request(Method): INDEX: ClassVar[int] - realm: _str + realm: str exclusive: bool passive: bool active: bool @@ -277,7 +274,7 @@ class Access(Class): read: bool def __init__( self, - realm: _str = "/data", + realm: str = "/data", exclusive: bool = False, passive: bool = True, active: bool = True, @@ -291,7 +288,7 @@ class Access(Class): class RequestOk(Method): INDEX: ClassVar[int] - ticket: Incomplete + ticket: int def __init__(self, ticket: int = 1) -> None: ... @property def synchronous(self) -> Literal[False]: ... @@ -303,26 +300,26 @@ class Exchange(Class): class Declare(Method): INDEX: ClassVar[int] - ticket: Incomplete - exchange: Incomplete - type: Incomplete + ticket: int + exchange: str | None + type: str passive: bool durable: bool auto_delete: bool internal: bool nowait: bool - arguments: Incomplete + arguments: Mapping[str, Incomplete] | None def __init__( self, ticket: int = 0, - exchange=None, - type=..., + exchange: str | None = None, + type: str = ..., passive: bool = False, durable: bool = False, auto_delete: bool = False, internal: bool = False, nowait: bool = False, - arguments=None, + arguments: Mapping[str, Incomplete] | None = None, ) -> None: ... @property def synchronous(self) -> Literal[True]: ... @@ -339,11 +336,13 @@ class Exchange(Class): class Delete(Method): INDEX: ClassVar[int] - ticket: Incomplete - exchange: Incomplete - if_unused: Incomplete + ticket: int + exchange: str | None + if_unused: bool nowait: bool - def __init__(self, ticket: int = 0, exchange=None, if_unused: bool = False, nowait: bool = False) -> None: ... + def __init__( + self, ticket: int = 0, exchange: str | None = None, if_unused: bool = False, nowait: bool = False + ) -> None: ... @property def synchronous(self) -> Literal[True]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -360,13 +359,19 @@ class Exchange(Class): class Bind(Method): INDEX: ClassVar[int] ticket: int - destination: Incomplete | None - source: Incomplete | None - routing_key: _str + destination: str | None + source: str | None + routing_key: str nowait: bool - arguments: Incomplete | None + arguments: Mapping[str, Incomplete] | None def __init__( - self, ticket: int = 0, destination=None, source=None, routing_key: _str = "", nowait: bool = False, arguments=None + self, + ticket: int = 0, + destination: str | None = None, + source: str | None = None, + routing_key: str = "", + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, ) -> None: ... @property def synchronous(self) -> Literal[True]: ... @@ -383,14 +388,20 @@ class Exchange(Class): class Unbind(Method): INDEX: ClassVar[int] - ticket: Incomplete - destination: Incomplete - source: Incomplete - routing_key: Incomplete + ticket: int + destination: str | None + source: str | None + routing_key: str nowait: bool - arguments: Incomplete + arguments: Mapping[str, Incomplete] | None def __init__( - self, ticket: int = 0, destination=None, source=None, routing_key: _str = "", nowait: bool = False, arguments=None + self, + ticket: int = 0, + destination: str | None = None, + source: str | None = None, + routing_key: str = "", + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, ) -> None: ... @property def synchronous(self) -> Literal[True]: ... @@ -410,24 +421,24 @@ class Queue(Class): class Declare(Method): INDEX: ClassVar[int] - ticket: Incomplete - queue: Incomplete + ticket: int + queue: str passive: bool durable: bool exclusive: bool auto_delete: bool nowait: bool - arguments: Incomplete + arguments: Mapping[str, Incomplete] | None def __init__( self, ticket: int = 0, - queue: _str = "", + queue: str = "", passive: bool = False, durable: bool = False, exclusive: bool = False, auto_delete: bool = False, nowait: bool = False, - arguments=None, + arguments: Mapping[str, Incomplete] | None = None, ) -> None: ... @property def synchronous(self) -> Literal[True]: ... @@ -436,10 +447,10 @@ class Queue(Class): class DeclareOk(Method): INDEX: ClassVar[int] - queue: _str + queue: str message_count: int consumer_count: int - def __init__(self, queue: _str, message_count: int, consumer_count: int) -> None: ... + def __init__(self, queue: str, message_count: int, consumer_count: int) -> None: ... @property def synchronous(self) -> Literal[False]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -447,14 +458,20 @@ class Queue(Class): class Bind(Method): INDEX: ClassVar[int] - ticket: Incomplete - queue: Incomplete - exchange: Incomplete - routing_key: Incomplete + ticket: int + queue: str + exchange: str | None + routing_key: str nowait: bool - arguments: Incomplete + arguments: Mapping[str, Incomplete] | None def __init__( - self, ticket: int = 0, queue: _str = "", exchange=None, routing_key: _str = "", nowait: bool = False, arguments=None + self, + ticket: int = 0, + queue: str = "", + exchange: str | None = None, + routing_key: str = "", + nowait: bool = False, + arguments: Mapping[str, Incomplete] | None = None, ) -> None: ... @property def synchronous(self) -> Literal[True]: ... @@ -471,10 +488,10 @@ class Queue(Class): class Purge(Method): INDEX: ClassVar[int] - ticket: Incomplete - queue: Incomplete + ticket: int + queue: str nowait: bool - def __init__(self, ticket: int = 0, queue: _str = "", nowait: bool = False) -> None: ... + def __init__(self, ticket: int = 0, queue: str = "", nowait: bool = False) -> None: ... @property def synchronous(self) -> Literal[True]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -482,8 +499,8 @@ class Queue(Class): class PurgeOk(Method): INDEX: ClassVar[int] - message_count: Incomplete - def __init__(self, message_count=None) -> None: ... + message_count: int | None + def __init__(self, message_count: int | None = None) -> None: ... @property def synchronous(self) -> Literal[False]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -491,13 +508,13 @@ class Queue(Class): class Delete(Method): INDEX: ClassVar[int] - ticket: Incomplete - queue: Incomplete - if_unused: Incomplete - if_empty: Incomplete + ticket: int + queue: str + if_unused: bool + if_empty: bool nowait: bool def __init__( - self, ticket: int = 0, queue: _str = "", if_unused: bool = False, if_empty: bool = False, nowait: bool = False + self, ticket: int = 0, queue: str = "", if_unused: bool = False, if_empty: bool = False, nowait: bool = False ) -> None: ... @property def synchronous(self) -> Literal[True]: ... @@ -506,8 +523,8 @@ class Queue(Class): class DeleteOk(Method): INDEX: ClassVar[int] - message_count: Incomplete - def __init__(self, message_count=None) -> None: ... + message_count: int | None + def __init__(self, message_count: int | None = None) -> None: ... @property def synchronous(self) -> Literal[False]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -515,12 +532,19 @@ class Queue(Class): class Unbind(Method): INDEX: ClassVar[int] - ticket: Incomplete - queue: Incomplete - exchange: Incomplete - routing_key: Incomplete - arguments: Incomplete - def __init__(self, ticket: int = 0, queue: _str = "", exchange=None, routing_key: _str = "", arguments=None) -> None: ... + ticket: int + queue: str + exchange: str | None + routing_key: str + arguments: Mapping[str, Incomplete] | None + def __init__( + self, + ticket: int = 0, + queue: str = "", + exchange: str | None = None, + routing_key: str = "", + arguments: Mapping[str, Incomplete] | None = None, + ) -> None: ... @property def synchronous(self) -> Literal[True]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -539,9 +563,9 @@ class Basic(Class): class Qos(Method): INDEX: ClassVar[int] - prefetch_size: Incomplete - prefetch_count: Incomplete - global_qos: Incomplete + prefetch_size: int + prefetch_count: int + global_qos: bool def __init__(self, prefetch_size: int = 0, prefetch_count: int = 0, global_qos: bool = False) -> None: ... @property def synchronous(self) -> Literal[True]: ... @@ -558,24 +582,24 @@ class Basic(Class): class Consume(Method): INDEX: ClassVar[int] - ticket: Incomplete - queue: Incomplete - consumer_tag: Incomplete + ticket: int + queue: str + consumer_tag: str no_local: bool no_ack: bool exclusive: bool nowait: bool - arguments: Incomplete + arguments: Mapping[str, Incomplete] | None def __init__( self, ticket: int = 0, - queue: _str = "", - consumer_tag: _str = "", + queue: str = "", + consumer_tag: str = "", no_local: bool = False, no_ack: bool = False, exclusive: bool = False, nowait: bool = False, - arguments=None, + arguments: Mapping[str, Incomplete] | None = None, ) -> None: ... @property def synchronous(self) -> Literal[True]: ... @@ -584,8 +608,8 @@ class Basic(Class): class ConsumeOk(Method): INDEX: ClassVar[int] - consumer_tag: Incomplete - def __init__(self, consumer_tag=None) -> None: ... + consumer_tag: str | None + def __init__(self, consumer_tag: str | None = None) -> None: ... @property def synchronous(self) -> Literal[False]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -593,9 +617,9 @@ class Basic(Class): class Cancel(Method): INDEX: ClassVar[int] - consumer_tag: Incomplete + consumer_tag: str | None nowait: bool - def __init__(self, consumer_tag=None, nowait: bool = False) -> None: ... + def __init__(self, consumer_tag: str | None = None, nowait: bool = False) -> None: ... @property def synchronous(self) -> Literal[True]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -603,8 +627,8 @@ class Basic(Class): class CancelOk(Method): INDEX: ClassVar[int] - consumer_tag: Incomplete - def __init__(self, consumer_tag=None) -> None: ... + consumer_tag: str | None + def __init__(self, consumer_tag: str | None = None) -> None: ... @property def synchronous(self) -> Literal[False]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -612,13 +636,13 @@ class Basic(Class): class Publish(Method): INDEX: ClassVar[int] - ticket: Incomplete - exchange: Incomplete - routing_key: Incomplete - mandatory: Incomplete - immediate: Incomplete + ticket: int + exchange: str + routing_key: str + mandatory: bool + immediate: bool def __init__( - self, ticket: int = 0, exchange: _str = "", routing_key: _str = "", mandatory: bool = False, immediate: bool = False + self, ticket: int = 0, exchange: str = "", routing_key: str = "", mandatory: bool = False, immediate: bool = False ) -> None: ... @property def synchronous(self) -> Literal[False]: ... @@ -627,11 +651,13 @@ class Basic(Class): class Return(Method): INDEX: ClassVar[int] - reply_code: Incomplete - reply_text: Incomplete - exchange: Incomplete - routing_key: Incomplete - def __init__(self, reply_code=None, reply_text: _str = "", exchange=None, routing_key=None) -> None: ... + reply_code: int | None + reply_text: str + exchange: str | None + routing_key: str | None + def __init__( + self, reply_code: int | None = None, reply_text: str = "", exchange: str | None = None, routing_key: str | None = None + ) -> None: ... @property def synchronous(self) -> Literal[False]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -639,13 +665,18 @@ class Basic(Class): class Deliver(Method): INDEX: ClassVar[int] - consumer_tag: Incomplete - delivery_tag: Incomplete - redelivered: Incomplete - exchange: Incomplete - routing_key: Incomplete + consumer_tag: str | None + delivery_tag: int | None + redelivered: bool + exchange: str | None + routing_key: str | None def __init__( - self, consumer_tag=None, delivery_tag=None, redelivered: bool = False, exchange=None, routing_key=None + self, + consumer_tag: str | None = None, + delivery_tag: int | None = None, + redelivered: bool = False, + exchange: str | None = None, + routing_key: str | None = None, ) -> None: ... @property def synchronous(self) -> Literal[False]: ... @@ -654,10 +685,10 @@ class Basic(Class): class Get(Method): INDEX: ClassVar[int] - ticket: Incomplete - queue: Incomplete + ticket: int + queue: str no_ack: bool - def __init__(self, ticket: int = 0, queue: _str = "", no_ack: bool = False) -> None: ... + def __init__(self, ticket: int = 0, queue: str = "", no_ack: bool = False) -> None: ... @property def synchronous(self) -> Literal[True]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -665,13 +696,18 @@ class Basic(Class): class GetOk(Method): INDEX: ClassVar[int] - delivery_tag: Incomplete - redelivered: Incomplete - exchange: Incomplete - routing_key: Incomplete - message_count: Incomplete + delivery_tag: int | None + redelivered: bool + exchange: str | None + routing_key: str | None + message_count: int | None def __init__( - self, delivery_tag=None, redelivered: bool = False, exchange=None, routing_key=None, message_count=None + self, + delivery_tag: int | None = None, + redelivered: bool = False, + exchange: str | None = None, + routing_key: str | None = None, + message_count: int | None = None, ) -> None: ... @property def synchronous(self) -> Literal[False]: ... @@ -680,8 +716,8 @@ class Basic(Class): class GetEmpty(Method): INDEX: ClassVar[int] - cluster_id: Incomplete - def __init__(self, cluster_id: _str = "") -> None: ... + cluster_id: str + def __init__(self, cluster_id: str = "") -> None: ... @property def synchronous(self) -> Literal[False]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -689,8 +725,8 @@ class Basic(Class): class Ack(Method): INDEX: ClassVar[int] - delivery_tag: Incomplete - multiple: Incomplete + delivery_tag: int + multiple: bool def __init__(self, delivery_tag: int = 0, multiple: bool = False) -> None: ... @property def synchronous(self) -> Literal[False]: ... @@ -699,9 +735,9 @@ class Basic(Class): class Reject(Method): INDEX: ClassVar[int] - delivery_tag: Incomplete + delivery_tag: int | None requeue: bool - def __init__(self, delivery_tag=None, requeue: bool = True) -> None: ... + def __init__(self, delivery_tag: int | None = None, requeue: bool = True) -> None: ... @property def synchronous(self) -> Literal[False]: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... @@ -735,8 +771,8 @@ class Basic(Class): class Nack(Method): INDEX: ClassVar[int] - delivery_tag: Incomplete - multiple: Incomplete + delivery_tag: int + multiple: bool requeue: bool def __init__(self, delivery_tag: int = 0, multiple: bool = False, requeue: bool = True) -> None: ... @property @@ -816,52 +852,52 @@ class Confirm(Class): def encode(self) -> list[bytes]: ... class BasicProperties(Properties): - CLASS: ClassVar[builtins.type[Basic]] + CLASS: ClassVar[_type[Basic]] INDEX: ClassVar[int] - FLAG_CONTENT_TYPE: ClassVar[int] - FLAG_CONTENT_ENCODING: ClassVar[int] - FLAG_HEADERS: ClassVar[int] - FLAG_DELIVERY_MODE: ClassVar[int] - FLAG_PRIORITY: ClassVar[int] - FLAG_CORRELATION_ID: ClassVar[int] - FLAG_REPLY_TO: ClassVar[int] - FLAG_EXPIRATION: ClassVar[int] - FLAG_MESSAGE_ID: ClassVar[int] - FLAG_TIMESTAMP: ClassVar[int] - FLAG_TYPE: ClassVar[int] - FLAG_USER_ID: ClassVar[int] - FLAG_APP_ID: ClassVar[int] - FLAG_CLUSTER_ID: ClassVar[int] - content_type: _str | None - content_encoding: _str | None + FLAG_CONTENT_TYPE: Final = 32768 + FLAG_CONTENT_ENCODING: Final = 16384 + FLAG_HEADERS: Final = 8192 + FLAG_DELIVERY_MODE: Final = 4096 + FLAG_PRIORITY: Final = 2048 + FLAG_CORRELATION_ID: Final = 1024 + FLAG_REPLY_TO: Final = 512 + FLAG_EXPIRATION: Final = 256 + FLAG_MESSAGE_ID: Final = 128 + FLAG_TIMESTAMP: Final = 64 + FLAG_TYPE: Final = 32 + FLAG_USER_ID: Final = 16 + FLAG_APP_ID: Final = 8 + FLAG_CLUSTER_ID: Final = 4 + content_type: str | None + content_encoding: str | None headers: _ArgumentMapping | None delivery_mode: Literal[1, 2] | None - priority: Incomplete - correlation_id: _str | None - reply_to: _str | None - expiration: _str | None - message_id: _str | None - timestamp: Incomplete - type: _str | None - user_id: _str | None - app_id: _str | None - cluster_id: _str | None + priority: int | None + correlation_id: str | None + reply_to: str | None + expiration: str | None + message_id: str | None + timestamp: int | None + type: str | None + user_id: str | None + app_id: str | None + cluster_id: str | None def __init__( self, - content_type: _str | None = None, - content_encoding: _str | None = None, + content_type: str | None = None, + content_encoding: str | None = None, headers: _ArgumentMapping | None = None, delivery_mode: DeliveryMode | Literal[1, 2] | None = None, - priority=None, - correlation_id: _str | None = None, - reply_to: _str | None = None, - expiration: _str | None = None, - message_id: _str | None = None, - timestamp=None, - type: _str | None = None, - user_id: _str | None = None, - app_id: _str | None = None, - cluster_id: _str | None = None, + priority: int | None = None, + correlation_id: str | None = None, + reply_to: str | None = None, + expiration: str | None = None, + message_id: str | None = None, + timestamp: int | None = None, + type: str | None = None, + user_id: str | None = None, + app_id: str | None = None, + cluster_id: str | None = None, ) -> None: ... def decode(self, encoded: bytes, offset: int = 0) -> Self: ... def encode(self) -> list[bytes]: ... diff --git a/python/helpers/typeshed/stubs/pika/pika/validators.pyi b/python/helpers/typeshed/stubs/pika/pika/validators.pyi index 8fea4a8e7343..07c2bb0f110d 100644 --- a/python/helpers/typeshed/stubs/pika/pika/validators.pyi +++ b/python/helpers/typeshed/stubs/pika/pika/validators.pyi @@ -1,14 +1,15 @@ +from _typeshed import ConvertibleToInt from collections.abc import Callable from typing import Literal, overload def require_string(value: object, value_name: str) -> None: ... # raise TypeError if value is not string def require_callback( - callback: object, callback_name: str = "callback" -) -> None: ... # raise TypeError if callback is not callable + callback: object, callback_name: str = "callback" # raise TypeError if callback is not callable +) -> None: ... @overload def rpc_completion_callback(callback: None) -> Literal[True]: ... @overload def rpc_completion_callback(callback: Callable[..., object]) -> Literal[False]: ... -def zero_or_greater(name: str, value: str | float) -> None: ... +def zero_or_greater(name: str, value: ConvertibleToInt) -> None: ... diff --git a/python/helpers/typeshed/stubs/pony/pony/orm/core.pyi b/python/helpers/typeshed/stubs/pony/pony/orm/core.pyi index 5bee204805bc..d05d3104f456 100644 --- a/python/helpers/typeshed/stubs/pony/pony/orm/core.pyi +++ b/python/helpers/typeshed/stubs/pony/pony/orm/core.pyi @@ -6,8 +6,8 @@ from _typeshed import Incomplete from collections import defaultdict from collections.abc import Callable, Generator from logging import Logger -from typing import Literal, NoReturn, TypeAlias, TypeVar -from typing_extensions import Self, deprecated +from typing import Literal, TypeAlias, TypeVar +from typing_extensions import Never, Self, deprecated import pony as pony from pony.orm.asttranslation import TranslationError as TranslationError @@ -296,7 +296,7 @@ class SQLDebuggingContextManager: sql_debugging: SQLDebuggingContextManager -def throw_db_session_is_over(action: str, obj: Entity, attr: Attribute | None = None) -> NoReturn: ... +def throw_db_session_is_over(action: str, obj: Entity, attr: Attribute | None = None) -> Never: ... @deprecated("@with_transaction decorator is deprecated, use @db_session decorator instead.") def with_transaction(*args, **kwargs): ... @@ -762,7 +762,7 @@ del_statuses: set[str] created_or_deleted_statuses: set[str] saved_statuses: set[str] -def throw_object_was_deleted(obj: Entity) -> NoReturn: ... +def throw_object_was_deleted(obj: Entity) -> Never: ... def unpickle_entity(d): ... def safe_repr(obj: Entity) -> str: ... def make_proxy(obj: Entity) -> EntityProxy: ... @@ -872,7 +872,7 @@ class QueryResultIterator: __next__ = next def __length_hint__(self) -> int: ... -def make_query_result_method_error_stub(name: str, title: str | None = None) -> Callable[..., NoReturn]: ... +def make_query_result_method_error_stub(name: str, title: str | None = None) -> Callable[..., Never]: ... class QueryResult: __slots__ = ("_query", "_limit", "_offset", "_items", "_expr_type", "_col_names") diff --git a/python/helpers/typeshed/stubs/pony/pony/orm/sqltranslation.pyi b/python/helpers/typeshed/stubs/pony/pony/orm/sqltranslation.pyi index 816405de10c2..98b5a66b0bc1 100644 --- a/python/helpers/typeshed/stubs/pony/pony/orm/sqltranslation.pyi +++ b/python/helpers/typeshed/stubs/pony/pony/orm/sqltranslation.pyi @@ -8,8 +8,8 @@ from collections.abc import Generator, Iterable, Sequence from datetime import date, datetime, time, timedelta from decimal import Decimal from random import random -from typing import Any, ClassVar, NoReturn -from typing_extensions import Self +from typing import Any, ClassVar +from typing_extensions import Never, Self from pony.orm import core from pony.orm.asttranslation import ASTTranslator @@ -130,12 +130,12 @@ class SQLTranslator(ASTTranslator): def postAdd(translator, node: ast.Add): ... def postSub(translator, node: ast.Sub): ... def postMult(translator, node: ast.Mult): ... - def postMatMult(translator, node: ast.MatMult) -> NoReturn: ... + def postMatMult(translator, node: ast.MatMult) -> Never: ... def postDiv(translator, node: ast.Div): ... def postFloorDiv(translator, node: ast.FloorDiv): ... def postMod(translator, node: ast.Mod): ... - def postLShift(translator, node: ast.LShift) -> NoReturn: ... - def postRShift(translator, node: ast.RShift) -> NoReturn: ... + def postLShift(translator, node: ast.LShift) -> Never: ... + def postRShift(translator, node: ast.RShift) -> Never: ... def postPow(translator, node: ast.Pow): ... def postUSub(translator, node: ast.USub): ... def postAttribute(translator, node: ast.Attribute): ... @@ -269,8 +269,8 @@ class RawSQLMonad(Monad): typeerror_re_1: re.Pattern[str] typeerror_re_2: re.Pattern[str] -def reraise_improved_typeerror(exc: Exception, func_name: str | tuple[str, ...], orig_func_name: str) -> NoReturn: ... -def raise_forgot_parentheses(monad: Monad) -> NoReturn: ... +def reraise_improved_typeerror(exc: Exception, func_name: str | tuple[str, ...], orig_func_name: str) -> Never: ... +def raise_forgot_parentheses(monad: Monad) -> Never: ... class MethodMonad(Monad): def __init__(monad, parent, attrname) -> None: ... diff --git a/python/helpers/typeshed/stubs/pony/pony/utils/utils.pyi b/python/helpers/typeshed/stubs/pony/pony/utils/utils.pyi index 4817e48c40ab..ffe7c493afff 100644 --- a/python/helpers/typeshed/stubs/pony/pony/utils/utils.pyi +++ b/python/helpers/typeshed/stubs/pony/pony/utils/utils.pyi @@ -6,7 +6,8 @@ from collections.abc import Callable, Iterable from datetime import datetime from threading import local as _localbase from types import CodeType, FunctionType, TracebackType -from typing import Any, NoReturn, overload +from typing import Any, overload +from typing_extensions import Never localbase = _localbase @@ -22,9 +23,9 @@ cut_traceback_depth: int @overload def reraise(exc_type: Unused, exc: None, tb: TracebackType | None) -> None: ... @overload -def reraise(exc_type: Unused, exc: BaseException, tb: TracebackType | None) -> NoReturn: ... +def reraise(exc_type: Unused, exc: BaseException, tb: TracebackType | None) -> Never: ... -def throw(exc_type: Exception | Callable[..., Exception], *args, **kwargs) -> NoReturn: ... +def throw(exc_type: Exception | Callable[..., Exception], *args, **kwargs) -> Never: ... def truncate_repr(s: object, max_len: int = 100) -> str: ... codeobjects: dict[int, CodeType] @@ -34,7 +35,7 @@ def get_codeobject_id(codeobject: CodeType) -> int: ... lambda_args_cache: dict[int | ast.Lambda, list[str]] def get_lambda_args(func: FunctionType | ast.Lambda) -> list[str]: ... -def error_method(*args: Unused, **kwargs: Unused) -> NoReturn: ... +def error_method(*args: Unused, **kwargs: Unused) -> Never: ... def is_ident(string: str) -> bool: ... def split_name(name: str) -> list[str]: ... def uppercase_name(name: str) -> str: ... diff --git a/python/helpers/typeshed/stubs/psycopg2/psycopg2/_psycopg.pyi b/python/helpers/typeshed/stubs/psycopg2/psycopg2/_psycopg.pyi index c40c83048a6e..91e51a53a012 100644 --- a/python/helpers/typeshed/stubs/psycopg2/psycopg2/_psycopg.pyi +++ b/python/helpers/typeshed/stubs/psycopg2/psycopg2/_psycopg.pyi @@ -2,8 +2,8 @@ import datetime as dt from _typeshed import ConvertibleToInt, Incomplete, SupportsRead, SupportsReadline, SupportsWrite, Unused from collections.abc import Callable, Iterable, Mapping, Sequence from types import TracebackType -from typing import Any, Literal, NoReturn, Protocol, TextIO, TypeAlias, TypeVar, overload, type_check_only -from typing_extensions import Self, disjoint_base +from typing import Any, Literal, Protocol, TextIO, TypeAlias, TypeVar, overload, type_check_only +from typing_extensions import Never, Self, disjoint_base from psycopg2.extras import ReplicationCursor as extras_ReplicationCursor from psycopg2.sql import Composable @@ -153,7 +153,7 @@ class cursor: def fetchmany(self, size: int | None = None) -> list[tuple[Any, ...]]: ... def fetchone(self) -> tuple[Any, ...] | None: ... def mogrify(self, query: str | bytes | Composable, vars: _Vars | None = None) -> bytes: ... - def nextset(self) -> NoReturn: ... # not supported + def nextset(self) -> Never: ... # not supported def scroll(self, value: int, mode: Literal["absolute", "relative"] = "relative") -> None: ... def setinputsizes(self, sizes: Unused) -> None: ... def setoutputsize(self, size: int, column: int = ..., /) -> None: ... diff --git a/python/helpers/typeshed/stubs/pyasn1/pyasn1/type/base.pyi b/python/helpers/typeshed/stubs/pyasn1/pyasn1/type/base.pyi index ab443c197304..0e2da760e4e4 100644 --- a/python/helpers/typeshed/stubs/pyasn1/pyasn1/type/base.pyi +++ b/python/helpers/typeshed/stubs/pyasn1/pyasn1/type/base.pyi @@ -1,5 +1,6 @@ from _typeshed import Incomplete, Unused -from typing import NoReturn, final, type_check_only +from typing import final, type_check_only +from typing_extensions import Never from pyasn1.type import constraint, namedtype from pyasn1.type.tag import TagSet @@ -42,7 +43,7 @@ class NoValue: def __getattr__(self, attr) -> None: ... # def __new__..getPlug..plug @type_check_only - def plug(self, *args: Unused, **kw: Unused) -> NoReturn: ... + def plug(self, *args: Unused, **kw: Unused) -> Never: ... # Magic methods assigned dynamically, priority from right to left: plug < str < int < list < dict __abs__ = int.__abs__ __add__ = list.__add__ diff --git a/python/helpers/typeshed/stubs/pycups/METADATA.toml b/python/helpers/typeshed/stubs/pycups/METADATA.toml new file mode 100644 index 000000000000..e8cde2087247 --- /dev/null +++ b/python/helpers/typeshed/stubs/pycups/METADATA.toml @@ -0,0 +1,5 @@ +version = "2.0.*" +upstream-repository = "https://github.com/OpenPrinting/pycups" + +[tool.stubtest] +apt-dependencies = ["libcups2-dev"] diff --git a/python/helpers/typeshed/stubs/pycups/cups.pyi b/python/helpers/typeshed/stubs/pycups/cups.pyi new file mode 100644 index 000000000000..3ccf11bcbd8c --- /dev/null +++ b/python/helpers/typeshed/stubs/pycups/cups.pyi @@ -0,0 +1,899 @@ +from _typeshed import Unused +from collections.abc import Callable, Sequence +from io import IOBase +from typing import Final, Literal, TypeAlias, TypedDict, TypeVar, final, overload, type_check_only +from typing_extensions import NotRequired + +_T = TypeVar("_T") + +_FileOrFd: TypeAlias = IOBase | int + +_CupsDevice = TypedDict( + "_CupsDevice", + {"device-class": str, "device-info": str, "device-make-and-model": str, "device-id": str, "device-location": str}, +) + +_CupsDocument = TypedDict("_CupsDocument", {"file": str, "document-format": NotRequired[str], "document-name": NotRequired[str]}) + +_CupsPPD = TypedDict( + "_CupsPPD", + { + "ppd-natural-language": str, + "ppd-make": str, + "ppd-make-and-model": str, + "ppd-device-id": str, + "ppd-product": str, + "ppd-psversion": str, + "ppd-type": str, + "ppd-model-number": int, + }, +) + +_CupsPPD2 = TypedDict( + "_CupsPPD2", + { + "ppd-natural-language": list[str], + "ppd-make": list[str], + "ppd-make-and-model": list[str], + "ppd-device-id": list[str], + "ppd-product": list[str], + "ppd-psversion": list[str], + "ppd-type": list[str], + "ppd-model-number": list[int], + }, +) + +_CupsJob = TypedDict( + "_CupsJob", + { + "number-of-documents": int, + "job-media-progress": int, + "job-more-info": str, + "job-preserved": bool, + "job-printer-up-time": int, + "job-printer-uri": str, + "job-uri": str, + "printer-uri": str, + "document-format-detected": str, + "document-format": str, + "job-priority": int, + "job-uuid": str, + "date-time-at-completed": str, + "date-time-at-creation": str, + "date-time-at-processing": str, + "time-at-completed": int, + "time-at-creation": int, + "time-at-processing": int, + "job-state": int, + "job-state-reasons": str, + "job-impressions-completed": int, + "job-media-sheets-completed": int, + "job-k-octets": int, + "job-hold-until": str, + "job-sheets": list[str], + "job-printer-state-message": str, + "job-printer-state-reasons": str, + "job-name": str, + "job-originating-user-name": str, + }, +) + +_CupsAttributeInfo = TypedDict( + "_CupsAttributeInfo", {"attributes-charset": str, "attributes-natural-language": str, "job-id": int} +) + +@type_check_only +class _CupsOptionChoice(TypedDict): + choice: str + text: str + marked: bool + +@type_check_only +class _CupsJobWithAttributeInfo(_CupsJob, _CupsAttributeInfo): ... + +_CupsEvent = TypedDict( # noqa: Y049 + "_CupsEvent", + { + "notify-charset": str, + "notify-natural-language": str, + "notify-subscription-id": int, + "notify-sequence-number": int, + "notify-subscribed-event": str, + "printer-up-time": int, + "notify-text": str, + "notify-printer-uri": str, + "printer-name": str, + "printer-state": int, + "printer-state-reasons": list[str], + "printer-is-accepting-jobs": bool, + "notify-job-id": int, + "job-state": int, + "job-name": str, + "job-state-reasons": str, + "job-impressions-completed": int, + }, +) + +_CupsNotifications = TypedDict( + "_CupsNotifications", {"notify-get-interval": int, "printer-up-time": int, "events": list[_CupsEvent]} +) + +_CupsPrinter = TypedDict( + "_CupsPrinter", + { + "marker-change-time": int, + "printer-config-change-date-time": str, + "printer-config-change-time": int, + "printer-current-time": str, + "printer-dns-sd-name": str | None, + "printer-error-policy": str, + "printer-error-policy-supported": list[str], + "printer-icons": str, + "printer-is-accepting-jobs": bool, + "printer-is-shared": bool, + "printer-is-temporary": bool, + "printer-more-info": str, + "printer-op-policy": str, + "printer-state": int, + "printer-state-change-date-time": str, + "printer-state-change-time": int, + "printer-state-message": str, + "printer-state-reasons": list[str], + "printer-strings-uri": str, + "printer-type": int, + "printer-up-time": int, + "printer-uri-supported": list[str], + "queued-job-count": int, + "uri-security-supported": list[str], + "uri-authentication-supported": list[str], + "printer-id": int, + "printer-name": str, + "printer-location": str, + "printer-geo-location": str, + "printer-info": str, + "printer-organization": str, + "printer-organizational-unit": str, + "printer-uuid": str, + "job-quota-period": int, + "job-k-limit": int, + "job-page-limit": int, + "job-sheets-default": tuple[str, str], + "device-uri": str, + "document-format-supported": list[str], + "copies-default": int, + "document-format-default": str, + "job-cancel-after-default": int, + "job-hold-until-default": str, + "job-priority-default": int, + "number-up-default": int, + "notify-lease-duration-default": int, + "notify-events-default": list[str], + "orientation-requested-default": int | None, + "print-color-mode-default": str, + "print-quality-default": int, + "copies-supported": tuple[int, int], + "ipp-features-supported": list[str], + "job-creation-attributes-supported": list[str], + "printer-make-and-model": str, + "finishings-supported": list[int], + "finishings-default": int, + "charset-configured": str, + "charset-supported": list[str], + "compression-supported": list[str], + "cups-version": str, + "generated-natural-language-supported": list[str], + "ipp-versions-supported": list[str], + "ippget-event-life": int, + "job-cancel-after-supported": tuple[int, int], + "job-hold-until-supported": list[str], + "job-ids-supported": bool, + "job-k-octets-supported": tuple[int, int], + "job-priority-supported": list[int], + "job-settable-attributes-supported": list[str], + "job-sheets-supported": list[str], + "jpeg-k-octets-supported": tuple[int, int], + "jpeg-x-dimension-supported": tuple[int, int], + "jpeg-y-dimension-supported": tuple[int, int], + "media-col-supported": list[str], + "multiple-document-handling-supported": list[str], + "multiple-document-jobs-supported": bool, + "multiple-operation-time-out": int, + "multiple-operation-time-out-action": str, + "natural-language-configured": str, + "notify-attributes-supported": list[str], + "notify-lease-duration-supported": tuple[int, int], + "notify-max-events-supported": list[int], + "notify-events-supported": list[str], + "notify-pull-method-supported": list[str], + "notify-schemes-supported": list[str], + "number-up-supported": list[int], + "number-up-layout-supported": list[str], + "operations-supported": list[int], + "orientation-requested-supported": list[int], + "page-delivery-supported": list[str], + "page-ranges-supported": bool, + "pdf-k-octets-supported": tuple[int, int], + "pdf-versions-supported": list[str], + "pdl-override-supported": list[str], + "print-scaling-supported": list[str], + "printer-get-attributes-supported": list[str], + "printer-op-policy-supported": list[str], + "printer-settable-attributes-supported": list[str], + "server-is-sharing-printers": bool, + "which-jobs-supported": list[str], + }, +) + +_CupsPrinterSimple = TypedDict( + "_CupsPrinterSimple", + { + "printer-is-shared": bool, + "printer-state": int, + "printer-state-message": str, + "printer-state-reasons": list[str], + "printer-type": int, + "printer-uri-supported": str, + "printer-location": str, + "printer-info": str, + "device-uri": str, + "printer-make-and-model": str, + }, +) + +_CupsSubscription = TypedDict( + "_CupsSubscription", + { + "notify-events": list[str], + "notify-lease-duration": int, + "notify-pull-method": NotRequired[str], + "notify-recipient-uri": NotRequired[str], + "notify-subscriber-user-name": str, + "notify-time-interval": int, + "notify-subscription-id": int, + }, +) + +CUPS_DEST_FLAGS_CANCELED: Final[int] +CUPS_DEST_FLAGS_CONNECTING: Final[int] +CUPS_DEST_FLAGS_ERROR: Final[int] +CUPS_DEST_FLAGS_MORE: Final[int] +CUPS_DEST_FLAGS_NONE: Final[int] +CUPS_DEST_FLAGS_REMOVED: Final[int] +CUPS_DEST_FLAGS_RESOLVING: Final[int] +CUPS_DEST_FLAGS_UNCONNECTED: Final[int] +CUPS_FORMAT_AUTO: Final[str] +CUPS_FORMAT_COMMAND: Final[str] +CUPS_FORMAT_PDF: Final[str] +CUPS_FORMAT_POSTSCRIPT: Final[str] +CUPS_FORMAT_RAW: Final[str] +CUPS_FORMAT_TEXT: Final[str] +CUPS_PRINTER_AUTHENTICATED: Final[int] +CUPS_PRINTER_BIND: Final[int] +CUPS_PRINTER_BW: Final[int] +CUPS_PRINTER_CLASS: Final[int] +CUPS_PRINTER_COLLATE: Final[int] +CUPS_PRINTER_COLOR: Final[int] +CUPS_PRINTER_COMMANDS: Final[int] +CUPS_PRINTER_COPIES: Final[int] +CUPS_PRINTER_COVER: Final[int] +CUPS_PRINTER_DEFAULT: Final[int] +CUPS_PRINTER_DELETE: Final[int] +CUPS_PRINTER_DISCOVERED: Final[int] +CUPS_PRINTER_DUPLEX: Final[int] +CUPS_PRINTER_FAX: Final[int] +CUPS_PRINTER_IMPLICIT: Final[int] +CUPS_PRINTER_LARGE: Final[int] +CUPS_PRINTER_LOCAL: Final[int] +CUPS_PRINTER_MEDIUM: Final[int] +CUPS_PRINTER_NOT_SHARED: Final[int] +CUPS_PRINTER_OPTIONS: Final[int] +CUPS_PRINTER_PUNCH: Final[int] +CUPS_PRINTER_REJECTING: Final[int] +CUPS_PRINTER_REMOTE: Final[int] +CUPS_PRINTER_SMALL: Final[int] +CUPS_PRINTER_SORT: Final[int] +CUPS_PRINTER_STAPLE: Final[int] +CUPS_PRINTER_VARIABLE: Final[int] +CUPS_SERVER_DEBUG_LOGGING: Final[str] +CUPS_SERVER_REMOTE_ADMIN: Final[str] +CUPS_SERVER_REMOTE_ANY: Final[str] +CUPS_SERVER_REMOTE_PRINTERS: Final[str] +CUPS_SERVER_SHARE_PRINTERS: Final[str] +CUPS_SERVER_USER_CANCEL_ANY: Final[str] +HTTP_AUTHORIZATION_CANCELED: Final[int] +HTTP_BAD_GATEWAY: Final[int] +HTTP_BAD_REQUEST: Final[int] +HTTP_ENCRYPT_ALWAYS: Final[int] +HTTP_ENCRYPT_IF_REQUESTED: Final[int] +HTTP_ENCRYPT_NEVER: Final[int] +HTTP_ENCRYPT_REQUIRED: Final[int] +HTTP_ERROR: Final[int] +HTTP_FORBIDDEN: Final[int] +HTTP_GATEWAY_TIMEOUT: Final[int] +HTTP_NOT_FOUND: Final[int] +HTTP_NOT_IMPLEMENTED: Final[int] +HTTP_NOT_MODIFIED: Final[int] +HTTP_NOT_SUPPORTED: Final[int] +HTTP_OK: Final[int] +HTTP_PKI_ERROR: Final[int] +HTTP_REQUEST_TIMEOUT: Final[int] +HTTP_SERVER_ERROR: Final[int] +HTTP_SERVICE_UNAVAILABLE: Final[int] +HTTP_STATUS_BAD_GATEWAY: Final[int] +HTTP_STATUS_BAD_REQUEST: Final[int] +HTTP_STATUS_CUPS_AUTHORIZATION_CANCELED: Final[int] +HTTP_STATUS_CUPS_PKI_ERROR: Final[int] +HTTP_STATUS_ERROR: Final[int] +HTTP_STATUS_FORBIDDEN: Final[int] +HTTP_STATUS_GATEWAY_TIMEOUT: Final[int] +HTTP_STATUS_NOT_FOUND: Final[int] +HTTP_STATUS_NOT_IMPLEMENTED: Final[int] +HTTP_STATUS_NOT_MODIFIED: Final[int] +HTTP_STATUS_NOT_SUPPORTED: Final[int] +HTTP_STATUS_OK: Final[int] +HTTP_STATUS_REQUEST_TIMEOUT: Final[int] +HTTP_STATUS_SERVER_ERROR: Final[int] +HTTP_STATUS_SERVICE_UNAVAILABLE: Final[int] +HTTP_STATUS_UNAUTHORIZED: Final[int] +HTTP_STATUS_UPGRADE_REQUIRED: Final[int] +HTTP_UNAUTHORIZED: Final[int] +HTTP_UPGRADE_REQUIRED: Final[int] +IPP_ATTRIBUTE: Final[int] +IPP_ATTRIBUTES: Final[int] +IPP_ATTRIBUTES_NOT_SETTABLE: Final[int] +IPP_AUTHENTICATION_CANCELED: Final[int] +IPP_BAD_REQUEST: Final[int] +IPP_CHARSET: Final[int] +IPP_COMPRESSION_ERROR: Final[int] +IPP_COMPRESSION_NOT_SUPPORTED: Final[int] +IPP_CONFLICT: Final[int] +IPP_CREATE_JOB_SUBSCRIPTION: Final[int] +IPP_CREATE_PRINTER_SUBSCRIPTION: Final[int] +IPP_DATA: Final[int] +IPP_DEVICE_ERROR: Final[int] +IPP_DOCUMENT_ACCESS_ERROR: Final[int] +IPP_DOCUMENT_FORMAT: Final[int] +IPP_DOCUMENT_FORMAT_ERROR: Final[int] +IPP_ERROR: Final[int] +IPP_ERROR_JOB_CANCELED: Final[int] +IPP_FINISHINGS_BALE: Final[int] +IPP_FINISHINGS_BIND: Final[int] +IPP_FINISHINGS_BIND_BOTTOM: Final[int] +IPP_FINISHINGS_BIND_LEFT: Final[int] +IPP_FINISHINGS_BIND_RIGHT: Final[int] +IPP_FINISHINGS_BIND_TOP: Final[int] +IPP_FINISHINGS_BOOKLET_MAKER: Final[int] +IPP_FINISHINGS_COVER: Final[int] +IPP_FINISHINGS_EDGE_STITCH: Final[int] +IPP_FINISHINGS_EDGE_STITCH_BOTTOM: Final[int] +IPP_FINISHINGS_EDGE_STITCH_LEFT: Final[int] +IPP_FINISHINGS_EDGE_STITCH_RIGHT: Final[int] +IPP_FINISHINGS_EDGE_STITCH_TOP: Final[int] +IPP_FINISHINGS_FOLD: Final[int] +IPP_FINISHINGS_JOB_OFFSET: Final[int] +IPP_FINISHINGS_NONE: Final[int] +IPP_FINISHINGS_PUNCH: Final[int] +IPP_FINISHINGS_SADDLE_STITCH: Final[int] +IPP_FINISHINGS_STAPLE: Final[int] +IPP_FINISHINGS_STAPLE_BOTTOM_LEFT: Final[int] +IPP_FINISHINGS_STAPLE_BOTTOM_RIGHT: Final[int] +IPP_FINISHINGS_STAPLE_DUAL_BOTTOM: Final[int] +IPP_FINISHINGS_STAPLE_DUAL_LEFT: Final[int] +IPP_FINISHINGS_STAPLE_DUAL_RIGHT: Final[int] +IPP_FINISHINGS_STAPLE_DUAL_TOP: Final[int] +IPP_FINISHINGS_STAPLE_TOP_LEFT: Final[int] +IPP_FINISHINGS_STAPLE_TOP_RIGHT: Final[int] +IPP_FINISHINGS_TRIM: Final[int] +IPP_FORBIDDEN: Final[int] +IPP_GONE: Final[int] +IPP_HEADER: Final[int] +IPP_IDLE: Final[int] +IPP_IGNORED_ALL_NOTIFICATIONS: Final[int] +IPP_IGNORED_ALL_SUBSCRIPTIONS: Final[int] +IPP_INTERNAL_ERROR: Final[int] +IPP_JOB_ABORTED: Final[int] +IPP_JOB_CANCELED: Final[int] +IPP_JOB_COMPLETED: Final[int] +IPP_JOB_HELD: Final[int] +IPP_JOB_PENDING: Final[int] +IPP_JOB_PROCESSING: Final[int] +IPP_JOB_STOPPED: Final[int] +IPP_LANDSCAPE: Final[int] +IPP_MAX_NAME: Final[int] +IPP_MULTIPLE_JOBS_NOT_SUPPORTED: Final[int] +IPP_NOT_ACCEPTING: Final[int] +IPP_NOT_AUTHENTICATED: Final[int] +IPP_NOT_AUTHORIZED: Final[int] +IPP_NOT_FOUND: Final[int] +IPP_NOT_POSSIBLE: Final[int] +IPP_OK: Final[int] +IPP_OK_BUT_CANCEL_SUBSCRIPTION: Final[int] +IPP_OK_CONFLICT: Final[int] +IPP_OK_EVENTS_COMPLETE: Final[int] +IPP_OK_IGNORED_NOTIFICATIONS: Final[int] +IPP_OK_IGNORED_SUBSCRIPTIONS: Final[int] +IPP_OK_SUBST: Final[int] +IPP_OK_TOO_MANY_EVENTS: Final[int] +IPP_OPERATION_NOT_SUPPORTED: Final[int] +IPP_OP_ACTIVATE_PRINTER: Final[int] +IPP_OP_CANCEL_CURRENT_JOB: Final[int] +IPP_OP_CANCEL_JOB: Final[int] +IPP_OP_CANCEL_JOBS: Final[int] +IPP_OP_CANCEL_MY_JOBS: Final[int] +IPP_OP_CANCEL_SUBSCRIPTION: Final[int] +IPP_OP_CLOSE_JOB: Final[int] +IPP_OP_CREATE_JOB: Final[int] +IPP_OP_CREATE_JOB_SUBSCRIPTIONS: Final[int] +IPP_OP_CREATE_PRINTER_SUBSCRIPTIONS: Final[int] +IPP_OP_CUPS_ACCEPT_JOBS: Final[int] +IPP_OP_CUPS_ADD_MODIFY_CLASS: Final[int] +IPP_OP_CUPS_ADD_MODIFY_PRINTER: Final[int] +IPP_OP_CUPS_AUTHENTICATE_JOB: Final[int] +IPP_OP_CUPS_DELETE_CLASS: Final[int] +IPP_OP_CUPS_DELETE_PRINTER: Final[int] +IPP_OP_CUPS_GET_CLASSES: Final[int] +IPP_OP_CUPS_GET_DEFAULT: Final[int] +IPP_OP_CUPS_GET_DOCUMENT: Final[int] +IPP_OP_CUPS_GET_PPD: Final[int] +IPP_OP_CUPS_GET_PPDS: Final[int] +IPP_OP_CUPS_GET_PRINTERS: Final[int] +IPP_OP_CUPS_MOVE_JOB: Final[int] +IPP_OP_CUPS_REJECT_JOBS: Final[int] +IPP_OP_CUPS_SET_DEFAULT: Final[int] +IPP_OP_DEACTIVATE_PRINTER: Final[int] +IPP_OP_DISABLE_PRINTER: Final[int] +IPP_OP_ENABLE_PRINTER: Final[int] +IPP_OP_GET_JOBS: Final[int] +IPP_OP_GET_JOB_ATTRIBUTES: Final[int] +IPP_OP_GET_NOTIFICATIONS: Final[int] +IPP_OP_GET_PRINTER_ATTRIBUTES: Final[int] +IPP_OP_GET_PRINTER_SUPPORTED_VALUES: Final[int] +IPP_OP_GET_PRINT_SUPPORT_FILES: Final[int] +IPP_OP_GET_RESOURCES: Final[int] +IPP_OP_GET_RESOURCE_ATTRIBUTES: Final[int] +IPP_OP_GET_RESOURCE_DATA: Final[int] +IPP_OP_GET_SUBSCRIPTIONS: Final[int] +IPP_OP_HOLD_JOB: Final[int] +IPP_OP_HOLD_NEW_JOBS: Final[int] +IPP_OP_IDENTIFY_PRINTER: Final[int] +IPP_OP_PAUSE_PRINTER: Final[int] +IPP_OP_PAUSE_PRINTER_AFTER_CURRENT_JOB: Final[int] +IPP_OP_PRINT_JOB: Final[int] +IPP_OP_PRINT_URI: Final[int] +IPP_OP_PROMOTE_JOB: Final[int] +IPP_OP_PURGE_JOBS: Final[int] +IPP_OP_RELEASE_HELD_NEW_JOBS: Final[int] +IPP_OP_RELEASE_JOB: Final[int] +IPP_OP_RENEW_SUBSCRIPTION: Final[int] +IPP_OP_REPROCESS_JOB: Final[int] +IPP_OP_RESTART_JOB: Final[int] +IPP_OP_RESTART_PRINTER: Final[int] +IPP_OP_RESUBMIT_JOB: Final[int] +IPP_OP_RESUME_JOB: Final[int] +IPP_OP_RESUME_PRINTER: Final[int] +IPP_OP_SCHEDULE_JOB_AFTER: Final[int] +IPP_OP_SEND_DOCUMENT: Final[int] +IPP_OP_SEND_HARDCOPY_DOCUMENT: Final[int] +IPP_OP_SEND_NOTIFICATIONS: Final[int] +IPP_OP_SEND_URI: Final[int] +IPP_OP_SET_JOB_ATTRIBUTES: Final[int] +IPP_OP_SET_PRINTER_ATTRIBUTES: Final[int] +IPP_OP_SHUTDOWN_PRINTER: Final[int] +IPP_OP_STARTUP_PRINTER: Final[int] +IPP_OP_SUSPEND_CURRENT_JOB: Final[int] +IPP_OP_VALIDATE_DOCUMENT: Final[int] +IPP_OP_VALIDATE_JOB: Final[int] +IPP_ORIENT_LANDSCAPE: Final[int] +IPP_ORIENT_PORTRAIT: Final[int] +IPP_ORIENT_REVERSE_LANDSCAPE: Final[int] +IPP_ORIENT_REVERSE_PORTRAIT: Final[int] +IPP_PKI_ERROR: Final[int] +IPP_PORTRAIT: Final[int] +IPP_PRINTER_BUSY: Final[int] +IPP_PRINTER_IDLE: Final[int] +IPP_PRINTER_IS_DEACTIVATED: Final[int] +IPP_PRINTER_PROCESSING: Final[int] +IPP_PRINTER_STOPPED: Final[int] +IPP_PRINT_SUPPORT_FILE_NOT_FOUND: Final[int] +IPP_QUALITY_DRAFT: Final[int] +IPP_QUALITY_HIGH: Final[int] +IPP_QUALITY_NORMAL: Final[int] +IPP_REDIRECTION_OTHER_SITE: Final[int] +IPP_REQUEST_ENTITY: Final[int] +IPP_REQUEST_VALUE: Final[int] +IPP_RES_PER_CM: Final[int] +IPP_RES_PER_INCH: Final[int] +IPP_REVERSE_LANDSCAPE: Final[int] +IPP_REVERSE_PORTRAIT: Final[int] +IPP_SERVICE_UNAVAILABLE: Final[int] +IPP_STATE_ATTRIBUTE: Final[int] +IPP_STATE_DATA: Final[int] +IPP_STATE_ERROR: Final[int] +IPP_STATE_HEADER: Final[int] +IPP_STATE_IDLE: Final[int] +IPP_STATUS_ERROR_ATTRIBUTES_NOT_SETTABLE: Final[int] +IPP_STATUS_ERROR_ATTRIBUTES_OR_VALUES: Final[int] +IPP_STATUS_ERROR_BAD_REQUEST: Final[int] +IPP_STATUS_ERROR_BUSY: Final[int] +IPP_STATUS_ERROR_CHARSET: Final[int] +IPP_STATUS_ERROR_COMPRESSION_ERROR: Final[int] +IPP_STATUS_ERROR_COMPRESSION_NOT_SUPPORTED: Final[int] +IPP_STATUS_ERROR_CONFLICTING: Final[int] +IPP_STATUS_ERROR_CUPS_AUTHENTICATION_CANCELED: Final[int] +IPP_STATUS_ERROR_CUPS_PKI: Final[int] +IPP_STATUS_ERROR_CUPS_UPGRADE_REQUIRED: Final[int] +IPP_STATUS_ERROR_DEVICE: Final[int] +IPP_STATUS_ERROR_DOCUMENT_ACCESS: Final[int] +IPP_STATUS_ERROR_DOCUMENT_FORMAT_ERROR: Final[int] +IPP_STATUS_ERROR_DOCUMENT_FORMAT_NOT_SUPPORTED: Final[int] +IPP_STATUS_ERROR_FORBIDDEN: Final[int] +IPP_STATUS_ERROR_GONE: Final[int] +IPP_STATUS_ERROR_IGNORED_ALL_NOTIFICATIONS: Final[int] +IPP_STATUS_ERROR_IGNORED_ALL_SUBSCRIPTIONS: Final[int] +IPP_STATUS_ERROR_INTERNAL: Final[int] +IPP_STATUS_ERROR_JOB_CANCELED: Final[int] +IPP_STATUS_ERROR_MULTIPLE_JOBS_NOT_SUPPORTED: Final[int] +IPP_STATUS_ERROR_NOT_ACCEPTING_JOBS: Final[int] +IPP_STATUS_ERROR_NOT_AUTHENTICATED: Final[int] +IPP_STATUS_ERROR_NOT_AUTHORIZED: Final[int] +IPP_STATUS_ERROR_NOT_FOUND: Final[int] +IPP_STATUS_ERROR_NOT_POSSIBLE: Final[int] +IPP_STATUS_ERROR_OPERATION_NOT_SUPPORTED: Final[int] +IPP_STATUS_ERROR_PRINTER_IS_DEACTIVATED: Final[int] +IPP_STATUS_ERROR_PRINT_SUPPORT_FILE_NOT_FOUND: Final[int] +IPP_STATUS_ERROR_REQUEST_ENTITY: Final[int] +IPP_STATUS_ERROR_REQUEST_VALUE: Final[int] +IPP_STATUS_ERROR_SERVICE_UNAVAILABLE: Final[int] +IPP_STATUS_ERROR_TEMPORARY: Final[int] +IPP_STATUS_ERROR_TIMEOUT: Final[int] +IPP_STATUS_ERROR_TOO_MANY_SUBSCRIPTIONS: Final[int] +IPP_STATUS_ERROR_URI_SCHEME: Final[int] +IPP_STATUS_ERROR_VERSION_NOT_SUPPORTED: Final[int] +IPP_STATUS_OK: Final[int] +IPP_STATUS_OK_BUT_CANCEL_SUBSCRIPTION: Final[int] +IPP_STATUS_OK_CONFLICTING: Final[int] +IPP_STATUS_OK_EVENTS_COMPLETE: Final[int] +IPP_STATUS_OK_IGNORED_NOTIFICATIONS: Final[int] +IPP_STATUS_OK_IGNORED_OR_SUBSTITUTED: Final[int] +IPP_STATUS_OK_IGNORED_SUBSCRIPTIONS: Final[int] +IPP_STATUS_OK_TOO_MANY_EVENTS: Final[int] +IPP_STATUS_REDIRECTION_OTHER_SITE: Final[int] +IPP_TAG_BOOLEAN: Final[int] +IPP_TAG_CHARSET: Final[int] +IPP_TAG_ENUM: Final[int] +IPP_TAG_INTEGER: Final[int] +IPP_TAG_JOB: Final[int] +IPP_TAG_KEYWORD: Final[int] +IPP_TAG_LANGUAGE: Final[int] +IPP_TAG_MIMETYPE: Final[int] +IPP_TAG_NAME: Final[int] +IPP_TAG_OPERATION: Final[int] +IPP_TAG_PRINTER: Final[int] +IPP_TAG_RANGE: Final[int] +IPP_TAG_STRING: Final[int] +IPP_TAG_TEXT: Final[int] +IPP_TAG_URI: Final[int] +IPP_TAG_ZERO: Final[int] +IPP_TEMPORARY_ERROR: Final[int] +IPP_TIMEOUT: Final[int] +IPP_TOO_MANY_SUBSCRIPTIONS: Final[int] +IPP_UPGRADE_REQUIRED: Final[int] +IPP_URI_SCHEME: Final[int] +IPP_VERSION_NOT_SUPPORTED: Final[int] +PPD_CONFORM_RELAXED: Final[int] +PPD_CONFORM_STRICT: Final[int] +PPD_ORDER_ANY: Final[int] +PPD_ORDER_DOCUMENT: Final[int] +PPD_ORDER_EXIT: Final[int] +PPD_ORDER_JCL: Final[int] +PPD_ORDER_PAGE: Final[int] +PPD_ORDER_PROLOG: Final[int] +PPD_UI_BOOLEAN: Final[int] +PPD_UI_PICKMANY: Final[int] +PPD_UI_PICKONE: Final[int] + +@final +class Attribute: + @property + def name(self) -> str: ... + @property + def spec(self) -> str: ... + @property + def text(self) -> str: ... + @property + def value(self) -> str: ... + def __init__(self, *args: Unused) -> None: ... + +@final +class Connection: + def __init__(self, host: str = ..., port: int = ..., encryption: int = ...) -> None: ... + def acceptJobs(self, name: str, /) -> None: ... + + @overload + def addPrinter(self, name: str, filename: str = ..., *, info: str = ..., location: str = ..., device: str = ...) -> None: ... + @overload + def addPrinter(self, name: str, *, ppdname: str = ..., info: str = ..., location: str = ..., device: str = ...) -> None: ... + @overload + def addPrinter(self, name: str, *, info: str = ..., location: str = ..., device: str = ..., ppd: PPD = ...) -> None: ... + + def addPrinterOptionDefault(self, name: str, option: str, value: str | int | Sequence[str | int], /) -> None: ... + def addPrinterToClass(self, name: str, _class: str, /) -> None: ... + def adminExportSamba(self, name: str, server: str, user: str, password: str, /): ... + def adminGetServerSettings(self) -> dict[str, str]: ... + def adminSetServerSettings(self, settings: dict[str, str], /) -> None: ... + def authenticateJob(self, jobid: int, auth_info: list[str] = ..., /) -> None: ... + + @overload + def cancelAllJobs(self, name: str, *, my_jobs: bool = False, purge_jobs: bool = True) -> None: ... + @overload + def cancelAllJobs(self, *, uri: str, my_jobs: bool = False, purge_jobs: bool = True) -> None: ... + + def cancelJob(self, job_id: int, purge_job: bool = False) -> None: ... + def cancelSubscription(self, id: int, /) -> None: ... + def createJob(self, printer: str, title: str, options: dict[str, str]) -> int: ... + def createSubscription( + self, + uri: str, + events: list[str] = ..., + job_id: int = ..., + recipient_uri: str = ..., + lease_duration: int = ..., + time_interval: int = ..., + user_data: str = ..., + ) -> int: ... + def deleteClass(self, _class: str, /) -> None: ... + def deletePrinter(self, name: str, /) -> None: ... + def deletePrinterFromClass(self, name: str, _class: str, /) -> None: ... + def deletePrinterOptionDefault(self, name: str, option: str, /) -> None: ... + def disablePrinter(self, name: str, reason: str = ...) -> None: ... + def enablePrinter(self, name: str, /) -> None: ... + def finishDocument(self, printer: str) -> int: ... + def getClasses(self) -> dict[str, str | list[str]]: ... + def getDefault(self) -> str | None: ... + def getDests(self) -> dict[tuple[str, str] | tuple[None, None], Dest]: ... + def getDevices( + self, limit: int = 0, exclude_schemes: list[str] = ..., include_schemes: list[str] = ..., timeout: int = 0 + ) -> dict[str, _CupsDevice]: ... + def getDocument(self, printer_uri: str, job_id: int, document_number: int, /) -> _CupsDocument: ... + + @overload + def getFile(self, resource: str, filename: str = ...) -> None: ... + @overload + def getFile(self, resource: str, *, fd: int) -> None: ... + @overload + def getFile(self, resource: str, *, file: _FileOrFd) -> None: ... + + def getJobAttributes(self, job_id: int, requested_attributes: list[str] = ...) -> _CupsJobWithAttributeInfo: ... + def getJobs( + self, + which_jobs: Literal["completed", "not-completed", "all"] = "not-completed", + my_jobs: bool = False, + limit: int = ..., + first_job_id: int = ..., + requested_attributes: list[str] = ["job-id", "job-uri"], + ) -> dict[int, _CupsJob]: ... + def getNotifications(self, subscription_ids: list[int], sequence_numbers: list[int] = ...) -> _CupsNotifications: ... + def getPPD(self, name: str, /) -> str: ... + def getPPD3(self, name: str, modtime: float = ..., filename: str = ...) -> tuple[int, float, str]: ... + def getPPDs( + self, + limit: int = ..., + exclude_schemes: list[str] = ..., + include_schemes: list[str] = ..., + ppd_natural_language: str = ..., + ppd_device_id: str = ..., + ppd_make: str = ..., + ppd_make_and_model: str = ..., + ppd_model_number: int = ..., + ppd_product: str = ..., + ppd_psversion: str = ..., + ppd_type: str = ..., + ) -> dict[str, _CupsPPD]: ... + def getPPDs2( + self, + limit: int = ..., + exclude_schemes: list[str] = ..., + include_schemes: list[str] = ..., + ppd_natural_language: str = ..., + ppd_device_id: str = ..., + ppd_make: str = ..., + ppd_make_and_model: str = ..., + ppd_model_number: int = ..., + ppd_product: str = ..., + ppd_psversion: str = ..., + ppd_type: str = ..., + ) -> dict[str, _CupsPPD2]: ... + + @overload + def getPrinterAttributes(self, name: str, *, requested_attributes: list[str] = ...) -> _CupsPrinter: ... + @overload + def getPrinterAttributes(self, *, uri: str, requested_attributes: list[str] = ...) -> _CupsPrinter: ... + + def getPrinters(self) -> dict[str, _CupsPrinterSimple]: ... + def getServerPPD(self, ppd_name: str, /) -> str: ... + def getSubscriptions(self, uri: str, my_subscriptions: bool = False, job_id: int = ...) -> list[_CupsSubscription]: ... + + @overload + def moveJob(self, printer_uri: str, job_id: int, job_printer_uri: str) -> None: ... + @overload + def moveJob(self, printer_uri: str, *, job_printer_uri: str) -> None: ... + @overload + def moveJob(self, *, job_id: int, job_printer_uri: str) -> None: ... + + def printFile(self, printer: str, filename: str, title: str, options: dict[str, str]) -> int: ... + def printFiles(self, printer: str, filenames: list[str], title: str, options: dict[str, str]) -> int: ... + def printTestPage(self, name: str) -> int: ... + + @overload + def putFile(self, resource: str, filename: str) -> None: ... + @overload + def putFile(self, resource: str, *, fd: int) -> None: ... + @overload + def putFile(self, resource: str, *, file: _FileOrFd) -> None: ... + + def rejectJobs(self, name: str, reason: str = ...) -> None: ... + def renewSubscription(self, id: int, lease_duration: int = ...) -> None: ... + def restartJob(self, job_id: int, job_hold_until: str = ...) -> None: ... + def setDefault(self, name: str, /) -> None: ... + def setJobHoldUntil(self, job_id: int, job_hold_until: str, /) -> None: ... + def setPrinterDevice(self, name: str, device_uri: str, /) -> None: ... + def setPrinterErrorPolicy(self, name: str, policy: str, /) -> None: ... + def setPrinterInfo(self, name: str, info: str, /) -> None: ... + def setPrinterJobSheets(self, name: str, start: str, end: str, /) -> None: ... + def setPrinterLocation(self, name: str, location: str, /) -> None: ... + def setPrinterOpPolicy(self, name: str, policy: str, /) -> None: ... + def setPrinterShared(self, name: str, shared: bool, /) -> None: ... + def setPrinterUsersAllowed(self, name: str, allowed: list[str], /) -> None: ... + def setPrinterUsersDenied(self, name: str, denied: list[str], /) -> None: ... + def startDocument(self, printer: str, job_id: int, doc_name: str, format: str, last_document: bool) -> int: ... + def writeRequestData(self, buffer: bytes, length: int) -> int: ... + +@final +class Constraint: + @property + def choice1(self) -> str: ... + @property + def choice2(self) -> str: ... + @property + def option1(self) -> str: ... + @property + def option2(self) -> str: ... + def __init__(self, *args: Unused) -> None: ... + +@final +class Dest: + @property + def instance(self) -> str | None: ... + @property + def is_default(self) -> bool: ... + @property + def name(self) -> str: ... + @property + def options(self) -> dict[str, str]: ... + def __init__(self, *args: Unused) -> None: ... + +@final +class Group: + @property + def name(self) -> str: ... + @property + def options(self) -> list[Option]: ... + @property + def subgroups(self) -> list[Group]: ... + @property + def text(self) -> str: ... + def __init__(self, *args: Unused) -> None: ... + +class HTTPError(Exception): ... + +@final +class IPPAttribute: + @property + def group_tag(self) -> int: ... + @property + def name(self) -> str: ... + @property + def value_tag(self) -> int: ... + @property + def values(self) -> list[int | str | bool]: ... + def __init__(self, group_tag: int, value_tag: int, name: str, value: str = ..., /) -> None: ... + +class IPPError(Exception): ... + +@final +class IPPRequest: + @property + def attributes(self) -> list[IPPAttribute]: ... + @property + def operation(self) -> int: ... + + @property + def state(self) -> int: ... + @state.setter + def state(self, value: int) -> None: ... + + @property + def statuscode(self) -> int: ... + @statuscode.setter + def statuscode(self, value: int) -> None: ... + + def __init__(self, op: int = ..., /) -> None: ... + def add(self, attr: IPPAttribute, /) -> IPPAttribute: ... + def addSeparator(self) -> IPPAttribute: ... + def readIO(self, read_fn: Callable[[int], int], blocking: bool = True) -> int: ... + def writeIO(self, write_fn: Callable[[bytes], int], blocking: bool = True) -> int: ... + +@final +class Option: + @property + def choices(self) -> list[_CupsOptionChoice]: ... + @property + def conflicted(self) -> bool: ... + @property + def defchoice(self) -> str: ... + @property + def keyword(self) -> str: ... + @property + def text(self) -> str: ... + @property + def ui(self) -> int: ... + def __init__(self, *args: Unused) -> None: ... + +@final +class PPD: + @property + def attributes(self) -> list[Attribute]: ... + @property + def constraints(self) -> list[Constraint]: ... + @property + def optionGroups(self) -> list[Group]: ... + def __init__(self, filename: str, /) -> None: ... + def conflicts(self) -> int: ... + def emit(self, file: _FileOrFd, section: int, /) -> None: ... + def emitAfterOrder(self, file: _FileOrFd, section: int, limit: int, min_order: float, /) -> None: ... + def emitFd(self, fd: int, section: int, /) -> None: ... + def emitJCL(self, file: _FileOrFd, job_id: int, user: str, title: str, /) -> None: ... + def emitJCLEnd(self, file: _FileOrFd, /) -> None: ... + def emitString(self, section: int, min_order: float, /) -> str: ... + def findAttr(self, name: str, spec: str = ...) -> Attribute | None: ... + def findNextAttr(self, name: str, spec: str = ...) -> Attribute | None: ... + def findOption(self, name: str, /) -> Option | None: ... + def localize(self) -> None: ... + def localizeIPPReason(self, reason: str, scheme: str = ...) -> str | None: ... + def localizeMarkerName(self, name: str, /) -> str | None: ... + def markDefaults(self) -> None: ... + def markOption(self, option: str, choice: str, /) -> int: ... + def nondefaultsMarked(self) -> bool: ... + def writeFd(self, fd: int, /) -> None: ... + +def connectDest( + dest: Dest, cb: Callable[[_T, int, Dest], Literal[0, 1]], flags: int = 0, msec: int = -1, user_data: _T = ... +) -> tuple[Connection, str]: ... +def enumDests( + cb: Callable[[_T, int, Dest], Literal[0, 1]], + flags: int = 0, + msec: int = -1, + type: int = 0, + mask: int = 0, + user_data: _T = ..., +) -> None: ... +def getEncryption() -> int: ... +def getPort() -> int: ... +def getServer() -> str: ... +def getUser() -> str: ... +def ippErrorString(status_code: int, /) -> str: ... +def ippOpString(op: int, /) -> str: ... +def modelSort(s1: str, s2: str, /) -> Literal[-1, 0, 1]: ... +def ppdSetConformance(level: int, /) -> None: ... +def require(version: str, /) -> None: ... +def setEncryption(policy: int, /) -> None: ... +def setPasswordCB(fn: Callable[[str], str | None], /) -> None: ... + +@overload +def setPasswordCB2(fn: Callable[[str, Connection, str, str], str | None] | None, /) -> None: ... +@overload +def setPasswordCB2(fn: Callable[[str, Connection, str, str, _T], str | None], context: _T = ..., /) -> None: ... + +def setPort(port: int, /) -> None: ... +def setServer(server: str, /) -> None: ... +def setUser(user: str, /) -> None: ... diff --git a/python/helpers/typeshed/stubs/pyflakes/pyflakes/api.pyi b/python/helpers/typeshed/stubs/pyflakes/pyflakes/api.pyi index b2f910227c5a..c3e9477ab53e 100644 --- a/python/helpers/typeshed/stubs/pyflakes/pyflakes/api.pyi +++ b/python/helpers/typeshed/stubs/pyflakes/pyflakes/api.pyi @@ -1,7 +1,8 @@ from _typeshed import GenericPath from collections.abc import Iterable, Iterator, Sequence from re import Pattern -from typing import Final, NoReturn +from typing import Final +from typing_extensions import Never from pyflakes.reporter import Reporter @@ -14,4 +15,4 @@ def checkPath(filename: str, reporter: Reporter | None = None) -> int: ... def isPythonFile(filename: str) -> bool: ... def iterSourceCode(paths: Iterable[GenericPath[str]]) -> Iterator[GenericPath[str]]: ... def checkRecursive(paths: Iterable[GenericPath[str]], reporter: Reporter) -> int: ... -def main(prog: str | None = None, args: Sequence[str] | None = None) -> NoReturn: ... +def main(prog: str | None = None, args: Sequence[str] | None = None) -> Never: ... diff --git a/python/helpers/typeshed/stubs/pyjks/jks/jks.pyi b/python/helpers/typeshed/stubs/pyjks/jks/jks.pyi index 7d3bb7d7e0d4..d6c22d6e2998 100644 --- a/python/helpers/typeshed/stubs/pyjks/jks/jks.pyi +++ b/python/helpers/typeshed/stubs/pyjks/jks/jks.pyi @@ -1,7 +1,7 @@ from _typeshed import SupportsKeysAndGetItem, Unused from collections.abc import Iterable -from typing import Final, Literal, NoReturn, TypeAlias, overload -from typing_extensions import Self +from typing import Final, Literal, TypeAlias, overload +from typing_extensions import Never, Self from .util import AbstractKeystore, AbstractKeystoreEntry @@ -107,11 +107,9 @@ class SecretKeyEntry(AbstractKeystoreEntry): # Not implemented by pyjks @classmethod - def new( # type: ignore[override] - cls, alias: str, sealed_obj: bool, algorithm: str, key: bytes, key_size: int - ) -> NoReturn: ... + def new(cls, alias: str, sealed_obj: bool, algorithm: str, key: bytes, key_size: int) -> Never: ... # type: ignore[override] # Not implemented by pyjks - def encrypt(self, key_password: str) -> NoReturn: ... + def encrypt(self, key_password: str) -> Never: ... class KeyStore(AbstractKeystore): entries: dict[str, TrustedCertEntry | PrivateKeyEntry | SecretKeyEntry] # type: ignore[assignment] diff --git a/python/helpers/typeshed/stubs/python-crontab/cronlog.pyi b/python/helpers/typeshed/stubs/python-crontab/cronlog.pyi index 00774e321eb6..2d5d5b8ac5aa 100644 --- a/python/helpers/typeshed/stubs/python-crontab/cronlog.pyi +++ b/python/helpers/typeshed/stubs/python-crontab/cronlog.pyi @@ -13,19 +13,19 @@ class LogReader: size: int read: int pipe: StreamReaderWriter | None - def __init__(self, filename: StrOrBytesPath, mass: int = ...) -> None: ... + def __init__(self, filename: StrOrBytesPath, mass: int = 4096) -> None: ... def __enter__(self) -> Self: ... def __exit__( self, error_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None ) -> None: ... def __iter__(self) -> Iterator[str]: ... - def readlines(self, until: int = ...) -> Generator[tuple[int, str]]: ... + def readlines(self, until: int = 0) -> Generator[tuple[int, str]]: ... def cron_date_to_datetime(cron_str: str) -> datetime: ... class CronLog(LogReader): user: str | None - def __init__(self, filename: StrOrBytesPath = ..., user: str | None = ...) -> None: ... + def __init__(self, filename: StrOrBytesPath = "/var/log/syslog", user: str | None = None) -> None: ... def for_program(self, command: str) -> ProgramLog: ... def __iter__(self) -> dict[str, str | None]: ... # type: ignore[override] diff --git a/python/helpers/typeshed/stubs/python-crontab/crontab.pyi b/python/helpers/typeshed/stubs/python-crontab/crontab.pyi index 9d215a2abfcb..2bd4d755e389 100644 --- a/python/helpers/typeshed/stubs/python-crontab/crontab.pyi +++ b/python/helpers/typeshed/stubs/python-crontab/crontab.pyi @@ -71,7 +71,7 @@ class CronTab: intab: str | None tabfile: str | None def __init__( - self, user: _User = ..., tab: str | None = ..., tabfile: str | None = ..., log: CronLog | str | None = ... + self, user: _User = None, tab: str | None = None, tabfile: str | None = None, log: CronLog | str | None = None ) -> None: ... def __enter__(self) -> Self: ... def __exit__( @@ -83,28 +83,28 @@ class CronTab: def user(self) -> _User: ... @property def user_opt(self) -> dict[str, str]: ... - def read(self, filename: str | None = ...) -> None: ... + def read(self, filename: str | None = None) -> None: ... def append( self, item: CronItem, - line: str = ..., - read: bool = ..., - before: str | re.Pattern[str] | list[CronItem] | tuple[CronItem, ...] | Generator[CronItem] | None = ..., + line: str = "", + read: bool = False, + before: str | re.Pattern[str] | list[CronItem] | tuple[CronItem, ...] | Generator[CronItem] | None = None, ) -> None: ... - def write(self, filename: str | None = ..., user: _User = ..., errors: bool = ...) -> None: ... - def write_to_user(self, user: bool | str = ...) -> None: ... + def write(self, filename: str | None = None, user: _User = None, errors: bool = False) -> None: ... + def write_to_user(self, user: bool | str = True) -> None: ... # Usually `kwargs` are just `now: datetime | None`, but technically this can # work for `CronItem` subclasses, which might define other kwargs. - def run_pending(self, *, now: datetime | None = ..., **kwargs: Any) -> Iterator[str]: ... + def run_pending(self, *, now: datetime | None = None, **kwargs: Any) -> Iterator[str]: ... def run_scheduler(self, timeout: int = -1, cadence: int = 60, warp: bool = False) -> Iterator[str]: ... - def render(self, errors: bool = ...) -> str: ... + def render(self, errors: bool = False) -> str: ... def new( self, - command: str = ..., - comment: str = ..., - user: str | None = ..., - pre_comment: bool = ..., - before: str | re.Pattern[str] | list[CronItem] | tuple[CronItem, ...] | Generator[CronItem] | None = ..., + command: str = "", + comment: str = "", + user: str | None = None, + pre_comment: bool = False, + before: str | re.Pattern[str] | list[CronItem] | tuple[CronItem, ...] | Generator[CronItem] | None = None, ) -> CronItem: ... def find_command(self, command: str | re.Pattern[str]) -> Iterator[CronItem]: ... def find_comment(self, comment: str | re.Pattern[str]) -> Iterator[CronItem]: ... @@ -137,25 +137,25 @@ class CronItem: marker: str | None stdin: str | None slices: CronSlices - def __init__(self, command: str = ..., comment: str = ..., user: _User = ..., pre_comment: bool = ...) -> None: ... + def __init__(self, command: str = "", comment: str = "", user: _User = None, pre_comment: bool = False) -> None: ... def __hash__(self) -> int: ... def __eq__(self, other: object) -> bool: ... @classmethod - def from_line(cls, line: str, user: str | None = ..., cron: CronTab | None = ...) -> Self: ... + def from_line(cls, line: str, user: str | None = None, cron: CronTab | None = None) -> Self: ... def delete(self) -> None: ... - def set_command(self, cmd: str, parse_stdin: bool = ...) -> None: ... - def set_comment(self, cmt: str, pre_comment: bool = ...) -> None: ... + def set_command(self, cmd: str, parse_stdin: bool = False) -> None: ... + def set_comment(self, cmt: str, pre_comment: bool = False) -> None: ... def parse(self, line: str) -> None: ... - def enable(self, enabled: bool = ...) -> bool: ... + def enable(self, enabled: bool = True) -> bool: ... def is_enabled(self) -> bool: ... def is_valid(self) -> bool: ... def render(self) -> str: ... def every_reboot(self) -> None: ... - def every(self, unit: int = ...) -> Every: ... + def every(self, unit: int = 1) -> Every: ... def setall(self, *args: Any) -> None: ... def clear(self) -> None: ... - def frequency(self, year: int | None = ...) -> int: ... - def frequency_per_year(self, year: int | None = ...) -> int: ... + def frequency(self, year: int | None = None) -> int: ... + def frequency_per_year(self, year: int | None = None) -> int: ... def frequency_per_day(self) -> int: ... def frequency_per_hour(self) -> int: ... def frequency_at_year(self, year: int | None = None) -> int: ... @@ -175,9 +175,9 @@ class CronItem: @overload def frequency_at_hour(self, year: None = None, month: None = None, day: None = None, hour: None = None) -> int: ... - def run_pending(self, now: datetime | None = ...) -> int | str: ... + def run_pending(self, now: datetime | None = None) -> int | str: ... def run(self) -> str: ... - def schedule(self, date_from: datetime | None = ...) -> croniter: ... + def schedule(self, date_from: datetime | None = None) -> croniter: ... def description( self, *, @@ -232,8 +232,8 @@ class CronSlices(list[CronSlice]): def clean_render(self) -> str: ... def render(self) -> str: ... def clear(self) -> None: ... - def frequency(self, year: int | None = ...) -> int: ... - def frequency_per_year(self, year: int | None = ...) -> int: ... + def frequency(self, year: int | None = None) -> int: ... + def frequency_per_year(self, year: int | None = None) -> int: ... def frequency_per_day(self) -> int: ... def frequency_per_hour(self) -> int: ... def frequency_at_year(self, year: int | None = None) -> int: ... @@ -274,23 +274,23 @@ class CronSlice: name: str | None enum: list[str | None] | None parts: list[_Part] - def __init__(self, info: int | dict[str, Any], value: str | None = ...) -> None: ... + def __init__(self, info: int | dict[str, Any], value: str | None = None) -> None: ... def __hash__(self) -> int: ... def parse(self, value: str | None) -> None: ... def render(self, resolve: bool = False) -> str: ... def __eq__(self, arg: object) -> bool: ... - def every(self, n_value: int, also: bool = ...) -> _Part: ... + def every(self, n_value: int, also: bool = False) -> _Part: ... # The only known kwarg, others are unused, # `*args`` are passed to `parse_value`, so they are `Any` - def on(self, *n_value: Any, also: bool = ...) -> list[_Part]: ... - def during(self, vfrom: int | str, vto: int | str, also: bool = ...) -> _Part: ... + def on(self, *n_value: Any, also: bool = False) -> list[_Part]: ... + def during(self, vfrom: int | str, vto: int | str, also: bool = False) -> _Part: ... @property def also(self) -> Also: ... def clear(self) -> None: ... def get_range(self, *vrange: int | str | CronValue) -> list[int | CronRange]: ... def __iter__(self) -> Iterator[int]: ... def __len__(self) -> int: ... - def parse_value(self, val: str, sunday: int | None = ...) -> int | CronValue: ... + def parse_value(self, val: str, sunday: int | None = None) -> int | CronValue: ... def test_value(self, value: str, sunday: int | None = None) -> str: ... def get_cronvalue(value: int, enums: list[str]) -> int | CronValue: ... @@ -313,7 +313,7 @@ class CronRange: vto: int | CronValue def parse(self, value: str) -> None: ... def all(self) -> None: ... - def render(self, resolve: bool = ...) -> str: ... + def render(self, resolve: bool = False) -> str: ... def range(self) -> _range: ... def every(self, value: int | str) -> None: ... def __lt__(self, value: object) -> bool: ... diff --git a/python/helpers/typeshed/stubs/python-crontab/crontabs.pyi b/python/helpers/typeshed/stubs/python-crontab/crontabs.pyi index 85fd062dbc18..fcdfb77d8e42 100644 --- a/python/helpers/typeshed/stubs/python-crontab/crontabs.pyi +++ b/python/helpers/typeshed/stubs/python-crontab/crontabs.pyi @@ -3,16 +3,16 @@ from typing import Any from crontab import CronTab class UserSpool(list[CronTab]): - def __init__(self, loc: str, tabs: CronTabs | None = ...) -> None: ... + def __init__(self, loc: str, tabs: CronTabs | None = None) -> None: ... def listdir(self, loc: str) -> list[str]: ... def get_owner(self, path: str) -> str: ... def generate(self, loc: str, username: str) -> CronTab: ... class SystemTab(list[CronTab]): - def __init__(self, loc: str, tabs: CronTabs | None = ...) -> None: ... + def __init__(self, loc: str, tabs: CronTabs | None = None) -> None: ... class AnaCronTab(list[CronTab]): - def __init__(self, loc: str, tabs: CronTabs | None = ...) -> None: ... + def __init__(self, loc: str, tabs: CronTabs | None = None) -> None: ... def add(self, loc: str, item: str, anajob: CronTab) -> CronTab: ... KNOWN_LOCATIONS: list[tuple[UserSpool | SystemTab | AnaCronTab, str]] diff --git a/python/helpers/typeshed/stubs/python-xlib/Xlib/protocol/request.pyi b/python/helpers/typeshed/stubs/python-xlib/Xlib/protocol/request.pyi index 6cc1da72a1e8..1095bbad5cff 100644 --- a/python/helpers/typeshed/stubs/python-xlib/Xlib/protocol/request.pyi +++ b/python/helpers/typeshed/stubs/python-xlib/Xlib/protocol/request.pyi @@ -1,4 +1,5 @@ -from typing import Final, NoReturn +from typing import Final +from typing_extensions import Never from Xlib import display from Xlib.protocol import rq @@ -55,7 +56,7 @@ class ListFonts(rq.ReplyRequest): ... class ListFontsWithInfo(rq.ReplyRequest): def __init__(self, display: display.Display, defer: bool = False, *args: object, **keys: object) -> None: ... - def __getattr__(self, attr: object) -> NoReturn: ... + def __getattr__(self, attr: object) -> Never: ... def __getitem__(self, item: str) -> object: ... def __len__(self) -> int: ... diff --git a/python/helpers/typeshed/stubs/pytz/METADATA.toml b/python/helpers/typeshed/stubs/pytz/METADATA.toml index 98805271a8fe..7af2a69d8106 100644 --- a/python/helpers/typeshed/stubs/pytz/METADATA.toml +++ b/python/helpers/typeshed/stubs/pytz/METADATA.toml @@ -1,3 +1,3 @@ # This is a mirror of https://git.launchpad.net/pytz/tree, see https://pythonhosted.org/pytz/#latest-versions -version = "2026.2" +version = "2026.3.post1" upstream-repository = "https://github.com/stub42/pytz" diff --git a/python/helpers/typeshed/stubs/pywin32/_win32typing.pyi b/python/helpers/typeshed/stubs/pywin32/_win32typing.pyi index b1055116e6b8..4e61a1565645 100644 --- a/python/helpers/typeshed/stubs/pywin32/_win32typing.pyi +++ b/python/helpers/typeshed/stubs/pywin32/_win32typing.pyi @@ -1,7 +1,7 @@ # Not available at runtime. Contains type definitions that are otherwise not exposed and not part of a specific module. from _typeshed import Incomplete, Unused from collections.abc import Iterable, Sequence -from typing import Literal, NoReturn, SupportsIndex, TypeAlias, TypedDict, final, overload, type_check_only +from typing import Literal, SupportsIndex, TypeAlias, TypedDict, final, overload, type_check_only from typing_extensions import Never, Required, Self, deprecated, disjoint_base from win32.lib.pywintypes import TimeType @@ -1038,7 +1038,7 @@ class PyGetSignerCertificate: ... @disjoint_base class PyHANDLE: # type: ignore[type-var] - def __new__(cls, *args: Never) -> NoReturn: ... + def __new__(cls, *args: Never) -> Never: ... @property def handle(self) -> int: ... def Close(self) -> None: ... @@ -3807,7 +3807,7 @@ class PyIFolderView: def GetFolder(self, riid: PyIID | None, /): ... def Item(self, iItemIndex: int, /): ... def ItemCount(self, uFlags: int, /): ... - def Items(self) -> NoReturn: ... # Not Implemented + def Items(self) -> Never: ... # Not Implemented def GetSelectionMarkedItem(self): ... def GetFocusedItem(self): ... def GetItemPosition(self, pidl: PyIDL | None, /): ... @@ -3815,7 +3815,7 @@ class PyIFolderView: def GetDefaultSpacing(self): ... def GetAutoArrange(self): ... def SelectItem(self, iItem: int, dwFlags: int, /): ... - def SelectAndPositionItems(self) -> NoReturn: ... # Not Implemented + def SelectAndPositionItems(self) -> Never: ... # Not Implemented def SelectAndPositionItem(self, apidl: PyIDL | None, pt: tuple[int, int], dwFlags: int, /): ... class PyIIdentityName: ... diff --git a/python/helpers/typeshed/stubs/pywin32/win32/win32console.pyi b/python/helpers/typeshed/stubs/pywin32/win32/win32console.pyi index ca6c0661ba0c..e007253a2637 100644 --- a/python/helpers/typeshed/stubs/pywin32/win32/win32console.pyi +++ b/python/helpers/typeshed/stubs/pywin32/win32/win32console.pyi @@ -1,4 +1,5 @@ -from typing import Literal, NoReturn, overload +from typing import Literal, overload +from typing_extensions import Never import _win32typing from win32.lib.pywintypes import error as error @@ -25,7 +26,7 @@ def SetConsoleTitle(ConsoleTitle: str) -> None: ... def GetConsoleTitle(): ... @overload -def GenerateConsoleCtrlEvent(CtrlEvent: Literal[1], ProcessGroupId: Literal[0] = 0) -> NoReturn: ... +def GenerateConsoleCtrlEvent(CtrlEvent: Literal[1], ProcessGroupId: Literal[0] = 0) -> Never: ... @overload def GenerateConsoleCtrlEvent(CtrlEvent: Literal[0, 1], ProcessGroupId: int) -> None: ... diff --git a/python/helpers/typeshed/stubs/pywin32/win32com/client/gencache.pyi b/python/helpers/typeshed/stubs/pywin32/win32com/client/gencache.pyi index e12756df8887..9f72ce3009aa 100644 --- a/python/helpers/typeshed/stubs/pywin32/win32com/client/gencache.pyi +++ b/python/helpers/typeshed/stubs/pywin32/win32com/client/gencache.pyi @@ -2,7 +2,8 @@ from _typeshed import Incomplete, Unused from collections.abc import Generator from contextlib import contextmanager from types import ModuleType -from typing import Literal, NoReturn +from typing import Literal +from typing_extensions import Never from win32.lib.pywintypes import IIDType from win32com.client import dynamic @@ -60,4 +61,4 @@ def EnsureDispatch( def AddModuleToCache(typelibclsid, lcid, major, minor, verbose: Unused = 1, bFlushNow: bool | Literal[0, 1] = ...) -> None: ... def GetGeneratedInfos() -> list[tuple[Incomplete, Incomplete, Incomplete, Incomplete]]: ... def Rebuild(verbose: bool | Literal[0, 1] = 1) -> None: ... -def usage() -> NoReturn: ... +def usage() -> Never: ... diff --git a/python/helpers/typeshed/stubs/pywin32/win32comext/axscript/client/framework.pyi b/python/helpers/typeshed/stubs/pywin32/win32comext/axscript/client/framework.pyi index 270eddc67a58..19de3698f06a 100644 --- a/python/helpers/typeshed/stubs/pywin32/win32comext/axscript/client/framework.pyi +++ b/python/helpers/typeshed/stubs/pywin32/win32comext/axscript/client/framework.pyi @@ -1,5 +1,5 @@ from _typeshed import Incomplete -from typing import NoReturn +from typing_extensions import Never def RemoveCR(text): ... @@ -20,7 +20,7 @@ class SafeOutput: def MakeValidSysOuts() -> None: ... def trace(*args) -> None: ... -def RaiseAssert(scode, desc) -> NoReturn: ... +def RaiseAssert(scode, desc) -> Never: ... class AXScriptCodeBlock: name: Incomplete @@ -143,7 +143,7 @@ class COMScript: def CompileInScriptedSection(self, codeBlock: AXScriptCodeBlock, type, realCode=None): ... def ExecInScriptedSection(self, codeBlock: AXScriptCodeBlock, globals, locals=None): ... def EvalInScriptedSection(self, codeBlock, globals, locals=None): ... - def HandleException(self, codeBlock: AXScriptCodeBlock | None) -> NoReturn: ... + def HandleException(self, codeBlock: AXScriptCodeBlock | None) -> Never: ... def BeginScriptedSection(self) -> None: ... def EndScriptedSection(self) -> None: ... def DisableInterrupts(self) -> None: ... diff --git a/python/helpers/typeshed/stubs/rasterio/@tests/stubtest_allowlist.txt b/python/helpers/typeshed/stubs/rasterio/@tests/stubtest_allowlist.txt new file mode 100644 index 000000000000..ce1edb64708e --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/@tests/stubtest_allowlist.txt @@ -0,0 +1,43 @@ +# Stubs-only helper modules with no runtime counterpart. +rasterio\._typing +rasterio\._affine_types + +# Stubs-only type aliases referenced in signatures only. +rasterio\.merge\.MethodFunction + +# Cython implementation-detail attributes auto-generated on every +# Cython-compiled module and extension class. +.*\.__pyx_capi__ +.*\.__test__ +.*\.__reduce_cython__ +.*\.__setstate_cython__ + +# attrs-generated introspection helpers on every @attr.s class. +.*\.__attrs_attrs__ +.*\.__attrs_own_setattr__ +.*\.__attrs_props__ + +# attrs-generated comparators and pattern-matching dunders on the +# specific @attr.s classes in the package (these are auto-generated by +# `order=True` / `eq=True`; not part of the documented API surface). +rasterio\._path\._ParsedPath\.__(ge|gt|le|lt|match_args|replace)__ +rasterio\._path\._UnparsedPath\.__(ge|gt|le|lt|match_args|replace)__ +rasterio\.env\.GDALVersion\.__(ge|gt|le|lt|match_args|replace)__ +rasterio\.rpc\.RPC\.__(ge|gt|le|lt|match_args|replace)__ +rasterio\.windows\.Window\.__(ge|gt|le|lt|match_args|replace)__ + +# Cython param-name drift and @disjoint_base markers for private +# extension modules. Public API surface is reconciled in the +# corresponding public `rasterio.*` modules. +rasterio\._base.* +rasterio\._io.* +rasterio\._env.* +rasterio\._err.* +rasterio\._features.* +rasterio\._transform.* + +# Vendored third-party packages — not part of rasterio's public API. +rasterio\._vendor\..* + +# Click-based CLI subpackage — not exposed through type-checked imports. +rasterio\.rio.* diff --git a/python/helpers/typeshed/stubs/rasterio/METADATA.toml b/python/helpers/typeshed/stubs/rasterio/METADATA.toml new file mode 100644 index 000000000000..9988aeddf71d --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/METADATA.toml @@ -0,0 +1,7 @@ +version = "1.5.*" +upstream-repository = "https://github.com/rasterio/rasterio" +requires-python = ">=3.12" +dependencies = ["numpy>=2", "click>=8"] + +[tool.stubtest] +stubtest-dependencies = ["rasterio==1.5.*"] diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/__init__.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/__init__.pyi new file mode 100644 index 000000000000..0fe6afa52c86 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/__init__.pyi @@ -0,0 +1,132 @@ +import logging +import os +from collections.abc import Callable, Sequence +from typing import Any, Final, Literal, NamedTuple, TypeAlias, overload + +from numpy.typing import DTypeLike, NDArray +from rasterio._base import DatasetBase as DatasetBase +from rasterio._io import Statistics as Statistics +from rasterio._path import _parse_path as _parse_path, _UnparsedPath as _UnparsedPath +from rasterio._show_versions import show_versions as show_versions +from rasterio._typing import AnyDataset, CRSInput, _Opener, _OpenOption +from rasterio._version import ( + gdal_version as gdal_version, + get_geos_version as get_geos_version, + get_proj_version as get_proj_version, +) +from rasterio._vsiopener import _opener_registration as _opener_registration +from rasterio.crs import CRS as CRS +from rasterio.drivers import driver_from_extension as driver_from_extension, is_blacklisted as is_blacklisted +from rasterio.dtypes import ( + bool_ as bool_, + check_dtype as check_dtype, + complex_ as complex_, + complex_int16 as complex_int16, + float16 as float16, + float32 as float32, + float64 as float64, + int8 as int8, + int16 as int16, + int32 as int32, + int64 as int64, + sbyte as sbyte, + ubyte as ubyte, + uint8 as uint8, + uint16 as uint16, + uint32 as uint32, + uint64 as uint64, +) +from rasterio.env import Env as Env, ensure_env_with_credentials as ensure_env_with_credentials +from rasterio.errors import ( + DriverCapabilityError as DriverCapabilityError, + RasterioDeprecationWarning as RasterioDeprecationWarning, + RasterioIOError as RasterioIOError, +) +from rasterio.io import ( + BufferedDatasetWriter as BufferedDatasetWriter, + DatasetReader as DatasetReader, + DatasetWriter as DatasetWriter, + FilePath as FilePath, + MemoryFile as MemoryFile, + get_writer_for_driver as get_writer_for_driver, + get_writer_for_path as get_writer_for_path, +) +from rasterio.profiles import default_gtiff_profile as default_gtiff_profile +from rasterio.transform import Affine as Affine, guard_transform as guard_transform + +__all__ = ["CRS", "Band", "Env", "band", "open", "pad"] + +__version__: Final[str] +__gdal_version__: Final[str] +__proj_version__: Final[str] +__geos_version__: Final[str] + +have_vsi_plugin: Final[bool] +log: logging.Logger + +_Fp: TypeAlias = str | os.PathLike[str] | MemoryFile | FilePath + +@overload +def open( + fp: _Fp, + mode: Literal["r"] = "r", + driver: str | Sequence[str] | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + sharing: bool = False, + thread_safe: bool = False, + opener: _Opener | None = None, + **kwargs: _OpenOption, +) -> DatasetReader: ... +@overload +def open( + fp: _Fp, + mode: Literal["r+", "w", "w+"], + driver: str | Sequence[str] | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + sharing: bool = False, + thread_safe: bool = False, + opener: _Opener | None = None, + **kwargs: _OpenOption, +) -> DatasetWriter: ... +@overload +def open( + fp: _Fp, + mode: str = "r", + driver: str | Sequence[str] | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + sharing: bool = False, + thread_safe: bool = False, + opener: _Opener | None = None, + **kwargs: _OpenOption, +) -> DatasetReader | DatasetWriter: ... + +class Band(NamedTuple): + ds: AnyDataset + bidx: int | Sequence[int] + dtype: str + shape: tuple[int, ...] + +def band(ds: AnyDataset, bidx: int | Sequence[int]) -> Band: ... + +# `mode` and `**kwargs` mirror `numpy.pad`'s signature; see numpy.pad documentation. +def pad( + array: NDArray[Any], transform: Affine, pad_width: int, mode: str | Callable[..., Any] | None = None, **kwargs: Any +) -> tuple[NDArray[Any], Affine]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/_affine_types.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/_affine_types.pyi new file mode 100644 index 000000000000..bf462c70813f --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/_affine_types.pyi @@ -0,0 +1,4 @@ +# Swap to `from affine import Affine as Affine` once affine ships `py.typed` (v3). +from typing import Any, TypeAlias + +Affine: TypeAlias = Any diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/_base.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/_base.pyi new file mode 100644 index 000000000000..8a7b76903797 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/_base.pyi @@ -0,0 +1,172 @@ +import logging +import os +from collections.abc import Iterable, Sequence +from types import TracebackType +from typing import Any, Final +from typing_extensions import Self, deprecated + +from rasterio._affine_types import Affine +from rasterio._path import _ParsedPath, _UnparsedPath +from rasterio._typing import Colormap, CRSInput, _OpenOption +from rasterio.control import GroundControlPoint +from rasterio.coords import BoundingBox +from rasterio.crs import CRS +from rasterio.enums import ColorInterp, Compression, Interleaving, MaskFlags, PhotometricInterp +from rasterio.profiles import Profile +from rasterio.rpc import RPC +from rasterio.windows import Window + +log: Final[logging.Logger] + +def get_dataset_driver(path: str) -> str: ... +def driver_supports_mode(drivername: str, creation_mode: str) -> bool: ... +def driver_can_create(drivername: str) -> bool: ... +def driver_can_create_copy(drivername: str) -> bool: ... +def tastes_like_gdal(seq: Affine | Sequence[float]) -> bool: ... +def _raster_driver_extensions() -> dict[str, str]: ... +def _can_create_osr(crs: CRSInput) -> bool: ... +def _transform( + src_crs: CRSInput, dst_crs: CRSInput, xs: Sequence[float], ys: Sequence[float], zs: Sequence[float] | None +) -> tuple[list[float], list[float], list[float]]: ... + +class DatasetBase: + name: str + mode: str + options: dict[str, Any] + width: int + height: int + shape: tuple[int, int] + driver: str + + def __init__( + self, + path: str | os.PathLike[str] | _ParsedPath | _UnparsedPath | None = None, + driver: str | Sequence[str] | None = None, + sharing: bool = False, + thread_safe: bool = False, + **kwargs: _OpenOption, + ) -> None: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def read_crs(self) -> CRS | None: ... + def read_transform(self) -> list[float]: ... + def start(self) -> None: ... + def stop(self) -> None: ... + def close(self) -> None: ... + @property + def closed(self) -> bool: ... + @property + def count(self) -> int: ... + @property + def indexes(self) -> tuple[int, ...]: ... + @property + def dtypes(self) -> tuple[str, ...]: ... + @property + def block_shapes(self) -> tuple[tuple[int, int], ...]: ... + def get_nodatavals(self) -> tuple[float | None, ...]: ... + @property + def nodatavals(self) -> tuple[float | None, ...]: ... + + @property + def nodata(self) -> float | None: ... + @nodata.setter + def nodata(self, value: float | None) -> None: ... + + @property + def mask_flag_enums(self) -> tuple[list[MaskFlags], ...]: ... + + @property + def crs(self) -> CRS: ... + @crs.setter + def crs(self, value: CRSInput) -> None: ... + + @property + def descriptions(self) -> tuple[str | None, ...]: ... + @descriptions.setter + def descriptions(self, value: Sequence[str | None]) -> None: ... + + def write_transform(self, transform: Sequence[float]) -> None: ... + + @property + def transform(self) -> Affine: ... + @transform.setter + def transform(self, value: Affine) -> None: ... + + @property + def offsets(self) -> tuple[float, ...]: ... + @offsets.setter + def offsets(self, value: Sequence[float]) -> None: ... + + @property + def scales(self) -> tuple[float, ...]: ... + @scales.setter + def scales(self, value: Sequence[float]) -> None: ... + + @property + def units(self) -> tuple[str | None, ...]: ... + @units.setter + def units(self, value: Sequence[str | None]) -> None: ... + + def block_window(self, bidx: int, i: int, j: int) -> Window: ... + def block_size(self, bidx: int, i: int, j: int) -> int: ... + def block_windows(self, bidx: int = 0) -> Iterable[tuple[tuple[int, int], Window]]: ... + @property + def bounds(self) -> BoundingBox: ... + @property + def res(self) -> tuple[float, float]: ... + @property + def meta(self) -> dict[str, Any]: ... + @property + def compression(self) -> Compression | None: ... + @property + def interleaving(self) -> Interleaving | None: ... + @property + def photometric(self) -> PhotometricInterp | None: ... + @property + @deprecated("DatasetBase.is_tiled will be removed in a future rasterio release; inspect block_shapes / profile directly.") + def is_tiled(self) -> bool: ... + @property + def profile(self) -> Profile: ... + def lnglat(self) -> tuple[float, float]: ... + def get_transform(self) -> list[float]: ... + @property + def subdatasets(self) -> list[str]: ... + def tag_namespaces(self, bidx: int = 0) -> list[str]: ... + def tags(self, bidx: int = 0, ns: str | None = None) -> dict[str, str]: ... + def get_tag_item(self, ns: str, dm: str | None = None, bidx: int = 0, ovr: int | None = None) -> str | None: ... + + @property + def colorinterp(self) -> tuple[ColorInterp, ...]: ... + @colorinterp.setter + def colorinterp(self, value: Sequence[ColorInterp]) -> None: ... + + def colormap(self, bidx: int) -> Colormap: ... + def overviews(self, bidx: int) -> list[int]: ... + def checksum(self, bidx: int, window: Window | None = None) -> int: ... + def get_gcps(self) -> tuple[list[GroundControlPoint], CRS]: ... + + @property + def gcps(self) -> tuple[list[GroundControlPoint], CRS]: ... + @gcps.setter + def gcps(self, value: tuple[Sequence[GroundControlPoint], CRSInput]) -> None: ... + + @property + def rpcs(self) -> RPC | None: ... + @rpcs.setter + def rpcs(self, value: RPC | None) -> None: ... + + @property + def files(self) -> list[str]: ... + +_GDAL_AT_LEAST_3_10: Final[bool] + +complex64: Final[str] +complex128: Final[str] +complex_int16: Final[str] +float32: Final[str] +float64: Final[str] +int16: Final[str] + +def _parse_path(path: str) -> _ParsedPath | _UnparsedPath: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/_env.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/_env.pyi new file mode 100644 index 000000000000..60dadbc6b7b2 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/_env.pyi @@ -0,0 +1,43 @@ +from contextlib import AbstractContextManager +from typing import Final + +from rasterio._typing import _GDALOption as _GDALOption + +ca_bundle: Final[str] +code_map: Final[dict[int, int]] +level_map: Final[dict[int, int]] + +def gdal_version() -> str: ... +def get_gdal_config(key: str, normalize: bool = True) -> _GDALOption: ... +def set_gdal_config(key: str, val: _GDALOption, normalize: bool = True) -> None: ... +def del_gdal_config(key: str) -> None: ... +def get_gdal_data() -> str | None: ... +def get_proj_data_search_paths() -> list[str]: ... +def set_proj_data_search_path(path: str) -> None: ... +def driver_count() -> int: ... +def catch_errors() -> AbstractContextManager[None]: ... + +class ConfigEnv: + options: dict[str, _GDALOption] + def __init__(self, **options: _GDALOption) -> None: ... + def update_config_options(self, **kwargs: _GDALOption) -> None: ... + def clear_config_options(self) -> None: ... + def get_config_options(self) -> dict[str, _GDALOption]: ... + +class GDALEnv(ConfigEnv): + def __init__(self, **options: _GDALOption) -> None: ... + def start(self) -> None: ... + def stop(self) -> None: ... + +class GDALDataFinder: + def find_file(self, basename: str) -> str | None: ... + def search(self, prefix: str | None = None) -> str | None: ... + def search_wheel(self, prefix: str | None = None) -> str | None: ... + def search_prefix(self, prefix: str) -> str | None: ... + def search_debian(self, prefix: str) -> str | None: ... + +class PROJDataFinder: + def has_data(self) -> bool: ... + def search(self, prefix: str | None = None) -> str | None: ... + def search_wheel(self, prefix: str | None = None) -> str | None: ... + def search_prefix(self, prefix: str) -> str | None: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/_err.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/_err.pyi new file mode 100644 index 000000000000..84e6be115d76 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/_err.pyi @@ -0,0 +1,41 @@ +from contextlib import AbstractContextManager +from enum import IntEnum +from typing import Final + +class GDALError(IntEnum): + none = 0 + debug = 1 + warning = 2 + failure = 3 + fatal = 4 + +class CPLE_BaseError(Exception): + error: int + errno: int + errmsg: str + def __init__(self, error: int, errno: int, errmsg: str) -> None: ... + +class CPLE_AppDefinedError(CPLE_BaseError): ... +class CPLE_AssertionFailedError(CPLE_BaseError): ... +class CPLE_FileIOError(CPLE_BaseError): ... +class CPLE_HttpResponseError(CPLE_BaseError): ... +class CPLE_IllegalArgError(CPLE_BaseError): ... +class CPLE_NoWriteAccessError(CPLE_BaseError): ... +class CPLE_NotSupportedError(CPLE_BaseError): ... +class CPLE_OpenFailedError(CPLE_BaseError): ... +class CPLE_OutOfMemoryError(CPLE_BaseError): ... +class CPLE_UserInterruptError(CPLE_BaseError): ... +class CPLE_AWSAccessDeniedError(CPLE_BaseError): ... +class CPLE_AWSBucketNotFoundError(CPLE_BaseError): ... +class CPLE_AWSError(CPLE_BaseError): ... +class CPLE_AWSInvalidCredentialsError(CPLE_BaseError): ... +class CPLE_AWSObjectNotFoundError(CPLE_BaseError): ... +class CPLE_AWSSignatureDoesNotMatchError(CPLE_BaseError): ... +class ObjectNullError(CPLE_BaseError): ... + +exception_map: Final[dict[int, type[CPLE_BaseError]]] + +class StackChecker: + def __init__(self) -> None: ... + +def stack_errors() -> AbstractContextManager[StackChecker]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/_features.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/_features.pyi new file mode 100644 index 000000000000..2fec9414185a --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/_features.pyi @@ -0,0 +1,34 @@ +from collections.abc import Iterator +from typing import Any, Final + +from rasterio._typing import _OGRGeometry +from rasterio.enums import MergeAlg as MergeAlg + +GEOMETRY_TYPES: Final[dict[int, str]] +GEOJSON2OGR_GEOMETRY_TYPES: Final[dict[str, int]] + +bool_: Final[str] +int8: Final[str] +int16: Final[str] +int32: Final[str] +int64: Final[str] +uint8: Final[str] +uint16: Final[str] +uint32: Final[str] +uint64: Final[str] +float16: Final[str] +float32: Final[str] +float64: Final[str] + +# Cython-side builders. `geom` arguments are opaque C structs / OGR +# geometry handles passed through `__pyx_capi__`; not surfaced via the +# public `rasterio.features` API. +class GeomBuilder: + def build(self, geom: object) -> dict[str, Any]: ... + +class OGRGeomBuilder: + def build(self, geom: dict[str, Any]) -> _OGRGeometry: ... + +class ShapeIterator: + def __iter__(self) -> Iterator[tuple[dict[str, Any], float]]: ... + def __next__(self) -> tuple[dict[str, Any], float]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/_filepath.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/_filepath.pyi new file mode 100644 index 000000000000..0cd22e067c4c --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/_filepath.pyi @@ -0,0 +1,14 @@ +from typing import TypeVar + +_FileT = TypeVar("_FileT") + +class FilePathBase: + # Cython base for FilePath; constructor and overall surface are + # implementation details — see `rasterio.io.FilePath` for the public API. + def __init__(self, *args: object, **kwargs: object) -> None: ... + def close(self) -> None: ... + def exists(self) -> bool: ... + +# Clones any file-like object (BytesIO, MemoryFile, fsspec file, Python +# file object); the returned object has the same concrete type as `fobj`. +def clone_file_obj(fobj: _FileT) -> _FileT: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/_io.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/_io.pyi new file mode 100644 index 000000000000..671d0067b07f --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/_io.pyi @@ -0,0 +1,177 @@ +import os +from collections.abc import Iterator, Sequence +from typing import Any, BinaryIO, Final +from typing_extensions import Self, deprecated + +import numpy as np +from numpy.typing import DTypeLike, NDArray +from rasterio._affine_types import Affine +from rasterio._base import DatasetBase +from rasterio._path import _ParsedPath, _UnparsedPath +from rasterio._typing import Colormap, CRSInput, Indexes, NumType, ShapeND, WindowInput, _GDALOption, _OpenOption +from rasterio.control import GroundControlPoint +from rasterio.enums import Resampling +from rasterio.rpc import RPC + +def validate_resampling(resampling: Resampling) -> None: ... +def virtual_file_to_buffer(filename: str) -> bytes: ... +def _is_complex_int(dtype: DTypeLike) -> bool: ... +def _getnpdtype(dtype: DTypeLike) -> np.dtype[Any]: ... +def _gdal_typename(dt: DTypeLike) -> str: ... +def _get_gdal_dtype(type_name: DTypeLike) -> int: ... +def _boundless_vrt_doc( + src_dataset: DatasetBase, + nodata: float | None = None, + background: float | None = None, + hidenodata: bool = False, + width: int | None = None, + height: int | None = None, + transform: Affine | None = None, + masked: bool = False, + resampling: Resampling = ..., +) -> str: ... +def sample_gen( + dataset: DatasetBase, xy: Sequence[tuple[float, float]], indexes: Indexes | None = None, masked: bool = False +) -> Iterator[NDArray[Any]]: ... + +class Statistics: + min: float + max: float + mean: float + std: float + def __init__(self, min: float, max: float, mean: float, std: float) -> None: ... + +class DatasetReaderBase(DatasetBase): + def read( + self, + indexes: Indexes | None = None, + out: NDArray[Any] | None = None, + window: WindowInput | None = None, + masked: bool = False, + out_shape: ShapeND | None = None, + boundless: bool = False, + resampling: Resampling = ..., + fill_value: NumType | None = None, + out_dtype: DTypeLike | None = None, + ) -> NDArray[Any]: ... + def read_masks( + self, + indexes: Indexes | None = None, + out: NDArray[Any] | None = None, + out_shape: ShapeND | None = None, + window: WindowInput | None = None, + boundless: bool = False, + resampling: Resampling = ..., + ) -> NDArray[Any]: ... + def dataset_mask( + self, + out: NDArray[Any] | None = None, + out_shape: ShapeND | None = None, + window: WindowInput | None = None, + boundless: bool = False, + resampling: Resampling = ..., + ) -> NDArray[Any]: ... + def sample( + self, xy: Sequence[tuple[float, float]], indexes: Indexes | None = None, masked: bool = False + ) -> Iterator[NDArray[Any]]: ... + def stats(self, *, indexes: Indexes | None = None, approx: bool = False) -> list[Statistics]: ... + @deprecated("DatasetReaderBase.statistics() will be removed in 2.0.0; please switch to stats().") + def statistics(self, bidx: int, approx: bool = False, clear_cache: bool = False) -> Statistics: ... + +class MemoryFileBase: + name: str + mode: str + closed: bool + def __init__( + self, + file_or_bytes: bytes | BinaryIO | None = None, + dirname: str | None = None, + filename: str | None = None, + ext: str = "", + ) -> None: ... + def __len__(self) -> int: ... + def exists(self) -> bool: ... + def getbuffer(self) -> memoryview: ... + def close(self) -> None: ... + def seek(self, offset: int, whence: int = 0) -> int: ... + def tell(self) -> int: ... + def read(self, size: int = -1) -> bytes: ... + def write(self, data: bytes) -> int: ... + +class DatasetWriterBase(DatasetReaderBase): + name: str + mode: str + width: int + height: int + shape: tuple[int, int] + driver: str + + def __init__( + self, + path: str | os.PathLike[str] | _ParsedPath | _UnparsedPath, + mode: str, + driver: str | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + sharing: bool = False, + **kwargs: _OpenOption, + ) -> None: ... + def write( + self, arr: NDArray[Any], indexes: Indexes | None = None, window: WindowInput | None = None, masked: bool = False + ) -> None: ... + def write_band(self, bidx: int, src: NDArray[Any], window: WindowInput | None = None) -> None: ... + def update_tags(self, bidx: int = 0, ns: str | None = None, **kwargs: _GDALOption) -> None: ... + def set_band_description(self, bidx: int, value: str) -> None: ... + def set_band_unit(self, bidx: int, value: str) -> None: ... + def write_colormap(self, bidx: int, colormap: Colormap) -> None: ... + def write_mask(self, mask_array: NDArray[Any], window: WindowInput | None = None) -> None: ... + def build_overviews(self, factors: Sequence[int], resampling: Resampling = ...) -> None: ... + def update_stats( + self, *, stats: Sequence[Statistics] | None = None, indexes: Indexes | None = None, approx: bool = False + ) -> None: ... + def clear_stats(self) -> None: ... + +class MemoryDataset(DatasetWriterBase): + def __init__( + self, + image: NDArray[Any] | None = None, + dtype: DTypeLike | None = None, + count: int = 1, + width: int | None = None, + height: int | None = None, + transform: Affine | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + crs: CRSInput | None = None, + ) -> None: ... + def __enter__(self) -> Self: ... + +class BufferedDatasetWriterBase(DatasetWriterBase): + def __init__( + self, + path: str | os.PathLike[str] | _ParsedPath | _UnparsedPath, + mode: str = "w", + driver: str | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + sharing: bool = False, + **kwargs: _OpenOption, + ) -> None: ... + def stop(self) -> None: ... + +int8: Final[str] +uint8: Final[str] diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/_path.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/_path.pyi new file mode 100644 index 000000000000..cf9b098d569c --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/_path.pyi @@ -0,0 +1,34 @@ +import os +from typing import Any, Final +from typing_extensions import Self + +SCHEMES: Final[dict[str, str]] +ARCHIVESCHEMES: Final[type[set[Any]]] +CURLSCHEMES: Final[set[str]] +REMOTESCHEMES: Final[set[str]] + +class _Path: + def as_vsi(self) -> str: ... + +class _ParsedPath(_Path): + path: str + archive: str | None + scheme: str | None + def __init__(self, path: str, archive: str | None, scheme: str | None) -> None: ... + @classmethod + def from_uri(cls, uri: str) -> Self: ... + @property + def name(self) -> str: ... + @property + def is_remote(self) -> bool: ... + @property + def is_local(self) -> bool: ... + +class _UnparsedPath(_Path): + path: str + def __init__(self, path: str) -> None: ... + @property + def name(self) -> str: ... + +def _parse_path(path: str | os.PathLike[str] | _Path) -> _ParsedPath | _UnparsedPath: ... +def _vsi_path(path: _Path) -> str: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/_show_versions.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/_show_versions.pyi new file mode 100644 index 000000000000..1eeec0747405 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/_show_versions.pyi @@ -0,0 +1 @@ +def show_versions() -> None: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/_transform.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/_transform.pyi new file mode 100644 index 000000000000..350f8c05cd60 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/_transform.pyi @@ -0,0 +1,16 @@ +from collections.abc import Sequence + +from rasterio._typing import _GDALOption +from rasterio.control import GroundControlPoint +from rasterio.errors import TransformWarning as TransformWarning +from rasterio.rpc import RPC + +class GCPTransformerBase: + def __init__(self, gcps: Sequence[GroundControlPoint]) -> None: ... + def close(self) -> None: ... + +class RPCTransformerBase: + def __init__(self, rpcs: RPC, **kwargs: _GDALOption) -> None: ... + def close(self) -> None: ... + +def _transform_from_gcps(gcps: Sequence[GroundControlPoint]) -> tuple[float, ...]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/_typing.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/_typing.pyi new file mode 100644 index 000000000000..974afc3a8369 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/_typing.pyi @@ -0,0 +1,58 @@ +from collections.abc import Callable, Mapping, Sequence +from enum import Enum +from typing import Any, BinaryIO, Protocol, TypeAlias, type_check_only + +from rasterio.crs import CRS +from rasterio.io import DatasetReaderBase, MemoryFile +from rasterio.windows import Window + +# `DatasetReaderBase` covers every readable dataset handle: DatasetReader, +# DatasetWriter, BufferedDatasetWriter, MemoryDataset, and WarpedVRT (via +# WarpedVRTReaderBase). `MemoryFile` is a file wrapper, not a dataset. +AnyDataset: TypeAlias = DatasetReaderBase | MemoryFile + +@type_check_only +class _SupportsGeoInterface(Protocol): + @property + def __geo_interface__(self) -> Mapping[str, Any]: ... + +# A GeoJSON-like mapping, or any object exposing one through the +# `__geo_interface__` protocol (e.g. shapely / geopandas geometries). +# The runtime unwraps `__geo_interface__` before use, so both forms are +# accepted anywhere a geometry is expected. +Geometry: TypeAlias = Mapping[str, Any] | _SupportsGeoInterface # noqa: Y047 +Colormap: TypeAlias = dict[int, tuple[int, int, int] | tuple[int, int, int, int]] +CRSInput: TypeAlias = str | dict[str, str] | CRS +FileOrBytes: TypeAlias = BinaryIO | bytes +Indexes: TypeAlias = int | Sequence[int] +NumType: TypeAlias = int | float +ShapeND: TypeAlias = Sequence[int] +WindowInput: TypeAlias = Window | tuple[tuple[int, int], tuple[int, int]] + +# Scalar values accepted by every GDAL CSL-style option list: global +# config (`set_gdal_config` / `Env`), per-call warp options +# (NUM_THREADS, INIT_DEST, …), RPC/transformer options (RPC_HEIGHT, +# RPC_DEM, COORDINATE_OPERATION, …), and metadata tag values. The +# runtime stringifies each value at the C boundary and does not +# special-case Enum or tuple types here (use `_OpenOption` for those). +_GDALOption: TypeAlias = str | int | float | bool | None # noqa: Y047 + +# GDAL driver-specific open/creation option values. The runtime coerces +# every value to a string at the C boundary; documented usage covers +# scalars, Enum members (encoded as `.name.upper()`), and tuples of +# scalars (joined with commas). Lists are not handled specially — pass +# a tuple if you need a multi-value option. +_OpenOption: TypeAlias = str | int | float | bool | Enum | tuple[str | int | float | bool, ...] | None # noqa: Y047 + +# Opaque OGR geometry handle (a Cython-wrapped C object). Callers only +# pass it back to other Cython internals; the public API surfaces +# already-decoded GeoJSON-like dicts. +_OGRGeometry: TypeAlias = Any # noqa: Y047 + +# Scalar or arbitrarily nested list of scalars; used by helpers that +# recurse into sequences while preserving the nesting depth. +_NestedScalar: TypeAlias = float | list[_NestedScalar] # noqa: Y047 + +# fsspec-style opener forwarded to `rasterio.open(opener=...)`: +# `(path: str, mode: str) -> file-like`. +_Opener: TypeAlias = Callable[..., Any] # noqa: Y047 diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/_version.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/_version.pyi new file mode 100644 index 000000000000..063e03ad00dd --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/_version.pyi @@ -0,0 +1,5 @@ +def gdal_version() -> str: ... +def get_gdal_version_info(key: str) -> str: ... +def check_gdal_version(major: int, minor: int) -> bool: ... +def get_geos_version() -> tuple[int, int, int]: ... +def get_proj_version() -> tuple[int, int, int]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/_vsiopener.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/_vsiopener.pyi new file mode 100644 index 000000000000..0354d31dc260 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/_vsiopener.pyi @@ -0,0 +1,36 @@ +from abc import ABC, abstractmethod +from contextlib import AbstractContextManager +from typing import Any, BinaryIO + +from rasterio.errors import OpenerRegistrationError as OpenerRegistrationError + +class FileContainer(ABC): + @abstractmethod + def open(self, path: str, mode: str = "r", **kwds: Any) -> BinaryIO: ... + @abstractmethod + def isdir(self, path: str) -> bool: ... + @abstractmethod + def isfile(self, path: str) -> bool: ... + @abstractmethod + def ls(self, path: str) -> list[str]: ... + @abstractmethod + def mtime(self, path: str) -> int: ... + @abstractmethod + def rm(self, path: str) -> None: ... + @abstractmethod + def size(self, path: str) -> int: ... + +class MultiByteRangeResource(ABC): + @abstractmethod + def get_byte_ranges(self, offsets: list[int], sizes: list[int]) -> list[bytes]: ... + +class MultiByteRangeResourceContainer(FileContainer): + @abstractmethod + def open(self, path: str, **kwds: Any) -> MultiByteRangeResource: ... # type: ignore[override] + +# Duck-typed adapter: `obj` may be a `FileContainer` subclass or any +# object exposing the fsspec filesystem protocol (`hasattr(obj, "file_size")`). +def to_pyopener(obj: Any) -> FileContainer: ... + +# `obj` accepts the same types as `to_pyopener` plus raw callables. +def _opener_registration(urlpath: str, obj: Any) -> AbstractContextManager[str]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/_warp.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/_warp.pyi new file mode 100644 index 000000000000..b98484b6fd62 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/_warp.pyi @@ -0,0 +1,123 @@ +from collections.abc import Sequence +from typing import Any, Final + +from numpy.typing import DTypeLike, NDArray +from rasterio._affine_types import Affine +from rasterio._io import DatasetReaderBase +from rasterio._typing import CRSInput, Geometry, Indexes, ShapeND, WindowInput, _GDALOption, _NestedScalar +from rasterio.control import GroundControlPoint +from rasterio.crs import CRS +from rasterio.enums import Resampling +from rasterio.io import DatasetReader +from rasterio.rpc import RPC + +SUPPORTED_RESAMPLING: Final[list[Resampling]] +DEFAULT_NODATA_FLAG: Final[object] + +def recursive_round(val: _NestedScalar, precision: int) -> _NestedScalar: ... +def _transform_geom( + src_crs: CRSInput, dst_crs: CRSInput, geom: Geometry | Sequence[Geometry], precision: int +) -> dict[str, Any] | list[dict[str, Any]]: ... +def _reproject( + source: NDArray[Any] | Any, + destination: NDArray[Any] | Any, + src_transform: Affine | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + src_crs: CRSInput | None = None, + src_nodata: float | None = None, + dst_transform: Affine | None = None, + dst_crs: CRSInput | None = None, + dst_nodata: float | None = None, + dst_alpha: int = 0, + src_alpha: int = 0, + resampling: Resampling = ..., + init_dest_nodata: bool = True, + tolerance: float = 0.125, + num_threads: int = 1, + warp_mem_limit: int = 0, + working_data_type: int = 0, + src_geoloc_array: NDArray[Any] | None = None, + **kwargs: _GDALOption, +) -> tuple[NDArray[Any], Affine]: ... +def _calculate_default_transform( + src_crs: CRSInput, + dst_crs: CRSInput, + width: int, + height: int, + left: float | None = None, + bottom: float | None = None, + right: float | None = None, + top: float | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, + src_geoloc_array: NDArray[Any] | None = None, + **kwargs: _GDALOption, +) -> tuple[Affine, int, int]: ... +def _transform_bounds( + src_crs: CRS, dst_crs: CRS, left: float, bottom: float, right: float, top: float, densify_pts: int +) -> tuple[float, float, float, float]: ... +def _suggested_proxy_vrt_doc( + width: int, + height: int, + transform: Affine | None = None, + crs: CRSInput | None = None, + gcps: Sequence[GroundControlPoint] | None = None, + rpcs: RPC | None = None, +) -> str: ... + +class WarpedVRTReaderBase(DatasetReaderBase): + src_dataset: DatasetReader + src_crs: CRS + src_transform: Affine | None + resampling: Resampling + tolerance: float + src_nodata: float | None + dst_nodata: float | None + working_dtype: DTypeLike | None + warp_extras: dict[str, _GDALOption] + + def __init__( + self, + src_dataset: DatasetReader, + src_crs: CRSInput | None = None, + crs: CRSInput | None = None, + resampling: Resampling = ..., + tolerance: float = 0.125, + src_nodata: float | None = ..., + nodata: float | None = ..., + width: int | None = None, + height: int | None = None, + src_transform: Affine | None = None, + transform: Affine | None = None, + init_dest_nodata: bool = True, + src_alpha: int = 0, + dst_alpha: int = 0, + add_alpha: bool = False, + warp_mem_limit: int = 0, + dtype: DTypeLike | None = None, + **warp_extras: _GDALOption, + ) -> None: ... + def read( # type: ignore[override] + self, + indexes: Indexes | None = None, + out: NDArray[Any] | None = None, + window: WindowInput | None = None, + masked: bool = False, + out_shape: ShapeND | None = None, + resampling: Resampling = ..., + fill_value: float | None = None, + out_dtype: DTypeLike | None = None, + # Swallows the deprecated `boundless` kwarg (raises ValueError if True). + **kwargs: bool, + ) -> NDArray[Any]: ... + def read_masks( # type: ignore[override] + self, + indexes: Indexes | None = None, + out: NDArray[Any] | None = None, + out_shape: ShapeND | None = None, + window: WindowInput | None = None, + resampling: Resampling = ..., + # Swallows the deprecated `boundless` kwarg (raises ValueError if True). + **kwargs: bool, + ) -> NDArray[Any]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/abc.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/abc.pyi new file mode 100644 index 000000000000..d9ebb71719e0 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/abc.pyi @@ -0,0 +1 @@ +from rasterio._vsiopener import FileContainer as FileContainer, MultiByteRangeResourceContainer as MultiByteRangeResourceContainer diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/cache.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/cache.pyi new file mode 100644 index 000000000000..ab1f8b285843 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/cache.pyi @@ -0,0 +1,2 @@ +def invalidate(pattern: str) -> None: ... +def invalidate_all() -> None: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/control.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/control.pyi new file mode 100644 index 000000000000..0fbec047e6be --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/control.pyi @@ -0,0 +1,46 @@ +from collections.abc import Sequence +from typing import Literal, TypedDict, type_check_only + +@type_check_only +class GroundControlPointDict(TypedDict): + id: str + info: str | None + row: float + col: float + x: float + y: float + z: float | None + +@type_check_only +class GroundControlPointGeometry(TypedDict): + type: Literal["Point"] + coordinates: Sequence[float] + +@type_check_only +class GroundControlPointFeature(TypedDict): + id: str + type: Literal["Feature"] + geometry: GroundControlPointGeometry + properties: GroundControlPointDict + +class GroundControlPoint: + id: str + info: str | None + row: float + col: float + x: float + y: float + z: float | None + def __init__( + self, + row: float | None = None, + col: float | None = None, + x: float | None = None, + y: float | None = None, + z: float | None = None, + id: str | None = None, + info: str | None = None, + ) -> None: ... + def asdict(self) -> GroundControlPointDict: ... + @property + def __geo_interface__(self) -> GroundControlPointFeature: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/coords.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/coords.pyi new file mode 100644 index 000000000000..c7b97fc2fe31 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/coords.pyi @@ -0,0 +1,11 @@ +from typing import NamedTuple, TypeAlias + +_Quadruple: TypeAlias = tuple[float, float, float, float] + +class BoundingBox(NamedTuple): + left: float + bottom: float + right: float + top: float + +def disjoint_bounds(bounds1: BoundingBox | _Quadruple, bounds2: BoundingBox | _Quadruple) -> bool: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/crs.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/crs.pyi new file mode 100644 index 000000000000..400c4c939d68 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/crs.pyi @@ -0,0 +1,69 @@ +from collections.abc import Iterator, Mapping +from typing import Any +from typing_extensions import Self, deprecated, disjoint_base + +from rasterio.enums import WktVersion + +all_proj_keys: set[str] + +@disjoint_base +class CRS(Mapping[str, Any]): + def __init__(self, initialdata: Mapping[str, Any] | None = None, **kwargs: Any) -> None: ... + def __getitem__(self, key: str, /) -> Any: ... + def __iter__(self) -> Iterator[str]: ... + def __len__(self) -> int: ... + def __bool__(self) -> bool: ... + def __nonzero__(self) -> bool: ... + def __eq__(self, other: object, /) -> bool: ... + def __copy__(self) -> Self: ... + def __hash__(self) -> int: ... + def __getstate__(self) -> dict[str, Any]: ... + def __setstate__(self, state: Mapping[str, Any]) -> None: ... + def to_proj4(self) -> str: ... + def to_wkt(self, morph_to_esri_dialect: bool = False, version: WktVersion | str | None = None) -> str: ... + @property + def wkt(self) -> str: ... + def to_epsg(self, confidence_threshold: int = 70) -> int | None: ... + def to_authority(self, confidence_threshold: int = 70) -> tuple[str, str] | None: ... + def to_dict(self, projjson: bool = False) -> dict[str, Any]: ... + @property + def data(self) -> dict[str, Any]: ... + @property + def is_geographic(self) -> bool: ... + @property + def is_projected(self) -> bool: ... + @property + @deprecated("CRS.is_valid is deprecated since rasterio 1.4 and will be removed in 2.0.0.") + def is_valid(self) -> bool: ... + @property + def is_epsg_code(self) -> bool: ... + @property + def linear_units_factor(self) -> tuple[str, float]: ... + @property + def linear_units(self) -> str: ... + @property + def units_factor(self) -> tuple[str, float]: ... + @property + def geodetic_crs(self) -> CRS | None: ... + def to_string(self) -> str: ... + def equals(self, other: CRS, ignore_axis_order: bool = False) -> bool: ... + def get(self, item: str) -> Any: ... # type: ignore[override] + @staticmethod + def from_epsg(code: int | str) -> CRS: ... + @staticmethod + def from_authority(auth_name: str, code: int | str) -> CRS: ... + @staticmethod + def from_string(value: str, morph_from_esri_dialect: bool = False) -> CRS: ... + @staticmethod + def from_proj4(proj: str) -> CRS: ... + @staticmethod + def from_dict(initialdata: Mapping[str, Any] | None = None, **kwargs: Any) -> CRS: ... + @staticmethod + def from_wkt(wkt: str, morph_from_esri_dialect: bool = False) -> CRS: ... + # `value` is dispatched at runtime: CRS, int (EPSG), str (PROJ/WKT/auth), Mapping[str, Any], or any pyproj-CRS-like object. + @staticmethod + def from_user_input(value: Any, morph_from_esri_dialect: bool = False) -> CRS: ... + +def epsg_treats_as_latlong(input_crs: CRS) -> bool: ... +def epsg_treats_as_northingeasting(input_crs: CRS) -> bool: ... +def auth_preference(item: str) -> None: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/drivers.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/drivers.pyi new file mode 100644 index 000000000000..96b6d727bd5b --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/drivers.pyi @@ -0,0 +1,8 @@ +import os +from typing import Final + +blacklist: Final[dict[str, tuple[str, ...]]] + +def raster_driver_extensions() -> dict[str, str]: ... +def driver_from_extension(path: str | os.PathLike[str]) -> str: ... +def is_blacklisted(name: str, mode: str) -> bool: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/dtypes.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/dtypes.pyi new file mode 100644 index 000000000000..f76501ed11d1 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/dtypes.pyi @@ -0,0 +1,46 @@ +from collections.abc import Sequence +from typing import Any, Final + +import numpy as np +from numpy.typing import ArrayLike, DTypeLike + +bool_: Final[str] +ubyte: Final[str] +uint8: Final[str] +sbyte: Final[str] +int8: Final[str] +uint16: Final[str] +int16: Final[str] +uint32: Final[str] +int32: Final[str] +int64: Final[str] +uint64: Final[str] +float16: Final[str] +float32: Final[str] +float64: Final[str] +complex_: Final[str] +complex64: Final[str] +complex128: Final[str] +complex_int16: Final[str] + +dtype_fwd: Final[dict[int, str | None]] +dtype_rev: Final[dict[str | None, int]] +typename_fwd: Final[dict[int, str]] +typename_rev: Final[dict[str, int]] +dtype_ranges: Final[dict[str, tuple[float, float]]] +dtype_info_registry: Final[dict[str, type]] + +# `numpy.finfo` instances cached at module import; used by `in_dtype_range`. +f16i: Final[np.finfo[np.float16]] +f32i: Final[np.finfo[np.float32]] +f64i: Final[np.finfo[np.float64]] + +def in_dtype_range(value: float, dtype: DTypeLike) -> bool: ... +def check_dtype(dt: DTypeLike) -> bool: ... +def get_minimum_dtype(values: ArrayLike) -> str: ... + +# isinstance check; accepts any object and returns True for numpy.ndarray +# and any object exposing `__array__`. +def is_ndarray(array: Any) -> bool: ... +def can_cast_dtype(values: ArrayLike, dtype: DTypeLike) -> bool: ... +def validate_dtype(values: ArrayLike, valid_dtypes: Sequence[DTypeLike]) -> bool: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/enums.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/enums.pyi new file mode 100644 index 000000000000..6e1a2fc76a6b --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/enums.pyi @@ -0,0 +1,126 @@ +from enum import Enum, IntEnum + +class TransformDirection(IntEnum): + forward = 1 + reverse = 0 + +class TransformMethod(Enum): + affine = "transform" + gcps = "gcps" + rpcs = "rpcs" + +class ColorInterp(IntEnum): + undefined = 0 + gray = 1 + grey = 1 + palette = 2 + red = 3 + green = 4 + blue = 5 + alpha = 6 + hue = 7 + saturation = 8 + lightness = 9 + cyan = 10 + magenta = 11 + yellow = 12 + black = 13 + Y = 14 + Cb = 15 + Cr = 16 + pan = 17 + coastal = 18 + rededge = 19 + nir = 20 + swir = 21 + mwir = 22 + lwir = 23 + tir = 24 + other_ir = 25 + sar_ka = 30 + sar_k = 31 + sar_ku = 32 + sar_x = 33 + sar_c = 34 + sar_s = 35 + sar_l = 36 + sar_p = 37 + +class Resampling(IntEnum): + nearest = 0 + bilinear = 1 + cubic = 2 + cubic_spline = 3 + lanczos = 4 + average = 5 + mode = 6 + gauss = 7 + max = 8 + min = 9 + med = 10 + q1 = 11 + q3 = 12 + sum = 13 + rms = 14 + +class OverviewResampling(IntEnum): + nearest = 0 + bilinear = 1 + cubic = 2 + cubic_spline = 3 + lanczos = 4 + average = 5 + mode = 6 + gauss = 7 + rms = 14 + +class Compression(Enum): + jpeg = "JPEG" + lzw = "LZW" + packbits = "PACKBITS" + deflate = "DEFLATE" + ccittrle = "CCITTRLE" + ccittfax3 = "CCITTFAX3" + ccittfax4 = "CCITTFAX4" + lzma = "LZMA" + none = "NONE" + zstd = "ZSTD" + lerc = "LERC" + lerc_deflate = "LERC_DEFLATE" + lerc_zstd = "LERC_ZSTD" + webp = "WEBP" + jpeg2000 = "JPEG2000" + +class Interleaving(Enum): + pixel = "PIXEL" + line = "LINE" + band = "BAND" + tile = "TILE" + +class MaskFlags(IntEnum): + all_valid = 1 + per_dataset = 2 + alpha = 4 + nodata = 8 + +class PhotometricInterp(Enum): + black = "MINISBLACK" + white = "MINISWHITE" + rgb = "RGB" + cmyk = "CMYK" + ycbcr = "YCbCr" + cielab = "CIELAB" + icclab = "ICCLAB" + itulab = "ITULAB" + +class MergeAlg(Enum): + replace = "REPLACE" + add = "ADD" + +class WktVersion(Enum): + WKT2_2015 = "WKT2_2015" + WKT2 = "WKT2" + WKT2_2019 = "WKT2_2018" + WKT1_GDAL = "WKT1_GDAL" + WKT1 = "WKT1" + WKT1_ESRI = "WKT1_ESRI" diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/env.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/env.pyi new file mode 100644 index 000000000000..3f5c57bfeb2a --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/env.pyi @@ -0,0 +1,102 @@ +import logging +import threading +from collections.abc import Callable, Iterable +from types import TracebackType +from typing import Any, Final, TypeVar +from typing_extensions import Self, deprecated + +from rasterio._env import ( + GDALDataFinder as GDALDataFinder, + GDALEnv as GDALEnv, + PROJDataFinder as PROJDataFinder, + _GDALOption, + get_gdal_config as get_gdal_config, + set_gdal_config as set_gdal_config, + set_proj_data_search_path as set_proj_data_search_path, +) +from rasterio.errors import ( + EnvError as EnvError, + GDALVersionError as GDALVersionError, + RasterioDeprecationWarning as RasterioDeprecationWarning, +) +from rasterio.session import DummySession as DummySession, Session as Session + +_F = TypeVar("_F", bound=Callable[..., Any]) + +class ThreadEnv(threading.local): + def __init__(self) -> None: ... + +local: ThreadEnv +log: logging.Logger + +class Env: + session: Session + options: dict[str, _GDALOption] + context_options: dict[str, _GDALOption] + def __init__( + self, + session: Session | None = None, + aws_unsigned: bool = False, + profile_name: str | None = None, + session_class: Callable[..., Session] = ..., + **options: _GDALOption, + ) -> None: ... + @classmethod + def default_options(cls) -> dict[str, _GDALOption]: ... + # Forwarded to `cls(...)` after merging in default_options(); see __init__. + @classmethod + def from_defaults(cls, *args: Any, **kwargs: _GDALOption) -> Self: ... + def credentialize(self) -> None: ... + def aws_creds_from_context_options(self) -> dict[str, str]: ... + def drivers(self) -> dict[str, str]: ... + def __enter__(self) -> Self: ... + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_val: BaseException | None = None, + exc_tb: TracebackType | None = None, + ) -> None: ... + +def defenv(**options: _GDALOption) -> None: ... +def getenv() -> dict[str, _GDALOption]: ... +def hasenv() -> bool: ... +def setenv(**options: _GDALOption) -> None: ... +@deprecated("Please use Env.session.hascreds() instead.") +def hascreds() -> bool: ... +def delenv() -> None: ... + +class NullContextManager: + def __init__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + +def env_ctx_if_needed() -> Env | NullContextManager: ... +def ensure_env(f: _F) -> _F: ... +@deprecated("ensure_env_credentialled is a deprecated alias; use ensure_env_with_credentials instead.") +def ensure_env_credentialled(f: _F) -> _F: ... +def ensure_env_with_credentials(f: _F) -> _F: ... +def gdal_version() -> str: ... + +class GDALVersion: + major: int + minor: int + patch: int + def __init__(self, major: int = 0, minor: int = 0, patch: int = 0) -> None: ... + def __eq__(self, other: object) -> bool: ... + def __lt__(self, other: GDALVersion) -> bool: ... + @classmethod + def parse(cls, input: str | GDALVersion, include_patch: bool = False) -> Self: ... + @classmethod + def runtime(cls, include_patch: bool = False) -> Self: ... + def at_least(self, other: str | GDALVersion, include_patch: bool = False) -> bool: ... + +def require_gdal_version( + version: str | GDALVersion, + param: str | None = None, + # `values` are matched against the decorated function's `param` argument; types depend on that argument. + values: Iterable[Any] | None = None, + is_max_version: bool = False, + reason: str = "", +) -> Callable[[_F], _F]: ... + +path: Final[str | None] diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/errors.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/errors.pyi new file mode 100644 index 000000000000..c883864c3f86 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/errors.pyi @@ -0,0 +1,40 @@ +from click import FileError + +class RasterioError(Exception): ... +class InvalidArrayError(RasterioError): ... +class WindowError(RasterioError): ... +class CRSError(ValueError): ... +class EnvError(RasterioError): ... +class DriverCapabilityError(RasterioError, ValueError): ... +class DriverRegistrationError(ValueError): ... + +class FileOverwriteError(FileError): + def __init__(self, message: str) -> None: ... + +class RasterioIOError(RasterioError, OSError): ... +class NodataShadowWarning(UserWarning): ... +class NotGeoreferencedWarning(UserWarning): ... +class TransformWarning(UserWarning): ... +class RPCError(ValueError): ... +class ShapeSkipWarning(UserWarning): ... +class GDALBehaviorChangeException(RuntimeError): ... +class GDALOptionNotImplementedError(RasterioError): ... +class GDALVersionError(RasterioError): ... +class WindowEvaluationError(ValueError): ... +class RasterioDeprecationWarning(FutureWarning): ... +class RasterBlockError(RasterioError): ... +class BandOverviewError(UserWarning): ... +class WarpOptionsError(RasterioError): ... +class UnsupportedOperation(RasterioError): ... +class OverviewCreationError(RasterioError): ... +class DatasetAttributeError(RasterioError, NotImplementedError): ... +class PathError(RasterioError): ... +class ResamplingAlgorithmError(RasterioError): ... +class TransformError(RasterioError): ... +class WarpedVRTError(RasterioError): ... +class DatasetIOShapeError(RasterioError): ... +class WarpOperationError(RasterioError): ... +class StatisticsError(RasterioError): ... +class OpenerRegistrationError(RasterioError): ... +class MergeError(RasterioError): ... +class StackError(RasterioError): ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/features.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/features.pyi new file mode 100644 index 000000000000..d3689801f08e --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/features.pyi @@ -0,0 +1,74 @@ +import logging +import os +from collections.abc import Iterable, Iterator +from typing import Any, Final, overload +from typing_extensions import deprecated + +import numpy as np +from numpy.typing import DTypeLike, NDArray +from rasterio._affine_types import Affine +from rasterio._typing import Geometry as Geometry +from rasterio.enums import MergeAlg as MergeAlg +from rasterio.io import DatasetReaderBase +from rasterio.windows import Window as Window + +log: Final[logging.Logger] + +def geometry_mask( + geometries: Iterable[Geometry], out_shape: tuple[int, int], transform: Affine, all_touched: bool = False, invert: bool = False +) -> NDArray[np.bool_]: ... +def shapes( + source: NDArray[Any], mask: NDArray[np.bool_] | None = None, connectivity: int = 4, transform: Affine = ... +) -> Iterator[tuple[dict[str, Any], float | int]]: ... +def sieve( + source: NDArray[Any], size: int, out: NDArray[Any] | None = None, mask: NDArray[np.bool_] | None = None, connectivity: int = 4 +) -> NDArray[Any]: ... +def rasterize( + shapes: Iterable[tuple[Geometry, float] | Geometry], + out_shape: tuple[int, int] | None = None, + fill: float = 0, + nodata: float | None = None, + masked: bool = False, + out: NDArray[Any] | None = None, + transform: Affine = ..., + all_touched: bool = False, + merge_alg: MergeAlg = ..., + default_value: float = 1, + dtype: DTypeLike | None = None, + skip_invalid: bool = True, + dst_path: str | os.PathLike[str] | None = None, + dst_kwds: dict[str, Any] | None = None, +) -> NDArray[Any]: ... +def bounds(geometry: Geometry, north_up: bool = True, transform: Affine | None = None) -> tuple[float, float, float, float]: ... + +@overload +def geometry_window( + dataset: DatasetReaderBase, shapes: Iterable[Geometry], pad_x: float = 0, pad_y: float = 0, *, boundless: bool = False +) -> Window: ... +@overload +@deprecated( + "`north_up`, `rotated`, and `pixel_precision` on features.geometry_window are " + "unused since rasterio 1.2.1 and will be removed in a future release." +) +def geometry_window( + dataset: DatasetReaderBase, + shapes: Iterable[Geometry], + pad_x: float = 0, + pad_y: float = 0, + north_up: bool | None = None, + rotated: bool | None = None, + pixel_precision: float | None = None, + boundless: bool = False, +) -> Window: ... + +def is_valid_geom(geom: Geometry) -> bool: ... +def dataset_features( + src: DatasetReaderBase, + bidx: int | None = None, + sampling: int = 1, + band: bool = True, + as_mask: bool = False, + with_nodata: bool = False, + geographic: bool = True, + precision: int = -1, +) -> Iterator[dict[str, Any]]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/fill.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/fill.pyi new file mode 100644 index 000000000000..8f121f75a3a8 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/fill.pyi @@ -0,0 +1,11 @@ +from typing import Any + +from numpy.ma import MaskedArray +from numpy.typing import NDArray + +def fillnodata( + image: NDArray[Any] | MaskedArray[Any, Any], + mask: NDArray[Any] | None = None, + max_search_distance: float = 100.0, + smoothing_iterations: int = 0, +) -> NDArray[Any]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/io.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/io.pyi new file mode 100644 index 000000000000..ad52b80ed0a7 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/io.pyi @@ -0,0 +1,67 @@ +import logging +from types import TracebackType +from typing import Any, Final +from typing_extensions import Self, deprecated + +from numpy.typing import DTypeLike +from rasterio._affine_types import Affine +from rasterio._filepath import FilePathBase as FilePathBase +from rasterio._io import ( + BufferedDatasetWriterBase as BufferedDatasetWriterBase, + DatasetReaderBase as DatasetReaderBase, + DatasetWriterBase as DatasetWriterBase, + MemoryFileBase as MemoryFileBase, +) +from rasterio._typing import CRSInput, FileOrBytes, _OpenOption +from rasterio.transform import TransformMethodsMixin +from rasterio.windows import WindowMethodsMixin + +log: Final[logging.Logger] + +class DatasetReader(DatasetReaderBase, WindowMethodsMixin, TransformMethodsMixin): ... +class DatasetWriter(DatasetWriterBase, WindowMethodsMixin, TransformMethodsMixin): ... +class BufferedDatasetWriter(BufferedDatasetWriterBase, WindowMethodsMixin, TransformMethodsMixin): ... + +class MemoryFile(MemoryFileBase): + def __init__( + self, file_or_bytes: FileOrBytes | None = None, dirname: str | None = None, filename: str | None = None, ext: str = ".tif" + ) -> None: ... + def open( + self, + driver: str | None = None, + width: int | None = None, + height: int | None = None, + count: int | None = None, + crs: CRSInput | None = None, + transform: Affine | None = None, + dtype: DTypeLike | None = None, + nodata: float | None = None, + sharing: bool = False, + thread_safe: bool = False, + **kwargs: _OpenOption, + ) -> DatasetReader | DatasetWriter: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... + +class ZipMemoryFile(MemoryFile): + def __init__(self, file_or_bytes: FileOrBytes | None = None) -> None: ... + def open( # type: ignore[override] + self, path: str, driver: str | None = None, sharing: bool = False, thread_safe: bool = False, **kwargs: _OpenOption + ) -> DatasetReader: ... + +@deprecated("FilePath is supplanted by rasterio.open's `opener` keyword argument and will be removed in 2.0.0.") +class FilePath(FilePathBase): + # `filelike_obj`: any Python file-like object (BytesIO, fsspec file, etc.). + def __init__(self, filelike_obj: Any, dirname: str | None = None, filename: str | None = None) -> None: ... + def open( + self, driver: str | None = None, sharing: bool = False, thread_safe: bool = False, **kwargs: _OpenOption + ) -> DatasetReader: ... + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: ... + +def get_writer_for_driver(driver: str) -> type[DatasetWriter | BufferedDatasetWriter] | None: ... +def get_writer_for_path(path: str, driver: str | None = None) -> type[DatasetWriter | BufferedDatasetWriter] | None: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/mask.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/mask.pyi new file mode 100644 index 000000000000..016f621c567f --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/mask.pyi @@ -0,0 +1,34 @@ +import logging +from collections.abc import Iterable +from typing import Any, Final + +from numpy.typing import NDArray +from rasterio._affine_types import Affine +from rasterio._typing import Geometry +from rasterio.errors import WindowError as WindowError +from rasterio.features import geometry_mask as geometry_mask, geometry_window as geometry_window +from rasterio.io import DatasetReaderBase + +logger: Final[logging.Logger] + +def raster_geometry_mask( + dataset: DatasetReaderBase, + shapes: Iterable[Geometry], + all_touched: bool = False, + invert: bool = False, + crop: bool = False, + pad: bool = False, + pad_width: float = 0.5, +) -> tuple[NDArray[Any], Affine, tuple[int, int, int, int]]: ... +def mask( + dataset: DatasetReaderBase, + shapes: Iterable[Geometry], + all_touched: bool = False, + invert: bool = False, + nodata: float | None = None, + filled: bool = True, + crop: bool = False, + pad: bool = False, + pad_width: float = 0.5, + indexes: int | Iterable[int] | None = None, +) -> tuple[NDArray[Any], Affine]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/merge.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/merge.pyi new file mode 100644 index 000000000000..d9d767d53c2e --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/merge.pyi @@ -0,0 +1,65 @@ +import logging +import os +from collections.abc import Callable, Sequence +from typing import Any, Final, Literal, TypeAlias, overload +from typing_extensions import deprecated + +from numpy.typing import DTypeLike, NDArray +from rasterio._affine_types import Affine +from rasterio.enums import Resampling +from rasterio.io import DatasetReaderBase + +logger: Final[logging.Logger] + +MethodFunction: TypeAlias = Callable[..., None] +MERGE_METHODS: Final[dict[str, MethodFunction]] + +_Arr: TypeAlias = NDArray[Any] + +# `**kwargs` on each merge method accepts forwarded options from `merge()` (e.g. `index`); ignored otherwise. +def copy_first(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_last(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_min(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_max(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_sum(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... +def copy_count(merged_data: _Arr, new_data: _Arr, merged_mask: _Arr, new_mask: _Arr, **kwargs: Any) -> None: ... + +@overload +def merge( + sources: Sequence[DatasetReaderBase | str | os.PathLike[str]], + bounds: tuple[float, float, float, float] | None = None, + res: float | tuple[float, float] | None = None, + nodata: float | None = None, + dtype: DTypeLike | None = None, + *, + indexes: int | Sequence[int] | None = None, + output_count: int | None = None, + resampling: Resampling = ..., + method: Literal["first", "last", "min", "max", "sum", "count"] | MethodFunction = "first", + target_aligned_pixels: bool = False, + mem_limit: int = 64, + use_highest_res: bool = False, + masked: bool = False, + dst_path: str | os.PathLike[str] | None = None, + dst_kwds: dict[str, Any] | None = None, +) -> tuple[NDArray[Any], Affine]: ... +@overload +@deprecated("The `precision` parameter is unused since rasterio 1.3 and will be removed in 2.0.0.") +def merge( + sources: Sequence[DatasetReaderBase | str | os.PathLike[str]], + bounds: tuple[float, float, float, float] | None = None, + res: float | tuple[float, float] | None = None, + nodata: float | None = None, + dtype: DTypeLike | None = None, + precision: int | None = None, + indexes: int | Sequence[int] | None = None, + output_count: int | None = None, + resampling: Resampling = ..., + method: Literal["first", "last", "min", "max", "sum", "count"] | MethodFunction = "first", + target_aligned_pixels: bool = False, + mem_limit: int = 64, + use_highest_res: bool = False, + masked: bool = False, + dst_path: str | os.PathLike[str] | None = None, + dst_kwds: dict[str, Any] | None = None, +) -> tuple[NDArray[Any], Affine]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/path.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/path.pyi new file mode 100644 index 000000000000..b5e935ebfd94 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/path.pyi @@ -0,0 +1,13 @@ +from typing import TypeAlias +from typing_extensions import deprecated + +from rasterio._path import _ParsedPath, _UnparsedPath +from rasterio.errors import RasterioDeprecationWarning as RasterioDeprecationWarning + +ParsedPath: TypeAlias = _ParsedPath +UnparsedPath: TypeAlias = _UnparsedPath + +@deprecated("rasterio.path.parse_path is deprecated; use rasterio._path._parse_path or pass paths directly to rasterio.open.") +def parse_path(path: str) -> _ParsedPath | _UnparsedPath: ... +@deprecated("rasterio.path.vsi_path is deprecated; use rasterio._path._vsi_path directly.") +def vsi_path(path: _ParsedPath | _UnparsedPath) -> str: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/plot.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/plot.pyi new file mode 100644 index 000000000000..80815180dac1 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/plot.pyi @@ -0,0 +1,49 @@ +import logging +from collections.abc import Mapping, Sequence +from typing import Any, Final, Literal + +from numpy.typing import NDArray +from rasterio._affine_types import Affine +from rasterio.io import DatasetReader as DatasetReader +from rasterio.transform import guard_transform as guard_transform + +logger: Final[logging.Logger] + +# Returns the `matplotlib.pyplot` module (lazy import). +def get_plt() -> Any: ... + +# `ax`: matplotlib.axes.Axes; returns matplotlib.image.AxesImage or +# the input `ax` for contour plots. `**kwargs` are forwarded to +# matplotlib's `imshow`/`contour` call. +def show( + source: NDArray[Any] | DatasetReader | tuple[DatasetReader, int], + with_bounds: bool = True, + contour: bool = False, + contour_label_kws: Mapping[str, Any] | None = None, + indexes: Sequence[int] | None = None, + ax: Any | None = None, + title: str | None = None, + transform: Affine | None = None, + percent_range: tuple[float, float] | None = None, + adjust: bool = True, + **kwargs: Any, +) -> Any: ... +def plotting_extent( + source: NDArray[Any] | DatasetReader, transform: Affine | None = None +) -> tuple[float, float, float, float]: ... +def reshape_as_image(arr: NDArray[Any]) -> NDArray[Any]: ... +def reshape_as_raster(arr: NDArray[Any]) -> NDArray[Any]: ... + +# `ax`: matplotlib.axes.Axes; `**kwargs` are forwarded to matplotlib's `hist` call. +def show_hist( + source: NDArray[Any] | DatasetReader, + bins: int = 10, + masked: bool = True, + title: str = "Histogram", + ax: Any | None = None, + label: str | Sequence[str] | None = None, + range: tuple[float, float] | None = None, + **kwargs: Any, +) -> None: ... +def adjust_band(band: NDArray[Any], kind: Literal["linear", "log"] | None = None) -> NDArray[Any]: ... +def contrast_strech(arr: NDArray[Any], percent_range: tuple[float, float] = (2.0, 98.0)) -> NDArray[Any]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/profiles.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/profiles.pyi new file mode 100644 index 000000000000..27bc61f92351 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/profiles.pyi @@ -0,0 +1,15 @@ +from collections import UserDict +from typing import Any, ClassVar, Final + +# A `Profile` is a dict of GDAL driver-specific dataset-creation options +# (e.g. `count`, `dtype`, `compress`); value types depend on the option. +class Profile(UserDict[str, Any]): + defaults: ClassVar[dict[str, Any]] + def __init__(self, data: dict[str, Any] = ..., **kwds: Any) -> None: ... + def __getitem__(self, key: str) -> Any: ... + def __setitem__(self, key: str, val: Any) -> None: ... + +class DefaultGTiffProfile(Profile): + defaults: ClassVar[dict[str, Any]] + +default_gtiff_profile: Final[DefaultGTiffProfile] diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/rpc.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/rpc.pyi new file mode 100644 index 000000000000..b4e2be46df5c --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/rpc.pyi @@ -0,0 +1,44 @@ +from collections.abc import Sequence +from typing import Any +from typing_extensions import Self + +class RPC: + height_off: float + height_scale: float + lat_off: float + lat_scale: float + line_den_coeff: Sequence[float] + line_num_coeff: Sequence[float] + line_off: float + line_scale: float + long_off: float + long_scale: float + samp_den_coeff: Sequence[float] + samp_num_coeff: Sequence[float] + samp_off: float + samp_scale: float + err_bias: float | None + err_rand: float | None + def __init__( + self, + height_off: float, + height_scale: float, + lat_off: float, + lat_scale: float, + line_den_coeff: Sequence[float], + line_num_coeff: Sequence[float], + line_off: float, + line_scale: float, + long_off: float, + long_scale: float, + samp_den_coeff: Sequence[float], + samp_num_coeff: Sequence[float], + samp_off: float, + samp_scale: float, + err_bias: float | None = None, + err_rand: float | None = None, + ) -> None: ... + def to_dict(self) -> dict[str, Any]: ... + def to_gdal(self) -> dict[str, str]: ... + @classmethod + def from_gdal(cls, rpcs: dict[str, str]) -> Self: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/sample.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/sample.pyi new file mode 100644 index 000000000000..4d7722bae293 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/sample.pyi @@ -0,0 +1,13 @@ +from collections.abc import Iterable, Iterator, Sequence +from typing import Any + +from numpy.typing import NDArray +from rasterio.io import DatasetReaderBase + +def sample_gen( + dataset: DatasetReaderBase, + xy: Iterable[tuple[float, float]], + indexes: int | Sequence[int] | None = None, + masked: bool = False, +) -> Iterator[NDArray[Any]]: ... +def sort_xy(xy: Iterable[tuple[float, float]]) -> list[tuple[float, float]]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/session.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/session.pyi new file mode 100644 index 000000000000..4a78d07976a1 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/session.pyi @@ -0,0 +1,112 @@ +import logging +from typing import Any, Final + +log: Final[logging.Logger] + +def parse_bool(v: bool | str | int) -> bool: ... + +class Session: + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + def get_credential_options(self) -> dict[str, str]: ... + # `session` is a foreign session object (e.g. boto3.session.Session, + # google.auth.credentials.Credentials); the runtime dispatches by isinstance. + @staticmethod + def from_foreign_session(session: Any, cls: type[Session] | None = None) -> Session: ... + @staticmethod + def cls_from_path(path: str) -> type[Session]: ... + # Forwarded to the resolved session class' __init__; see its signature. + @staticmethod + def from_path(path: str, *args: Any, **kwargs: Any) -> Session: ... + @staticmethod + def aws_or_dummy(*args: Any, **kwargs: Any) -> Session: ... + @staticmethod + def from_environ(*args: Any, **kwargs: Any) -> Session: ... + +class DummySession(Session): + credentials: dict[str, str] + # Accepts and ignores any args (no credentials are configured). + def __init__(self, *args: Any, **kwargs: Any) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + def get_credential_options(self) -> dict[str, str]: ... + +class AWSSession(Session): + requester_pays: bool + unsigned: bool + endpoint_url: str | None + def __init__( + self, + # A `boto3.session.Session` instance, or None to construct one from the other kwargs. + session: Any | None = None, + aws_unsigned: bool | None = None, + aws_access_key_id: str | None = None, + aws_secret_access_key: str | None = None, + aws_session_token: str | None = None, + region_name: str | None = None, + profile_name: str | None = None, + endpoint_url: str | None = None, + requester_pays: bool = False, + ) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... + +class OSSSession(Session): + def __init__( + self, oss_access_key_id: str | None = None, oss_secret_access_key: str | None = None, oss_endpoint: str | None = None + ) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... + +class GSSession(Session): + def __init__(self, google_application_credentials: str | None = None) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... + +class SwiftSession(Session): + def __init__( + self, + # A `swiftclient.Connection` instance, or None to construct one from the other kwargs. + session: Any | None = None, + swift_storage_url: str | None = None, + swift_auth_token: str | None = None, + swift_auth_v1_url: str | None = None, + swift_user: str | None = None, + swift_key: str | None = None, + ) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... + +class AzureSession(Session): + unsigned: bool + storage_account: str | None + def __init__( + self, + azure_storage_connection_string: str | None = None, + azure_storage_account: str | None = None, + azure_storage_access_token: str | None = None, + azure_storage_access_key: str | None = None, + azure_storage_sas_token: str | None = None, + azure_unsigned: bool = False, + azure_tenant_id: str | None = None, + azure_client_id: str | None = None, + azure_federated_token_file: str | None = None, + azure_authority_host: str | None = None, + ) -> None: ... + @classmethod + def hascreds(cls, config: dict[str, Any]) -> bool: ... + @property + def credentials(self) -> dict[str, str]: ... + def get_credential_options(self) -> dict[str, str]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/shutil.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/shutil.pyi new file mode 100644 index 000000000000..409a657b8b8d --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/shutil.pyi @@ -0,0 +1,16 @@ +import os +from typing import Any + +from rasterio._typing import _OpenOption + +def exists(path: str | os.PathLike[str]) -> bool: ... +def copy( + # An open dataset handle (DatasetReader / DatasetWriter / DatasetBase) or a path. + src: str | os.PathLike[str] | Any, + dst: str | os.PathLike[str], + driver: str | None = None, + strict: bool = True, + **creation_options: _OpenOption, +) -> None: ... +def copyfiles(src: str | os.PathLike[str], dst: str | os.PathLike[str]) -> None: ... +def delete(path: str | os.PathLike[str], driver: str | None = None) -> None: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/stack.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/stack.pyi new file mode 100644 index 000000000000..68680ffe9b1e --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/stack.pyi @@ -0,0 +1,28 @@ +import logging +import os +from collections.abc import Sequence +from typing import Any, Final + +from numpy.typing import DTypeLike, NDArray +from rasterio._affine_types import Affine +from rasterio.enums import Resampling +from rasterio.io import DatasetReaderBase + +logger: Final[logging.Logger] + +def stack( + sources: Sequence[DatasetReaderBase | str | os.PathLike[str]], + bounds: tuple[float, float, float, float] | None = None, + res: float | tuple[float, float] | None = None, + nodata: float | None = None, + dtype: DTypeLike | None = None, + indexes: int | Sequence[int] | None = None, + output_count: int | None = None, + resampling: Resampling = ..., + target_aligned_pixels: bool = False, + mem_limit: int = 64, + use_highest_res: bool = False, + masked: bool = False, + dst_path: str | os.PathLike[str] | None = None, + dst_kwds: dict[str, Any] | None = None, +) -> tuple[NDArray[Any], Affine]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/tools.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/tools.pyi new file mode 100644 index 000000000000..0d78bca77964 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/tools.pyi @@ -0,0 +1,19 @@ +import os +from collections.abc import Callable, Iterable +from typing import Any, Final + +class JSONSequenceTool: + func: Callable[..., Iterable[Any]] + def __init__(self, func: Callable[..., Iterable[Any]]) -> None: ... + def __call__( + self, + src_path: str | os.PathLike[str], + dst_path: str | os.PathLike[str], + src_kwargs: dict[str, Any] | None = None, + dst_kwargs: dict[str, Any] | None = None, + func_args: Iterable[Any] | None = None, + func_kwargs: dict[str, Any] | None = None, + config: dict[str, Any] | None = None, + ) -> None: ... + +dataset_features_tool: Final[JSONSequenceTool] diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/transform.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/transform.pyi new file mode 100644 index 000000000000..f6aae2f7f098 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/transform.pyi @@ -0,0 +1,112 @@ +from collections.abc import Callable, Sequence +from typing import Final, Literal, TypeAlias, overload +from typing_extensions import Self, deprecated + +from rasterio._affine_types import Affine as Affine +from rasterio._transform import GCPTransformerBase, RPCTransformerBase +from rasterio._typing import _GDALOption +from rasterio.control import GroundControlPoint +from rasterio.enums import TransformDirection as TransformDirection, TransformMethod as TransformMethod +from rasterio.errors import RasterioDeprecationWarning as RasterioDeprecationWarning +from rasterio.rpc import RPC + +_Sextuple: TypeAlias = tuple[float, float, float, float, float, float] +_OffsetOptions: TypeAlias = Literal["center", "ul", "ur", "ll", "lr"] +_RoundOperation: TypeAlias = Callable[[float], int] + +IDENTITY: Final[Affine] +GDAL_IDENTITY: Final[_Sextuple] + +class TransformMethodsMixin: + def xy( + self, + row: int | Sequence[int], + col: int | Sequence[int], + z: float | Sequence[float] | None = None, + offset: _OffsetOptions = "center", + transform_method: TransformMethod = ..., + **rpc_options: _GDALOption, + ) -> tuple[float, float] | tuple[list[float], list[float]]: ... + def index( + self, + x: float | Sequence[float], + y: float | Sequence[float], + z: float | Sequence[float] | None = None, + op: _RoundOperation | None = None, + precision: int | None = None, + transform_method: TransformMethod = ..., + **rpc_options: _GDALOption, + ) -> tuple[int, int] | tuple[list[int], list[int]]: ... + +def tastes_like_gdal(seq: Affine | _Sextuple) -> bool: ... +def guard_transform(transform: Affine | _Sextuple) -> Affine: ... +def from_origin(west: float, north: float, xsize: float, ysize: float) -> Affine: ... +def from_bounds(west: float, south: float, east: float, north: float, width: float, height: float) -> Affine: ... +def array_bounds(height: int, width: int, transform: Affine) -> tuple[float, float, float, float]: ... +def from_gcps(gcps: Sequence[GroundControlPoint]) -> Affine: ... +def xy( + transform: Affine | Sequence[GroundControlPoint] | RPC, + rows: int | Sequence[int], + cols: int | Sequence[int], + zs: float | Sequence[float] | None = None, + offset: _OffsetOptions = "center", + **rpc_options: _GDALOption, +) -> tuple[float, float] | tuple[list[float], list[float]]: ... +def rowcol( + transform: Affine | Sequence[GroundControlPoint] | RPC, + xs: float | Sequence[float], + ys: float | Sequence[float], + zs: float | Sequence[float] | None = None, + op: _RoundOperation | None = None, + precision: int | None = None, + **rpc_options: _GDALOption, +) -> tuple[int, int] | tuple[list[int], list[int]]: ... +def get_transformer( + transform: Affine | Sequence[GroundControlPoint] | RPC, **rpc_options: _GDALOption +) -> type[TransformerBase]: ... + +class TransformerBase: + def __init__(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + def xy( + self, + rows: int | Sequence[int], + cols: int | Sequence[int], + zs: float | Sequence[float] | None = None, + offset: _OffsetOptions = "center", + ) -> tuple[float, float] | tuple[list[float], list[float]]: ... + + @overload + def rowcol( + self, + xs: float | Sequence[float], + ys: float | Sequence[float], + zs: float | Sequence[float] | None = None, + op: _RoundOperation | None = None, + ) -> tuple[int, int] | tuple[list[int], list[int]]: ... + @overload + @deprecated("The `precision` parameter is unused since rasterio 1.3 and will be removed in 2.0.0.") + def rowcol( + self, + xs: float | Sequence[float], + ys: float | Sequence[float], + zs: float | Sequence[float] | None = None, + op: _RoundOperation | None = None, + precision: int | None = None, + ) -> tuple[int, int] | tuple[list[int], list[int]]: ... + +class GDALTransformerBase(TransformerBase): + def __init__(self) -> None: ... + def close(self) -> None: ... + def __enter__(self) -> Self: ... + def __exit__(self, *args: object) -> None: ... + +class AffineTransformer(TransformerBase): + def __init__(self, affine_transform: Affine | _Sextuple) -> None: ... + +class GCPTransformer(GCPTransformerBase, GDALTransformerBase): + def __init__(self, gcps: Sequence[GroundControlPoint], tps: bool = False) -> None: ... + +class RPCTransformer(RPCTransformerBase, GDALTransformerBase): + def __init__(self, rpcs: RPC, **rpc_options: _GDALOption) -> None: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/vrt.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/vrt.pyi new file mode 100644 index 000000000000..308e932590a2 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/vrt.pyi @@ -0,0 +1,13 @@ +from types import TracebackType +from typing_extensions import Self + +from rasterio._warp import WarpedVRTReaderBase +from rasterio.transform import TransformMethodsMixin +from rasterio.windows import WindowMethodsMixin + +class WarpedVRT(WarpedVRTReaderBase, WindowMethodsMixin, TransformMethodsMixin): + def __enter__(self) -> Self: ... + def __exit__( + self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None + ) -> None: ... + def __del__(self) -> None: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/warp.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/warp.pyi new file mode 100644 index 000000000000..09e4a86ca08d --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/warp.pyi @@ -0,0 +1,84 @@ +from _typeshed import Incomplete +from collections.abc import Mapping, Sequence +from typing import Any, Final, TypeAlias, overload +from typing_extensions import deprecated + +from numpy.typing import ArrayLike, NDArray +from rasterio._affine_types import Affine +from rasterio._typing import CRSInput, Geometry, _GDALOption +from rasterio.control import GroundControlPoint +from rasterio.enums import Resampling +from rasterio.rpc import RPC + +_Resolution: TypeAlias = tuple[float, float] | float +_Gcps: TypeAlias = Sequence[GroundControlPoint] +_Rpcs: TypeAlias = RPC | Mapping[str, Any] + +SUPPORTED_RESAMPLING: Final[list[Resampling]] + +def transform( + src_crs: CRSInput, dst_crs: CRSInput, xs: ArrayLike, ys: ArrayLike, zs: ArrayLike | None = None +) -> tuple[list[float], list[float]] | tuple[list[float], list[float], list[float]]: ... + +@overload +def transform_geom( + src_crs: CRSInput, dst_crs: CRSInput, geom: Geometry | Sequence[Geometry], *, precision: float = -1 +) -> dict[str, Any] | list[dict[str, Any]]: ... +@overload +@deprecated( + "`antimeridian_cutting` and `antimeridian_offset` are no-ops since GDAL 2.2 " + "and will be removed in a future rasterio release. Call transform_geom " + "without them." +) +def transform_geom( + src_crs: CRSInput, + dst_crs: CRSInput, + geom: Geometry | Sequence[Geometry], + antimeridian_cutting: bool | None = None, + antimeridian_offset: float | None = None, + precision: float = -1, +) -> dict[str, Any] | list[dict[str, Any]]: ... + +def transform_bounds( + src_crs: CRSInput, dst_crs: CRSInput, left: float, bottom: float, right: float, top: float, densify_pts: int = 21 +) -> tuple[float, float, float, float]: ... +def reproject( + source: ArrayLike | Incomplete, + destination: ArrayLike | Incomplete | None = None, + src_transform: Affine | None = None, + gcps: _Gcps | None = None, + rpcs: _Rpcs | None = None, + src_crs: CRSInput | None = None, + src_nodata: float | None = None, + dst_transform: Affine | None = None, + dst_crs: CRSInput | None = None, + dst_nodata: float | None = None, + dst_resolution: _Resolution | None = None, + src_alpha: int = 0, + dst_alpha: int = 0, + masked: bool = False, + resampling: Resampling = ..., + num_threads: int = 1, + init_dest_nodata: bool = True, + warp_mem_limit: int = 0, + src_geoloc_array: NDArray[Any] | None = None, + **kwargs: _GDALOption, +) -> tuple[NDArray[Any], Affine]: ... +def aligned_target(transform: Affine, width: int, height: int, resolution: _Resolution) -> tuple[Affine, int, int]: ... +def calculate_default_transform( + src_crs: CRSInput, + dst_crs: CRSInput, + width: int, + height: int, + left: float | None = None, + bottom: float | None = None, + right: float | None = None, + top: float | None = None, + gcps: _Gcps | None = None, + rpcs: _Rpcs | None = None, + resolution: _Resolution | None = None, + dst_width: int | None = None, + dst_height: int | None = None, + src_geoloc_array: NDArray[Any] | None = None, + **kwargs: _GDALOption, +) -> tuple[Affine, int, int]: ... diff --git a/python/helpers/typeshed/stubs/rasterio/rasterio/windows.pyi b/python/helpers/typeshed/stubs/rasterio/rasterio/windows.pyi new file mode 100644 index 000000000000..bead643d3f08 --- /dev/null +++ b/python/helpers/typeshed/stubs/rasterio/rasterio/windows.pyi @@ -0,0 +1,80 @@ +from collections.abc import Callable, Sequence +from typing import Any, TypeAlias, overload +from typing_extensions import Self, deprecated + +from numpy.typing import NDArray +from rasterio._affine_types import Affine +from rasterio.errors import RasterioDeprecationWarning as RasterioDeprecationWarning, WindowError as WindowError + +_Bounds: TypeAlias = tuple[float, float, float, float] +_Ranges: TypeAlias = tuple[tuple[int, int], tuple[int, int]] +_Slices: TypeAlias = tuple[slice, slice] + +class WindowMethodsMixin: + @overload + def window(self, left: float, bottom: float, right: float, top: float) -> Window: ... + @overload + @deprecated("The `precision` parameter is unused since rasterio 1.3 and will be removed in 2.0.0.") + def window(self, left: float, bottom: float, right: float, top: float, precision: int | None = None) -> Window: ... + + def window_transform(self, window: Window) -> Affine: ... + def window_bounds(self, window: Window) -> _Bounds: ... + +def iter_args(function: Callable[..., Any]) -> Callable[..., Any]: ... +def toranges(window: Window | _Ranges) -> _Ranges: ... +def get_data_window(arr: NDArray[Any], nodata: float | None = None) -> Window: ... +def union(*windows: Window) -> Window: ... +def intersection(*windows: Window) -> Window: ... +def intersect(*windows: Window) -> bool: ... + +@overload +def from_bounds(left: float, bottom: float, right: float, top: float, transform: Affine | None = None) -> Window: ... +@overload +@deprecated( + "`height`, `width`, and `precision` on windows.from_bounds are unused since rasterio 1.3 and will be removed in 2.0.0." +) +def from_bounds( + left: float, + bottom: float, + right: float, + top: float, + transform: Affine | None = None, + height: int | None = None, + width: int | None = None, + precision: int | None = None, +) -> Window: ... + +def transform(window: Window, transform: Affine) -> Affine: ... +def bounds(window: Window, transform: Affine, height: int = 0, width: int = 0) -> _Bounds: ... +def crop(window: Window, height: int, width: int) -> Window: ... +def evaluate(window: Window, height: int, width: int, boundless: bool = False) -> Window: ... +def shape(window: Window, height: int = -1, width: int = -1) -> tuple[int, int]: ... +def window_index(window: Window, height: int = 0, width: int = 0) -> _Slices: ... +def round_window_to_full_blocks( + window: Window, block_shapes: Sequence[tuple[int, int]], height: int = 0, width: int = 0 +) -> Window: ... +def validate_length_value(instance: object, attribute: object, value: float) -> None: ... +def subdivide(window: Window, height: int, width: int) -> list[Window]: ... + +class Window: + col_off: float + row_off: float + width: float + height: float + def __init__(self, col_off: float, row_off: float, width: float, height: float) -> None: ... + def flatten(self) -> tuple[float, float, float, float]: ... + def todict(self) -> dict[str, float]: ... + def toranges(self) -> _Ranges: ... + def toslices(self) -> _Slices: ... + @classmethod + def from_slices( + cls, rows: slice | Sequence[int], cols: slice | Sequence[int], height: int = -1, width: int = -1, boundless: bool = False + ) -> Self: ... + # `**kwds` accepts the deprecated kwargs `op` (callable) and `pixel_precision` (int) emitted by rasterio < 1.3. + def round_lengths(self, **kwds: Any) -> Window: ... + @deprecated("Window.round_shape is deprecated and will be removed in Rasterio 2.0.0; use round_lengths instead.") + def round_shape(self, **kwds: Any) -> Window: ... + def round_offsets(self, **kwds: Any) -> Window: ... + def round(self, ndigits: int | None = None) -> Window: ... + def crop(self, height: int, width: int) -> Window: ... + def intersection(self, other: Window) -> Window: ... diff --git a/python/helpers/typeshed/stubs/reportlab/reportlab/graphics/shapes.pyi b/python/helpers/typeshed/stubs/reportlab/reportlab/graphics/shapes.pyi index 253538227f0f..123a551ddc2e 100644 --- a/python/helpers/typeshed/stubs/reportlab/reportlab/graphics/shapes.pyi +++ b/python/helpers/typeshed/stubs/reportlab/reportlab/graphics/shapes.pyi @@ -1,8 +1,8 @@ from _typeshed import Incomplete, SupportsItems from abc import abstractmethod from collections.abc import Iterable, Sequence -from typing import Any, Final, Literal, NoReturn, TypeAlias, TypedDict, type_check_only -from typing_extensions import Self, Unpack +from typing import Any, Final, Literal, TypeAlias, TypedDict, type_check_only +from typing_extensions import Never, Self, Unpack from reportlab.lib.colors import Color from reportlab.lib.validators import NoneOr, Validator @@ -197,7 +197,7 @@ class Line(LineShape): y2: float def __init__(self, x1: float, y1: float, x2: float, y2: float, **kw: Unpack[_LineShapeKwArgs]) -> None: ... # NOTE: For some reason Line doesn't implement copy - def copy(self) -> NoReturn: ... + def copy(self) -> Never: ... def getBounds(self) -> tuple[float, float, float, float]: ... class SolidShape(LineShape): diff --git a/python/helpers/typeshed/stubs/reportlab/reportlab/graphics/widgets/grids.pyi b/python/helpers/typeshed/stubs/reportlab/reportlab/graphics/widgets/grids.pyi index 3a3a249301e6..e098fe78fc84 100644 --- a/python/helpers/typeshed/stubs/reportlab/reportlab/graphics/widgets/grids.pyi +++ b/python/helpers/typeshed/stubs/reportlab/reportlab/graphics/widgets/grids.pyi @@ -1,5 +1,6 @@ from _typeshed import Incomplete -from typing import Final, NoReturn +from typing import Final +from typing_extensions import Never from reportlab.graphics.shapes import LineShape from reportlab.graphics.widgetbase import Widget @@ -73,4 +74,4 @@ class ShadedPolygon(Widget, LineShape): def __init__(self, **kw) -> None: ... def draw(self): ... # NOTE: widgets don't implement this, only actual shapes - def copy(self) -> NoReturn: ... + def copy(self) -> Never: ... diff --git a/python/helpers/typeshed/stubs/reportlab/reportlab/lib/rl_safe_eval.pyi b/python/helpers/typeshed/stubs/reportlab/reportlab/lib/rl_safe_eval.pyi index be8a719e2661..e70536e3ee0f 100644 --- a/python/helpers/typeshed/stubs/reportlab/reportlab/lib/rl_safe_eval.pyi +++ b/python/helpers/typeshed/stubs/reportlab/reportlab/lib/rl_safe_eval.pyi @@ -4,8 +4,7 @@ import re import time from _typeshed import Incomplete from collections.abc import Generator -from typing import NoReturn -from typing_extensions import Self +from typing_extensions import Never, Self eval_debug: int strTypes: tuple[type[bytes], type[str]] @@ -27,7 +26,7 @@ class UntrustedAstTransformer(ast.NodeTransformer): def __init__(self, names_seen=None, nameIsAllowed=None) -> None: ... @property def tmpName(self) -> str: ... - def error(self, node, msg) -> NoReturn: ... + def error(self, node, msg) -> Never: ... def guard_iter(self, node): ... def is_starred(self, ob): ... def gen_unpack_spec(self, tpl) -> ast.Dict: ... @@ -60,7 +59,7 @@ class UntrustedAstTransformer(ast.NodeTransformer): visit_For = guard_iter visit_comprehension = guard_iter def generic_visit(self, node: ast.AST) -> None: ... # type: ignore[override] - def not_allowed(self, node: ast.AST) -> NoReturn: ... + def not_allowed(self, node: ast.AST) -> Never: ... def visit_children(self, node) -> ast.AST: ... def visit(self, node): ... visit_Ellipsis = not_allowed diff --git a/python/helpers/typeshed/stubs/reportlab/reportlab/platypus/flowables.pyi b/python/helpers/typeshed/stubs/reportlab/reportlab/platypus/flowables.pyi index b3a433df28f0..1cb252411155 100644 --- a/python/helpers/typeshed/stubs/reportlab/reportlab/platypus/flowables.pyi +++ b/python/helpers/typeshed/stubs/reportlab/reportlab/platypus/flowables.pyi @@ -1,7 +1,7 @@ from _typeshed import Incomplete, SupportsRead, Unused from collections.abc import Callable, Iterable, Sequence -from typing import Any, Literal, NoReturn, Protocol, TypeAlias, type_check_only -from typing_extensions import Self +from typing import Any, Literal, Protocol, TypeAlias, type_check_only +from typing_extensions import Never, Self from reportlab.lib.colors import Color from reportlab.lib.styles import ListStyle, ParagraphStyle, PropertySet @@ -219,10 +219,10 @@ class ParagraphAndImage(Flowable): def draw(self) -> None: ... class FailOnWrap(NullDraw): - def wrap(self, aW: float, aH: float) -> NoReturn: ... + def wrap(self, aW: float, aH: float) -> Never: ... class FailOnDraw(Flowable): - def draw(self) -> NoReturn: ... + def draw(self) -> Never: ... class HRFlowable(Flowable): width: float | str # type: ignore[assignment] diff --git a/python/helpers/typeshed/stubs/seaborn/seaborn/_core/plot.pyi b/python/helpers/typeshed/stubs/seaborn/seaborn/_core/plot.pyi index d5574f604fc8..7f8bf81069c6 100644 --- a/python/helpers/typeshed/stubs/seaborn/seaborn/_core/plot.pyi +++ b/python/helpers/typeshed/stubs/seaborn/seaborn/_core/plot.pyi @@ -3,7 +3,7 @@ import os from _typeshed import Incomplete, SupportsKeysAndGetItem from collections.abc import Callable, Generator from contextlib import contextmanager -from typing import IO, Any, Literal, NoReturn, TypedDict, TypeVar +from typing import IO, Any, Literal, TypedDict, TypeVar from typing_extensions import Never, Self import matplotlib as mpl @@ -72,7 +72,7 @@ class Plot: __signature__: inspect.Signature config: PlotConfig def __init__(self, *args: DataSource | VariableSpec, data: DataSource = None, **variables: VariableSpec) -> None: ... - def __add__(self, other: Never) -> NoReturn: ... + def __add__(self, other: Never) -> Never: ... def on(self, target: Axes | SubFigure | Figure) -> Plot: ... def add( self, diff --git a/python/helpers/typeshed/stubs/setuptools/setuptools/_distutils/compilers/C/cygwin.pyi b/python/helpers/typeshed/stubs/setuptools/setuptools/_distutils/compilers/C/cygwin.pyi index 814209f3d25c..14fd3bdc641c 100644 --- a/python/helpers/typeshed/stubs/setuptools/setuptools/_distutils/compilers/C/cygwin.pyi +++ b/python/helpers/typeshed/stubs/setuptools/setuptools/_distutils/compilers/C/cygwin.pyi @@ -1,7 +1,7 @@ from _typeshed import StrPath from collections.abc import Callable, Iterable from shlex import _ShlexInstream -from typing import ClassVar, Final, Literal, NoReturn +from typing import ClassVar, Final, Literal from typing_extensions import Never, deprecated from ...version import LooseVersion @@ -56,7 +56,7 @@ class Compiler(unix.Compiler): class MinGW32Compiler(Compiler): compiler_type: ClassVar[str] def __init__(self, verbose: bool = False, force: bool = False) -> None: ... - def runtime_library_dir_option(self, dir: str) -> NoReturn: ... + def runtime_library_dir_option(self, dir: str) -> Never: ... CONFIG_H_OK: Final = "ok" CONFIG_H_NOTOK: Final = "not ok" diff --git a/python/helpers/typeshed/stubs/setuptools/setuptools/build_meta.pyi b/python/helpers/typeshed/stubs/setuptools/setuptools/build_meta.pyi index 45a733d1128d..08f3128cda37 100644 --- a/python/helpers/typeshed/stubs/setuptools/setuptools/build_meta.pyi +++ b/python/helpers/typeshed/stubs/setuptools/setuptools/build_meta.pyi @@ -1,7 +1,8 @@ from _typeshed import Incomplete, StrPath from collections.abc import Mapping from contextlib import _GeneratorContextManager -from typing import NoReturn, TypeAlias +from typing import TypeAlias +from typing_extensions import Never from . import dist @@ -25,7 +26,7 @@ class SetupRequirementsError(BaseException): def __init__(self, specifiers) -> None: ... class Distribution(dist.Distribution): - def fetch_build_eggs(self, specifiers) -> NoReturn: ... + def fetch_build_eggs(self, specifiers) -> Never: ... @classmethod def patch(cls) -> _GeneratorContextManager[None]: ... diff --git a/python/helpers/typeshed/stubs/setuptools/setuptools/command/test.pyi b/python/helpers/typeshed/stubs/setuptools/setuptools/command/test.pyi index 2f7b41e5d4d5..536179f18f09 100644 --- a/python/helpers/typeshed/stubs/setuptools/setuptools/command/test.pyi +++ b/python/helpers/typeshed/stubs/setuptools/setuptools/command/test.pyi @@ -1,5 +1,5 @@ -from typing import ClassVar, NoReturn -from typing_extensions import deprecated +from typing import ClassVar +from typing_extensions import Never, deprecated from .. import Command @@ -12,4 +12,4 @@ class test(Command): user_options: ClassVar[list[tuple[str, str, str]]] def initialize_options(self) -> None: ... def finalize_options(self) -> None: ... - def run(self) -> NoReturn: ... + def run(self) -> Never: ... diff --git a/python/helpers/typeshed/stubs/shapely/shapely/geometry/base.pyi b/python/helpers/typeshed/stubs/shapely/shapely/geometry/base.pyi index a39ed80b3b89..e4138123166b 100644 --- a/python/helpers/typeshed/stubs/shapely/shapely/geometry/base.pyi +++ b/python/helpers/typeshed/stubs/shapely/shapely/geometry/base.pyi @@ -1,7 +1,7 @@ from array import array from collections.abc import Iterator -from typing import Any, Generic, Literal, NoReturn, overload -from typing_extensions import Self, TypeVar, deprecated +from typing import Any, Generic, Literal, overload +from typing_extensions import Never, Self, TypeVar, deprecated import numpy as np from numpy.typing import NDArray @@ -301,7 +301,7 @@ _GeoT_co = TypeVar("_GeoT_co", bound=Geometry, default=BaseGeometry, covariant=T class BaseMultipartGeometry(BaseGeometry, Generic[_GeoT_co]): __slots__: list[str] = [] @property - def coords(self) -> NoReturn: ... + def coords(self) -> Never: ... @property def geoms(self) -> GeometrySequence[Self]: ... def svg(self, scale_factor: float = 1.0, color: str | None = None) -> str: ... # type: ignore[override] diff --git a/python/helpers/typeshed/stubs/shapely/shapely/geometry/polygon.pyi b/python/helpers/typeshed/stubs/shapely/shapely/geometry/polygon.pyi index c64dd7796dcf..e52857a88946 100644 --- a/python/helpers/typeshed/stubs/shapely/shapely/geometry/polygon.pyi +++ b/python/helpers/typeshed/stubs/shapely/shapely/geometry/polygon.pyi @@ -1,6 +1,6 @@ from collections.abc import Collection -from typing import Literal, NoReturn, TypeAlias, overload -from typing_extensions import Self +from typing import Literal, TypeAlias, overload +from typing_extensions import Never, Self from .base import BaseGeometry from .linestring import LineString, _ConvertibleToLineString @@ -39,7 +39,7 @@ class Polygon(BaseGeometry): @property def interiors(self) -> list[LinearRing] | InteriorRingSequence: ... @property - def coords(self) -> NoReturn: ... + def coords(self) -> Never: ... def svg(self, scale_factor: float = 1.0, fill_color: str | None = None, opacity: float | None = None) -> str: ... # type: ignore[override] @classmethod def from_bounds(cls, xmin: float, ymin: float, xmax: float, ymax: float) -> Self: ... diff --git a/python/helpers/typeshed/stubs/simplejson/@tests/stubtest_allowlist.txt b/python/helpers/typeshed/stubs/simplejson/@tests/stubtest_allowlist.txt index 84e705994309..ebb5d87976c4 100644 --- a/python/helpers/typeshed/stubs/simplejson/@tests/stubtest_allowlist.txt +++ b/python/helpers/typeshed/stubs/simplejson/@tests/stubtest_allowlist.txt @@ -2,6 +2,8 @@ simplejson.scanner.make_scanner simplejson.scanner.JSONDecodeError.__init__ simplejson.encoder.c_make_encoder +simplejson.encoder.c_encode_basestring +simplejson.encoder.py_encode_basestring simplejson.encoder.c_encode_basestring_ascii simplejson.encoder.py_encode_basestring_ascii diff --git a/python/helpers/typeshed/stubs/simplejson/METADATA.toml b/python/helpers/typeshed/stubs/simplejson/METADATA.toml index 63c9ff16b4b7..d88621057572 100644 --- a/python/helpers/typeshed/stubs/simplejson/METADATA.toml +++ b/python/helpers/typeshed/stubs/simplejson/METADATA.toml @@ -1,2 +1,2 @@ -version = "3.20.*" +version = "4.1.*" upstream-repository = "https://github.com/simplejson/simplejson" diff --git a/python/helpers/typeshed/stubs/simplejson/simplejson/__init__.pyi b/python/helpers/typeshed/stubs/simplejson/simplejson/__init__.pyi index 73dd284fbe41..b89f04f64fdf 100644 --- a/python/helpers/typeshed/stubs/simplejson/simplejson/__init__.pyi +++ b/python/helpers/typeshed/stubs/simplejson/simplejson/__init__.pyi @@ -124,6 +124,7 @@ def loads( object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, use_decimal: bool = False, allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value **kw: Any, ) -> Any: ... @overload @@ -138,6 +139,7 @@ def loads( object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, use_decimal: bool = False, allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value ) -> Any: ... @overload @@ -153,6 +155,7 @@ def load( object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, use_decimal: bool = False, allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value **kw: Any, ) -> Any: ... @overload @@ -167,6 +170,7 @@ def load( object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, use_decimal: bool = False, allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value ) -> Any: ... def simple_first(kv: tuple[_T, object]) -> tuple[bool, _T]: ... diff --git a/python/helpers/typeshed/stubs/simplejson/simplejson/decoder.pyi b/python/helpers/typeshed/stubs/simplejson/simplejson/decoder.pyi index 4afa6ea9360c..3fc18bc176e5 100644 --- a/python/helpers/typeshed/stubs/simplejson/simplejson/decoder.pyi +++ b/python/helpers/typeshed/stubs/simplejson/simplejson/decoder.pyi @@ -1,3 +1,4 @@ +from _typeshed import Incomplete from collections.abc import Callable from re import Match from typing import Any, Literal @@ -5,11 +6,17 @@ from typing import Any, Literal class JSONDecoder: encoding: str object_hook: Callable[[dict[Any, Any]], Any] | None + # transforms a list of (key, json_value) pairs to an arbitrary value + object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None parse_float: Callable[[str], Any] | None parse_int: Callable[[str], Any] | None parse_constant: Callable[[str], Any] | None strict: bool - object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None + array_hook: Callable[[list[Any]], Any] | None # transforms a JSON value to an arbitrary value + # They have many parameters, it might be better to use Protocol: + parse_object: Callable[..., tuple[Incomplete, int]] + parse_array: Callable[..., tuple[Incomplete, int]] + parse_string: Callable[..., tuple[Incomplete, int]] memo: dict[Any, Any] scan_once: Callable[[str, int], tuple[bool, int]] @@ -23,6 +30,7 @@ class JSONDecoder: strict: bool = True, object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None, allow_nan: bool = False, + array_hook: Callable[[list[Any]], Any] | None = None, # transforms a JSON value to an arbitrary value ) -> None: ... def decode(self, s: str, _w: Callable[[str, int], Match[str]] = ..., _PY3: Literal[True] = True) -> Any: ... def raw_decode( diff --git a/python/helpers/typeshed/stubs/simplejson/simplejson/encoder.pyi b/python/helpers/typeshed/stubs/simplejson/simplejson/encoder.pyi index 15378765980d..9f82016fe917 100644 --- a/python/helpers/typeshed/stubs/simplejson/simplejson/encoder.pyi +++ b/python/helpers/typeshed/stubs/simplejson/simplejson/encoder.pyi @@ -1,7 +1,8 @@ import re from _typeshed import SupportsRichComparison from collections.abc import Callable, Iterator -from typing import Any, Literal, NoReturn +from typing import Any +from typing_extensions import Never ESCAPE: re.Pattern[str] ESCAPE_ASCII: re.Pattern[str] @@ -51,10 +52,10 @@ class JSONEncoder: iterable_as_array: bool = False, ) -> None: ... def encode(self, o: Any) -> str: ... - def default(self, o: Any) -> NoReturn: ... + def default(self, o: Any) -> Never: ... def iterencode(self, o: Any) -> Iterator[str]: ... class JSONEncoderForHTML(JSONEncoder): ... -def encode_basestring(s: str | bytes, _PY3: Literal[True] = True, _q: str = '"') -> str: ... +def encode_basestring(s: str | bytes, /) -> str: ... def encode_basestring_ascii(s: str | bytes, /) -> str: ... diff --git a/python/helpers/typeshed/stubs/six/@tests/stubtest_allowlist.txt b/python/helpers/typeshed/stubs/six/@tests/stubtest_allowlist.txt index 83d20bf7bb4f..d1870c38df1e 100644 --- a/python/helpers/typeshed/stubs/six/@tests/stubtest_allowlist.txt +++ b/python/helpers/typeshed/stubs/six/@tests/stubtest_allowlist.txt @@ -27,6 +27,3 @@ six.Module_six_moves_urllib_robotparser # Belongs to `django.utils.six` six.iterlists - -# Unclear problems -six.callable diff --git a/python/helpers/typeshed/stubs/six/six/__init__.pyi b/python/helpers/typeshed/stubs/six/six/__init__.pyi index 3c67386b7d80..b137922b7482 100644 --- a/python/helpers/typeshed/stubs/six/six/__init__.pyi +++ b/python/helpers/typeshed/stubs/six/six/__init__.pyi @@ -1,15 +1,15 @@ -import builtins import operator import types import unittest from _typeshed import IdentityFunction, SupportsGetItem, Unused -from builtins import next as next +from builtins import callable as callable, next as next from collections.abc import Callable, ItemsView, Iterable, Iterator as _Iterator, KeysView, Mapping, ValuesView from functools import wraps as wraps from importlib.util import spec_from_loader as spec_from_loader from io import BytesIO as BytesIO, StringIO as StringIO from re import Pattern -from typing import Any, AnyStr, Literal, NoReturn, TypeVar, overload +from typing import Any, AnyStr, Literal, TypeVar, overload +from typing_extensions import Never from six import moves as moves @@ -32,8 +32,6 @@ binary_type = bytes MAXSIZE: int -callable = builtins.callable - def get_unbound_function(unbound: types.FunctionType) -> types.FunctionType: ... create_bound_method = types.MethodType @@ -79,8 +77,8 @@ def assertNotRegex(self: unittest.TestCase, text: AnyStr, expected_regex: AnyStr exec_ = exec -def reraise(tp: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None = None) -> NoReturn: ... -def raise_from(value: BaseException | type[BaseException], from_value: BaseException | None) -> NoReturn: ... +def reraise(tp: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None = None) -> Never: ... +def raise_from(value: BaseException | type[BaseException], from_value: BaseException | None) -> Never: ... print_ = print diff --git a/python/helpers/typeshed/stubs/tensorflow/tensorflow/python/__init__.pyi b/python/helpers/typeshed/stubs/tensorflow/tensorflow/python/__init__.pyi index 5b0f74feb261..3536a6f021c5 100644 --- a/python/helpers/typeshed/stubs/tensorflow/tensorflow/python/__init__.pyi +++ b/python/helpers/typeshed/stubs/tensorflow/tensorflow/python/__init__.pyi @@ -1 +1 @@ -def __getattr__(name: str): ... # incomplete module +def __getattr__(name: str, /): ... # incomplete module diff --git a/python/helpers/typeshed/stubs/tensorflow/tensorflow/python/keras/__init__.pyi b/python/helpers/typeshed/stubs/tensorflow/tensorflow/python/keras/__init__.pyi index 5b0f74feb261..3536a6f021c5 100644 --- a/python/helpers/typeshed/stubs/tensorflow/tensorflow/python/keras/__init__.pyi +++ b/python/helpers/typeshed/stubs/tensorflow/tensorflow/python/keras/__init__.pyi @@ -1 +1 @@ -def __getattr__(name: str): ... # incomplete module +def __getattr__(name: str, /): ... # incomplete module diff --git a/python/helpers/typeshed/stubs/tqdm/tqdm/asyncio.pyi b/python/helpers/typeshed/stubs/tqdm/tqdm/asyncio.pyi index 0d5605b31f0a..b665fcfeb728 100644 --- a/python/helpers/typeshed/stubs/tqdm/tqdm/asyncio.pyi +++ b/python/helpers/typeshed/stubs/tqdm/tqdm/asyncio.pyi @@ -1,8 +1,8 @@ from _typeshed import SupportsWrite from asyncio import Future from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Iterator, Mapping -from typing import NoReturn, TypeVar, overload -from typing_extensions import Self +from typing import TypeVar, overload +from typing_extensions import Never, Self from .std import tqdm as std_tqdm @@ -117,7 +117,7 @@ class tqdm_asyncio(std_tqdm[_T]): ) -> None: ... @overload def __init__( - self: tqdm_asyncio[NoReturn], + self: tqdm_asyncio[Never], iterable: None = None, desc: str | None = ..., total: float | None = ..., diff --git a/python/helpers/typeshed/stubs/tqdm/tqdm/contrib/discord.pyi b/python/helpers/typeshed/stubs/tqdm/tqdm/contrib/discord.pyi index 63a3a63dcbe6..0c6ba34e702e 100644 --- a/python/helpers/typeshed/stubs/tqdm/tqdm/contrib/discord.pyi +++ b/python/helpers/typeshed/stubs/tqdm/tqdm/contrib/discord.pyi @@ -1,7 +1,8 @@ from _typeshed import Incomplete, SupportsWrite from collections.abc import Iterable, Mapping from concurrent.futures import Future -from typing import NoReturn, TypeVar, overload +from typing import TypeVar, overload +from typing_extensions import Never from requests import Session @@ -65,7 +66,7 @@ class tqdm_discord(tqdm_auto[_T]): ) -> None: ... @overload def __init__( - self: tqdm_discord[NoReturn], + self: tqdm_discord[Never], iterable: None = None, desc: str | None = ..., total: float | None = ..., diff --git a/python/helpers/typeshed/stubs/tqdm/tqdm/contrib/slack.pyi b/python/helpers/typeshed/stubs/tqdm/tqdm/contrib/slack.pyi index f35a919f7a92..cd163bc1bc39 100644 --- a/python/helpers/typeshed/stubs/tqdm/tqdm/contrib/slack.pyi +++ b/python/helpers/typeshed/stubs/tqdm/tqdm/contrib/slack.pyi @@ -1,6 +1,7 @@ from _typeshed import Incomplete, SupportsWrite from collections.abc import Iterable, Mapping -from typing import NoReturn, TypeVar, overload +from typing import TypeVar, overload +from typing_extensions import Never from ..auto import tqdm as tqdm_auto from .utils_worker import MonoWorker @@ -55,7 +56,7 @@ class tqdm_slack(tqdm_auto[_T]): ) -> None: ... @overload def __init__( - self: tqdm_slack[NoReturn], + self: tqdm_slack[Never], iterable: None = None, desc: str | None = ..., total: float | None = ..., diff --git a/python/helpers/typeshed/stubs/tqdm/tqdm/contrib/telegram.pyi b/python/helpers/typeshed/stubs/tqdm/tqdm/contrib/telegram.pyi index 80d206b22b56..8fd56a284dea 100644 --- a/python/helpers/typeshed/stubs/tqdm/tqdm/contrib/telegram.pyi +++ b/python/helpers/typeshed/stubs/tqdm/tqdm/contrib/telegram.pyi @@ -1,6 +1,7 @@ from _typeshed import Incomplete, SupportsWrite from collections.abc import Iterable, Mapping -from typing import NoReturn, TypeVar, overload +from typing import TypeVar, overload +from typing_extensions import Never from ..auto import tqdm as tqdm_auto from .utils_worker import MonoWorker @@ -60,7 +61,7 @@ class tqdm_telegram(tqdm_auto[_T]): ) -> None: ... @overload def __init__( - self: tqdm_telegram[NoReturn], + self: tqdm_telegram[Never], iterable: None = None, desc: str | None = ..., total: float | None = ..., diff --git a/python/helpers/typeshed/stubs/tqdm/tqdm/gui.pyi b/python/helpers/typeshed/stubs/tqdm/tqdm/gui.pyi index c01e78ee0200..265cfa0cf418 100644 --- a/python/helpers/typeshed/stubs/tqdm/tqdm/gui.pyi +++ b/python/helpers/typeshed/stubs/tqdm/tqdm/gui.pyi @@ -1,6 +1,7 @@ from _typeshed import Incomplete, SupportsWrite from collections.abc import Iterable, Mapping -from typing import NoReturn, TypeVar, overload +from typing import TypeVar, overload +from typing_extensions import Never from .std import tqdm as std_tqdm @@ -57,7 +58,7 @@ class tqdm_gui(std_tqdm[_T]): ) -> None: ... @overload def __init__( - self: tqdm_gui[NoReturn], + self: tqdm_gui[Never], iterable: None = None, desc: str | None = ..., total: float | None = ..., diff --git a/python/helpers/typeshed/stubs/tqdm/tqdm/notebook.pyi b/python/helpers/typeshed/stubs/tqdm/tqdm/notebook.pyi index bfea206f3c72..a2b329235b79 100644 --- a/python/helpers/typeshed/stubs/tqdm/tqdm/notebook.pyi +++ b/python/helpers/typeshed/stubs/tqdm/tqdm/notebook.pyi @@ -1,6 +1,7 @@ from _typeshed import Incomplete, SupportsWrite from collections.abc import Iterable, Iterator, Mapping -from typing import NoReturn, TypeVar, overload +from typing import TypeVar, overload +from typing_extensions import Never from .std import tqdm as std_tqdm, trange as trange @@ -65,7 +66,7 @@ class tqdm_notebook(std_tqdm[_T]): ) -> None: ... @overload def __init__( - self: tqdm_notebook[NoReturn], + self: tqdm_notebook[Never], iterable: None = None, desc: str | None = ..., total: float | None = ..., diff --git a/python/helpers/typeshed/stubs/tqdm/tqdm/rich.pyi b/python/helpers/typeshed/stubs/tqdm/tqdm/rich.pyi index 37ee5d347e36..e470dec5529b 100644 --- a/python/helpers/typeshed/stubs/tqdm/tqdm/rich.pyi +++ b/python/helpers/typeshed/stubs/tqdm/tqdm/rich.pyi @@ -1,7 +1,8 @@ from _typeshed import Incomplete, SupportsWrite from abc import ABC, abstractmethod from collections.abc import Iterable, Mapping -from typing import NoReturn, TypeVar, overload, type_check_only +from typing import TypeVar, overload, type_check_only +from typing_extensions import Never from .std import tqdm as std_tqdm @@ -73,7 +74,7 @@ class tqdm_rich(std_tqdm[_T]): ) -> None: ... @overload def __init__( - self: tqdm_rich[NoReturn], + self: tqdm_rich[Never], iterable: None = None, desc: str | None = ..., total: float | None = ..., diff --git a/python/helpers/typeshed/stubs/tqdm/tqdm/std.pyi b/python/helpers/typeshed/stubs/tqdm/tqdm/std.pyi index c2743b03b3cf..761cdf0b809c 100644 --- a/python/helpers/typeshed/stubs/tqdm/tqdm/std.pyi +++ b/python/helpers/typeshed/stubs/tqdm/tqdm/std.pyi @@ -2,8 +2,8 @@ import contextlib from _typeshed import Incomplete, SupportsRead, SupportsWrite from collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping from types import TracebackType -from typing import Any, ClassVar, Generic, Literal, NoReturn, TypeVar, overload -from typing_extensions import Self +from typing import Any, ClassVar, Generic, Literal, TypeVar, overload +from typing_extensions import Never, Self from ._monitor import TMonitor from .utils import Comparable @@ -95,7 +95,7 @@ class tqdm(Comparable, Generic[_T]): ) -> None: ... @overload def __init__( - self: tqdm[NoReturn], + self: tqdm[Never], iterable: None = None, desc: str | None = None, total: float | None = None, diff --git a/python/helpers/typeshed/stubs/tqdm/tqdm/tk.pyi b/python/helpers/typeshed/stubs/tqdm/tqdm/tk.pyi index e4e4a956489d..c45457e323a7 100644 --- a/python/helpers/typeshed/stubs/tqdm/tqdm/tk.pyi +++ b/python/helpers/typeshed/stubs/tqdm/tqdm/tk.pyi @@ -1,6 +1,7 @@ from _typeshed import Incomplete, SupportsWrite from collections.abc import Iterable, Mapping -from typing import NoReturn, TypeVar, overload +from typing import TypeVar, overload +from typing_extensions import Never from .std import tqdm as std_tqdm @@ -45,7 +46,7 @@ class tqdm_tk(std_tqdm[_T]): ) -> None: ... @overload def __init__( - self: tqdm_tk[NoReturn], + self: tqdm_tk[Never], iterable: None = None, desc: str | None = ..., total: float | None = ..., diff --git a/python/helpers/typeshed/stubs/unidiff/METADATA.toml b/python/helpers/typeshed/stubs/unidiff/METADATA.toml index 972eb6704981..06c862c5cc73 100644 --- a/python/helpers/typeshed/stubs/unidiff/METADATA.toml +++ b/python/helpers/typeshed/stubs/unidiff/METADATA.toml @@ -1,2 +1,3 @@ version = "0.7.*" upstream-repository = "https://github.com/matiasb/python-unidiff" +obsolete-since = {version = "1.0.0", date = "2026-07-25"} diff --git a/python/helpers/typeshed/stubs/waitress/waitress/buffers.pyi b/python/helpers/typeshed/stubs/waitress/waitress/buffers.pyi index c8a356234623..fa4e9537ea0a 100644 --- a/python/helpers/typeshed/stubs/waitress/waitress/buffers.pyi +++ b/python/helpers/typeshed/stubs/waitress/waitress/buffers.pyi @@ -1,6 +1,7 @@ from _typeshed import ReadableBuffer from io import BufferedIOBase, BufferedRandom, BytesIO -from typing import Final, Literal, NoReturn +from typing import Final, Literal +from typing_extensions import Never COPY_BYTES: Final = 262144 STRBUF_LIMIT: Final = 8192 @@ -38,7 +39,7 @@ class ReadOnlyFileBasedBuffer(FileBasedBuffer): def __iter__(self) -> ReadOnlyFileBasedBuffer: ... def next(self) -> bytes | None: ... __next__ = next - def append(self, s: ReadableBuffer) -> NoReturn: ... + def append(self, s: ReadableBuffer) -> Never: ... class OverflowableBuffer: overflowed: bool diff --git a/python/helpers/typeshed/stubs/yt-dlp/METADATA.toml b/python/helpers/typeshed/stubs/yt-dlp/METADATA.toml index 8b49165a231f..d29f3acb0729 100644 --- a/python/helpers/typeshed/stubs/yt-dlp/METADATA.toml +++ b/python/helpers/typeshed/stubs/yt-dlp/METADATA.toml @@ -1,3 +1,2 @@ -version = "2026.3.17" +version = "2026.7.4" upstream-repository = "https://github.com/yt-dlp/yt-dlp" -dependencies = ["websockets"] diff --git a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/YoutubeDL.pyi b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/YoutubeDL.pyi index 4648784a5beb..1fafc135d3cb 100644 --- a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/YoutubeDL.pyi +++ b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/YoutubeDL.pyi @@ -60,7 +60,9 @@ class YoutubeDL: def escape_outtmpl(outtmpl: str) -> str: ... @classmethod def validate_outtmpl(cls, outtmpl: str) -> ValueError | None: ... - def prepare_outtmpl(self, outtmpl: str, info_dict: _InfoDict, sanitize: bool = False) -> tuple[str, dict[str, Any]]: ... + def prepare_outtmpl( + self, outtmpl: str, info_dict: _InfoDict, sanitize: bool = False, *, _exec: bool = False + ) -> tuple[str, dict[str, Any]]: ... def evaluate_outtmpl(self, outtmpl: str, info_dict: _InfoDict, sanitize: bool = False) -> str: ... def prepare_filename( self, info_dict: _InfoDict, dir_type: str = "", *, outtmpl: str | None = None, warn: bool = False diff --git a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/__init__.pyi b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/__init__.pyi index d0b4e77df451..3cb378a9a436 100644 --- a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/__init__.pyi +++ b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/__init__.pyi @@ -38,9 +38,7 @@ class _ExternalDownloader(TypedDict, total=False): ftp: str http: str m3u8: str - mms: str rtmp: str - rtsp: str @type_check_only class _DownloadRange(TypedDict): diff --git a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/downloader/__init__.pyi b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/downloader/__init__.pyi index dcffac8ec8dd..87b5466a3d2f 100644 --- a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/downloader/__init__.pyi +++ b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/downloader/__init__.pyi @@ -1,5 +1,5 @@ from collections.abc import Mapping -from typing import Any, Literal, TypeAlias +from typing import Any from ..extractor.common import _InfoDict from ..utils._utils import NO_DEFAULT @@ -7,24 +7,11 @@ from .common import FileDownloader __all__ = ["FileDownloader", "get_suitable_downloader", "shorten_protocol_name"] -_Protocol: TypeAlias = Literal[ - "dash_frag_urls", - "ftps", - "http_dash_segments", - "http_dash_segments_generator", - "https", - "m3u8", - "m3u8_frag_urls", - "m3u8_native", - "rtmp_ffmpeg", - "websocket_frag", -] - def get_suitable_downloader( info_dict: _InfoDict, params: Mapping[str, Any] = {}, default: FileDownloader | type[NO_DEFAULT] = ..., - protocol: _Protocol | None = None, + protocol: str | None = None, to_stdout: bool = False, ) -> FileDownloader: ... -def shorten_protocol_name(proto: _Protocol, simplify: bool = False) -> str: ... +def shorten_protocol_name(proto: str, simplify: bool = False) -> str: ... diff --git a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/downloader/external.pyi b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/downloader/external.pyi index 341481dbfad2..22a3ad69e44d 100644 --- a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/downloader/external.pyi +++ b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/downloader/external.pyi @@ -1,7 +1,7 @@ import enum import functools from _typeshed import Unused -from collections.abc import Iterable, Mapping +from collections.abc import Mapping from typing import Any, Literal from ..extractor.common import _InfoDict @@ -29,6 +29,8 @@ class ExternalFD(FragmentFD): class CurlFD(ExternalFD): AVAILABLE_OPT: str + @classmethod + def available(cls, path: str | None = None) -> str | Literal[False]: ... class AxelFD(ExternalFD): AVAILABLE_OPT: str @@ -39,9 +41,6 @@ class WgetFD(ExternalFD): class Aria2cFD(ExternalFD): AVAILABLE_OPT: str SUPPORTED_PROTOCOLS: tuple[str, ...] - @staticmethod - def supports_manifest(manifest: str) -> bool: ... - def aria2c_rpc(self, rpc_port: int, rpc_secret: str, method: str, params: Iterable[str] = ()) -> Any: ... class HttpieFD(ExternalFD): AVAILABLE_OPT: str diff --git a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/downloader/rtsp.pyi b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/downloader/rtsp.pyi deleted file mode 100644 index 313d7c09fcd6..000000000000 --- a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/downloader/rtsp.pyi +++ /dev/null @@ -1,5 +0,0 @@ -from ..extractor.common import _InfoDict -from .common import FileDownloader - -class RtspFD(FileDownloader): - def real_download(self, filename: str, info_dict: _InfoDict) -> bool: ... diff --git a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/extractor/common.pyi b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/extractor/common.pyi index 821f045b0bf3..20394eb26203 100644 --- a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/extractor/common.pyi +++ b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/extractor/common.pyi @@ -228,7 +228,7 @@ class InfoExtractor: def report_drm(self, video_id: str, partial: bool) -> None: ... def report_extraction(self, id_or_name: str) -> None: ... - def report_download_webpage(self, video_id: str) -> None: ... + def report_download_webpage(self, video_id: str, *, note: str | None = None) -> None: ... def report_age_confirmation(self) -> None: ... def report_login(self) -> None: ... def raise_login_required( diff --git a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/extractor/commonprotocols.pyi b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/extractor/commonprotocols.pyi index a22cf411f683..1d0dc15ed1b0 100644 --- a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/extractor/commonprotocols.pyi +++ b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/extractor/commonprotocols.pyi @@ -5,8 +5,5 @@ from .common import InfoExtractor class RtmpIE(InfoExtractor): IE_DESC: ClassVar[bool] -class MmsIE(InfoExtractor): - IE_DESC: ClassVar[bool] - class ViewSourceIE(InfoExtractor): IE_DESC: ClassVar[bool] diff --git a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/jsinterp.pyi b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/jsinterp.pyi index 2bfb46228a6b..046586574c09 100644 --- a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/jsinterp.pyi +++ b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/jsinterp.pyi @@ -1,7 +1,8 @@ import collections import types from collections.abc import Callable, Collection, Iterable, Mapping -from typing import Any, NoReturn, TypeAlias +from typing import Any, TypeAlias +from typing_extensions import Never from yt_dlp.extractor.common import InfoExtractor from yt_dlp.utils._utils import function_with_repr @@ -25,7 +26,7 @@ class JS_Throw(ExtractorError): class LocalNameSpace(collections.ChainMap[str, Any]): def __setitem__(self, key: str, value: Any) -> None: ... - def __delitem__(self, key: str) -> NoReturn: ... + def __delitem__(self, key: str) -> Never: ... def set_local(self, key: str, value: Any) -> None: ... def get_local(self, key: str) -> Any: ... diff --git a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/postprocessor/common.pyi b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/postprocessor/common.pyi index bb02ab145873..880fa48ecbba 100644 --- a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/postprocessor/common.pyi +++ b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/postprocessor/common.pyi @@ -16,14 +16,7 @@ class PostProcessor(metaclass=PostProcessorMetaClass): @classmethod def pp_key(cls) -> str: ... def to_screen( - self, - text: str, - prefix: bool = True, - *, - message: str, - skip_eol: bool = False, - quiet: bool | None = None, - only_once: bool = False, + self, text: str, prefix: bool = True, *, skip_eol: bool = False, quiet: bool | None = None, only_once: bool = False ) -> None: ... def report_warning(self, text: str, only_once: bool = False) -> None: ... def deprecation_warning(self, msg: str) -> None: ... diff --git a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/update.pyi b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/update.pyi index bd287ac6212e..70b7fae5ad66 100644 --- a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/update.pyi +++ b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/update.pyi @@ -9,11 +9,11 @@ __all__ = ["Updater"] @dataclass class UpdateInfo: tag: str - version: str | None = ... - requested_version: str | None = ... - commit: str | None = ... - binary_name: str | None = ... - checksum: str | None = ... + version: str | None = None + requested_version: str | None = None + commit: str | None = None + binary_name: str | None = None + checksum: str | None = None class Updater: ydl: YoutubeDL diff --git a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/utils/__init__.pyi b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/utils/__init__.pyi index f4fea0224c81..a33675e077b3 100644 --- a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/utils/__init__.pyi +++ b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/utils/__init__.pyi @@ -1,269 +1,3 @@ -from ._deprecated import ( - bytes_to_intlist as bytes_to_intlist, - compiled_regex_type as compiled_regex_type, - intlist_to_bytes as intlist_to_bytes, - jwt_encode_hs256 as jwt_encode_hs256, -) -from ._utils import ( - ACCENT_CHARS as ACCENT_CHARS, - BOMS as BOMS, - DATE_FORMATS as DATE_FORMATS, - DATE_FORMATS_DAY_FIRST as DATE_FORMATS_DAY_FIRST, - DATE_FORMATS_MONTH_FIRST as DATE_FORMATS_MONTH_FIRST, - DEFAULT_OUTTMPL as DEFAULT_OUTTMPL, - DOT_DESKTOP_LINK_TEMPLATE as DOT_DESKTOP_LINK_TEMPLATE, - DOT_URL_LINK_TEMPLATE as DOT_URL_LINK_TEMPLATE, - DOT_WEBLOC_LINK_TEMPLATE as DOT_WEBLOC_LINK_TEMPLATE, - ENGLISH_MONTH_NAMES as ENGLISH_MONTH_NAMES, - IDENTITY as IDENTITY, - JSON_LD_RE as JSON_LD_RE, - KNOWN_EXTENSIONS as KNOWN_EXTENSIONS, - LINK_TEMPLATES as LINK_TEMPLATES, - MEDIA_EXTENSIONS as MEDIA_EXTENSIONS, - MONTH_NAMES as MONTH_NAMES, - NO_DEFAULT as NO_DEFAULT, - NUMBER_RE as NUMBER_RE, - OUTTMPL_TYPES as OUTTMPL_TYPES, - PACKED_CODES_RE as PACKED_CODES_RE, - POSTPROCESS_WHEN as POSTPROCESS_WHEN, - STR_FORMAT_RE_TMPL as STR_FORMAT_RE_TMPL, - STR_FORMAT_TYPES as STR_FORMAT_TYPES, - TIMEZONE_NAMES as TIMEZONE_NAMES, - TV_PARENTAL_GUIDELINES as TV_PARENTAL_GUIDELINES, - US_RATINGS as US_RATINGS, - WINDOWS_VT_MODE as WINDOWS_VT_MODE, - Config as Config, - ContentTooShortError as ContentTooShortError, - DateRange as DateRange, - DownloadCancelled as DownloadCancelled, - DownloadError as DownloadError, - EntryNotInPlaylist as EntryNotInPlaylist, - ExistingVideoReached as ExistingVideoReached, - ExtractorError as ExtractorError, - FormatSorter as FormatSorter, - GeoRestrictedError as GeoRestrictedError, - GeoUtils as GeoUtils, - HTMLAttributeParser as HTMLAttributeParser, - HTMLBreakOnClosingTagParser as HTMLBreakOnClosingTagParser, - HTMLListAttrsParser as HTMLListAttrsParser, - InAdvancePagedList as InAdvancePagedList, - ISO639Utils as ISO639Utils, - ISO3166Utils as ISO3166Utils, - LazyList as LazyList, - LenientJSONDecoder as LenientJSONDecoder, - LockingUnsupportedError as LockingUnsupportedError, - MaxDownloadsReached as MaxDownloadsReached, - Namespace as Namespace, - OnDemandPagedList as OnDemandPagedList, - PagedList as PagedList, - PlaylistEntries as PlaylistEntries, - Popen as Popen, - PostProcessingError as PostProcessingError, - ReExtractInfo as ReExtractInfo, - RegexNotFoundError as RegexNotFoundError, - RejectedVideoReached as RejectedVideoReached, - RetryManager as RetryManager, - SameFileError as SameFileError, - ThrottledDownload as ThrottledDownload, - UnavailableVideoError as UnavailableVideoError, - UnsupportedError as UnsupportedError, - UserNotLive as UserNotLive, - XAttrMetadataError as XAttrMetadataError, - XAttrUnavailableError as XAttrUnavailableError, - YoutubeDLError as YoutubeDLError, - age_restricted as age_restricted, - args_to_str as args_to_str, - ass_subtitles_timecode as ass_subtitles_timecode, - base_url as base_url, - bool_or_none as bool_or_none, - bug_reports_message as bug_reports_message, - bytes_to_long as bytes_to_long, - cached_method as cached_method, - caesar as caesar, - check_executable as check_executable, - classproperty as classproperty, - clean_html as clean_html, - clean_podcast_url as clean_podcast_url, - cli_bool_option as cli_bool_option, - cli_configuration_args as cli_configuration_args, - cli_option as cli_option, - cli_valueless_option as cli_valueless_option, - date_formats as date_formats, - date_from_str as date_from_str, - datetime_add_months as datetime_add_months, - datetime_from_str as datetime_from_str, - datetime_round as datetime_round, - decode_base_n as decode_base_n, - decode_packed_codes as decode_packed_codes, - deprecation_warning as deprecation_warning, - detect_exe_version as detect_exe_version, - determine_ext as determine_ext, - determine_file_encoding as determine_file_encoding, - determine_protocol as determine_protocol, - dfxp2srt as dfxp2srt, - download_range_func as download_range_func, - encode_base_n as encode_base_n, - encode_compat_str as encode_compat_str, - encode_data_uri as encode_data_uri, - encodeArgument as encodeArgument, - error_to_str as error_to_str, - escapeHTML as escapeHTML, - expand_path as expand_path, - ext2mimetype as ext2mimetype, - extract_attributes as extract_attributes, - extract_basic_auth as extract_basic_auth, - extract_timezone as extract_timezone, - filesize_from_tbr as filesize_from_tbr, - filter_dict as filter_dict, - find_available_port as find_available_port, - find_xpath_attr as find_xpath_attr, - fix_xml_ampersands as fix_xml_ampersands, - float_or_none as float_or_none, - format_bytes as format_bytes, - format_decimal_suffix as format_decimal_suffix, - format_field as format_field, - formatSeconds as formatSeconds, - frange as frange, - function_with_repr as function_with_repr, - get_compatible_ext as get_compatible_ext, - get_domain as get_domain, - get_element_by_attribute as get_element_by_attribute, - get_element_by_class as get_element_by_class, - get_element_by_id as get_element_by_id, - get_element_html_by_attribute as get_element_html_by_attribute, - get_element_html_by_class as get_element_html_by_class, - get_element_html_by_id as get_element_html_by_id, - get_element_text_and_html_by_tag as get_element_text_and_html_by_tag, - get_elements_by_attribute as get_elements_by_attribute, - get_elements_by_class as get_elements_by_class, - get_elements_html_by_attribute as get_elements_html_by_attribute, - get_elements_html_by_class as get_elements_html_by_class, - get_elements_text_and_html_by_attribute as get_elements_text_and_html_by_attribute, - get_exe_version as get_exe_version, - get_executable_path as get_executable_path, - get_filesystem_encoding as get_filesystem_encoding, - get_system_config_dirs as get_system_config_dirs, - get_user_config_dirs as get_user_config_dirs, - get_windows_version as get_windows_version, - hyphenate_date as hyphenate_date, - int_or_none as int_or_none, - iri_to_uri as iri_to_uri, - is_html as is_html, - is_iterable_like as is_iterable_like, - is_outdated_version as is_outdated_version, - is_path_like as is_path_like, - join_nonempty as join_nonempty, - js_to_json as js_to_json, - jwt_decode_hs256 as jwt_decode_hs256, - jwt_encode as jwt_encode, - limit_length as limit_length, - locked_file as locked_file, - long_to_bytes as long_to_bytes, - lookup_unit_table as lookup_unit_table, - lowercase_escape as lowercase_escape, - make_archive_id as make_archive_id, - make_dir as make_dir, - match_filter_func as match_filter_func, - match_str as match_str, - merge_dicts as merge_dicts, - merge_headers as merge_headers, - mimetype2ext as mimetype2ext, - month_by_abbreviation as month_by_abbreviation, - month_by_name as month_by_name, - multipart_encode as multipart_encode, - netrc_from_content as netrc_from_content, - number_of_digits as number_of_digits, - ohdave_rsa_encrypt as ohdave_rsa_encrypt, - orderedSet as orderedSet, - orderedSet_from_options as orderedSet_from_options, - parse_age_limit as parse_age_limit, - parse_bitrate as parse_bitrate, - parse_bytes as parse_bytes, - parse_codecs as parse_codecs, - parse_count as parse_count, - parse_dfxp_time_expr as parse_dfxp_time_expr, - parse_duration as parse_duration, - parse_filesize as parse_filesize, - parse_http_range as parse_http_range, - parse_iso8601 as parse_iso8601, - parse_list as parse_list, - parse_m3u8_attributes as parse_m3u8_attributes, - parse_qs as parse_qs, - parse_resolution as parse_resolution, - partial_application as partial_application, - pkcs1pad as pkcs1pad, - preferredencoding as preferredencoding, - prepend_extension as prepend_extension, - qualities as qualities, - random_birthday as random_birthday, - random_uuidv4 as random_uuidv4, - read_batch_urls as read_batch_urls, - read_stdin as read_stdin, - remove_end as remove_end, - remove_quotes as remove_quotes, - remove_start as remove_start, - remove_terminal_sequences as remove_terminal_sequences, - render_table as render_table, - replace_extension as replace_extension, - rot47 as rot47, - sanitize_filename as sanitize_filename, - sanitize_open as sanitize_open, - sanitize_path as sanitize_path, - sanitize_url as sanitize_url, - scale_thumbnails_to_max_format_width as scale_thumbnails_to_max_format_width, - setproctitle as setproctitle, - shell_quote as shell_quote, - smuggle_url as smuggle_url, - srt_subtitles_timecode as srt_subtitles_timecode, - str_or_none as str_or_none, - str_to_int as str_to_int, - strftime_or_none as strftime_or_none, - strip_jsonp as strip_jsonp, - strip_or_none as strip_or_none, - subtitles_filename as subtitles_filename, - supports_terminal_sequences as supports_terminal_sequences, - system_identifier as system_identifier, - time_seconds as time_seconds, - timeconvert as timeconvert, - timetuple_from_msec as timetuple_from_msec, - to_high_limit_path as to_high_limit_path, - truncate_string as truncate_string, - try_call as try_call, - try_get as try_get, - unescapeHTML as unescapeHTML, - unified_strdate as unified_strdate, - unified_timestamp as unified_timestamp, - unsmuggle_url as unsmuggle_url, - update_url as update_url, - update_url_query as update_url_query, - uppercase_escape as uppercase_escape, - url_basename as url_basename, - url_or_none as url_or_none, - urlencode_postdata as urlencode_postdata, - urlhandle_detect_ext as urlhandle_detect_ext, - urljoin as urljoin, - urshift as urshift, - variadic as variadic, - version_tuple as version_tuple, - windows_enable_vt_mode as windows_enable_vt_mode, - write_json_file as write_json_file, - write_string as write_string, - write_xattr as write_xattr, - xpath_attr as xpath_attr, - xpath_element as xpath_element, - xpath_text as xpath_text, - xpath_with_ns as xpath_with_ns, - ytdl_is_updateable as ytdl_is_updateable, -) -from .traversal import ( - dict_get as dict_get, - find_element as find_element, - find_elements as find_elements, - get_first as get_first, - require as require, - subs_list_to_dict as subs_list_to_dict, - traverse_obj as traverse_obj, - trim_str as trim_str, - unpack as unpack, - value as value, -) +from ._deprecated import * +from ._utils import * +from .traversal import * diff --git a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/utils/_deprecated.pyi b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/utils/_deprecated.pyi index 9d872396fb01..5f20b62a2fb0 100644 --- a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/utils/_deprecated.pyi +++ b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/utils/_deprecated.pyi @@ -1,6 +1,7 @@ import re -from collections.abc import Mapping -from typing import Any +from collections.abc import Callable, Mapping +from os import PathLike +from typing import Any, AnyStr from typing_extensions import deprecated @deprecated("Use `list` instead.") @@ -9,5 +10,7 @@ def bytes_to_intlist(bs: bytes) -> list[int]: ... def intlist_to_bytes(xs: list[int]) -> bytes: ... @deprecated("Use `yt_dlp.utils.jwt_encode` instead.") def jwt_encode_hs256(payload_data: Any, key: str, headers: Mapping[str, Any] = {}) -> bytes: ... # Passed to json.dumps(). +@deprecated("Use `yt_dlp.utils.make_parent_dirs` instead.") +def make_dir(path: PathLike[AnyStr], to_screen: Callable[[str], Any] | None = None) -> bool: ... compiled_regex_type: type[re.Pattern[Any]] diff --git a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/utils/_utils.pyi b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/utils/_utils.pyi index e95a5a4c0286..ea5d96e131ea 100644 --- a/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/utils/_utils.pyi +++ b/python/helpers/typeshed/stubs/yt-dlp/yt_dlp/utils/_utils.pyi @@ -269,6 +269,7 @@ class XAttrMetadataError(YoutubeDLError): def __init__(self, code: str | None = None, msg: str = "Unknown error") -> None: ... class XAttrUnavailableError(YoutubeDLError): ... +class UnsafeExecExpansionError(YoutubeDLError): ... def is_path_like(f: Any) -> bool: ... # Type checker. def extract_timezone(date_str: str, default: Any = None) -> tuple[timedelta, str]: ... # Any or type[NO_DEFAULT] @@ -330,7 +331,7 @@ def lookup_unit_table(unit_table: Mapping[str, int], s: str, strict: bool = Fals def parse_bytes(s: str) -> int: ... def parse_filesize(s: str | None) -> int | None: ... def parse_count(s: str | None) -> str | None: ... -def parse_resolution(s: str, *, lenient: bool = False) -> dict[str, int]: ... +def parse_resolution(s: str, *, lenient: bool = False, parse_fps: bool = False) -> dict[str, int]: ... def parse_bitrate(s: str) -> int: ... def month_by_name(name: str, lang: str = "en") -> str | None: ... def month_by_abbreviation(abbrev: str) -> str | None: ... @@ -561,7 +562,7 @@ DOT_WEBLOC_LINK_TEMPLATE: Final[str] DOT_DESKTOP_LINK_TEMPLATE: Final[str] LINK_TEMPLATES: Final[Mapping[str, str]] -def iri_to_uri(iri: str) -> str: ... +def iri_to_uri(iri: str, *, allowed_schemes: Iterable[str] = ("http", "https")) -> str: ... def to_high_limit_path(path: PathLike[AnyStr]) -> str: ... def format_field( obj: Mapping[str, Any] | Sequence[Any], @@ -573,7 +574,7 @@ def format_field( ) -> str: ... def clean_podcast_url(url: str) -> str: ... def random_uuidv4() -> str: ... -def make_dir(path: PathLike[AnyStr], to_screen: Callable[[str], Any] | None = None) -> bool: ... +def make_parent_dirs(path: PathLike[AnyStr]) -> None: ... def get_executable_path() -> str: ... def get_user_config_dirs(package_name: str) -> Iterator[str]: ... def get_system_config_dirs(package_name: str) -> Iterator[str]: ... @@ -633,7 +634,7 @@ class _UnsafeExtensionError(Exception): extension: str def __init__(self, extension: str, /) -> None: ... @classmethod - def sanitize_extension(cls, extension: str, /, *, prepend: bool = False) -> str: ... + def sanitize_extension(cls, extension: str, /, *, prepend: bool = False, _allowed_exts: Iterable[str] = ()) -> str: ... class RetryManager: attempt: int @@ -726,7 +727,7 @@ class Popen(subprocess.Popen[AnyStr]): def kill(self, *, timeout: int = 0) -> None: ... # kwargs passed to cls.__init__(). @classmethod - def run(cls, *args: Any, timeout: int | None = None, **kwargs: Any) -> tuple[AnyStr, AnyStr]: ... + def run(cls, *args: Any, timeout: int | None = None, input: AnyStr | None = None, **kwargs: Any) -> tuple[AnyStr, AnyStr]: ... class classproperty: # args passed to func(). diff --git a/python/helpers/typeshed/stubs/zstd/METADATA.toml b/python/helpers/typeshed/stubs/zstd/METADATA.toml index fbc3a5a5f5c2..a8c83583b850 100644 --- a/python/helpers/typeshed/stubs/zstd/METADATA.toml +++ b/python/helpers/typeshed/stubs/zstd/METADATA.toml @@ -1,2 +1,7 @@ version = "~=1.5.7.3" upstream-repository = "https://github.com/sergey-dryabzhinsky/python-zstd" + +[tool.stubtest] +# Temporarily disabled until release 1.5.7.3 returns to PyPI +# https://github.com/python/typeshed/pull/16057 +skip = true diff --git a/python/helpers/typeshed/tests/stubtest_third_party.py b/python/helpers/typeshed/tests/stubtest_third_party.py index 70bb8d0c182a..fa7d2906cab3 100644 --- a/python/helpers/typeshed/tests/stubtest_third_party.py +++ b/python/helpers/typeshed/tests/stubtest_third_party.py @@ -13,7 +13,7 @@ from pathlib import Path from shutil import rmtree from textwrap import dedent from time import time -from typing import NoReturn +from typing_extensions import Never from ts_utils.metadata import NoSuchStubError, get_recursive_requirements, read_metadata from ts_utils.mypy import mypy_configuration_from_distribution, temporary_mypy_config_file @@ -392,7 +392,7 @@ def print_command_output(e: subprocess.CalledProcessError | subprocess.Completed print(e.stderr.decode(), end="") -def main() -> NoReturn: +def main() -> Never: parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", action="store_true", help="verbose output") parser.add_argument("--num-shards", type=int, default=1)